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,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/CodeGenBringUpTests/ArrayExc_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="ArrayExc.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="ArrayExc.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/GC/Features/LOHCompaction/lohcompactapi.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <GCStressIncompatible>true</GCStressIncompatible> <!-- Test will timeout on Unix --> <IsLongRunningGCTest>true</IsLongRunningGCTest> </PropertyGroup> <ItemGroup> <Compile Include="lohcompactapi.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <GCStressIncompatible>true</GCStressIncompatible> <!-- Test will timeout on Unix --> <IsLongRunningGCTest>true</IsLongRunningGCTest> </PropertyGroup> <ItemGroup> <Compile Include="lohcompactapi.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Regression/JitBlue/GitHub_19149/GitHub_19149.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Bug report thanks to @mgravell // // JIT bug affecting how fixed buffers are handled // // Affects: netcoreapp2.1, debug and release // Does not seem to affect: netcoreapp2.0, net47 // // the idea behind CommandBytes is that it is a fixed-sized string-like thing // used for matching commands; it is *implemented* as a fixed buffer // of **longs**, but: the first byte of the first element is coerced into // a byte and used to store the length; the actual text payload (ASCII) // starts at the second byte of the first element // // as far as I can tell, it is all validly implemented, and it works fine // in isolation, however: when used in a dictionary, it goes bad; // - items not being found despite having GetHashCode and Equals match // - items over 1 chunk size becoming corrupted (see: ToInnerString) // // however, if I replace the fixed buffer with the same number of // regular fields (_c0,_c1,_c2) and use *all the same code*, it // all works correctly! // // The "Main" method populates a dictionary in the expected way, // then attempts to find things - either via TryGetValue or manually; // it then compares the contents // // Yes, this code is evil; it is for a very specific optimized scenario. using System; using System.Collections.Generic; using System.Text; unsafe struct CommandBytes : IEquatable<CommandBytes> { private const int ChunkLength = 3; public const int MaxLength = (ChunkLength * 8) - 1; fixed long _chunks[ChunkLength]; public override int GetHashCode() { fixed (long* lPtr = _chunks) { var hashCode = -1923861349; long* x = lPtr; for (int i = 0; i < ChunkLength; i++) { hashCode = hashCode * -1521134295 + (*x++).GetHashCode(); } return hashCode; } } public override string ToString() { fixed (long* lPtr = _chunks) { var bPtr = (byte*)lPtr; return Encoding.ASCII.GetString(bPtr + 1, bPtr[0]); } } public int Length { get { fixed (long* lPtr = _chunks) { var bPtr = (byte*)lPtr; return bPtr[0]; } } } public byte this[int index] { get { fixed (long* lPtr = _chunks) { byte* bPtr = (byte*)lPtr; int len = bPtr[0]; if (index < 0 || index >= len) throw new IndexOutOfRangeException(); return bPtr[index + 1]; } } } public CommandBytes(string value) { value = value.ToLowerInvariant(); var len = Encoding.ASCII.GetByteCount(value); if (len > MaxLength) throw new ArgumentOutOfRangeException("Maximum command length exceeed"); fixed (long* lPtr = _chunks) { Clear(lPtr); byte* bPtr = (byte*)lPtr; bPtr[0] = (byte)len; fixed (char* cPtr = value) { Encoding.ASCII.GetBytes(cPtr, value.Length, bPtr + 1, len); } } } public override bool Equals(object obj) => obj is CommandBytes cb && Equals(cb); public string ToInnerString() { fixed (long* lPtr = _chunks) { long* x = lPtr; var sb = new StringBuilder(); for (int i = 0; i < ChunkLength; i++) { if (sb.Length != 0) sb.Append(','); sb.Append(*x++); } return sb.ToString(); } } public bool Equals(CommandBytes value) { fixed (long* lPtr = _chunks) { long* x = lPtr; long* y = value._chunks; for (int i = 0; i < ChunkLength; i++) { if (*x++ != *y++) return false; } return true; } } private static void Clear(long* ptr) { for (int i = 0; i < ChunkLength; i++) { *ptr++ = 0L; } } } static class Program { static int Main() { var lookup = new Dictionary<CommandBytes, string>(); void Add(string val) { var cb = new CommandBytes(val); // prove we didn't screw up if (cb.ToString() != val) throw new InvalidOperationException("oops!"); lookup.Add(cb, val); } Add("client"); Add("cluster"); Add("command"); Add("config"); Add("dbsize"); Add("decr"); Add("del"); Add("echo"); Add("exists"); Add("flushall"); Add("flushdb"); Add("get"); Add("incr"); Add("incrby"); Add("info"); Add("keys"); Add("llen"); Add("lpop"); Add("lpush"); Add("lrange"); Add("memory"); Add("mget"); Add("mset"); Add("ping"); Add("quit"); Add("role"); Add("rpop"); Add("rpush"); Add("sadd"); Add("scard"); Add("select"); Add("set"); Add("shutdown"); Add("sismember"); Add("spop"); Add("srem"); Add("strlen"); Add("subscribe"); Add("time"); Add("unlink"); Add("unsubscribe"); bool HuntFor(string lookFor) { Console.WriteLine($"Looking for: '{lookFor}'"); var hunt = new CommandBytes(lookFor); bool result = lookup.TryGetValue(hunt, out var found); if (result) { Console.WriteLine($"Found via TryGetValue: '{found}'"); } else { Console.WriteLine("**NOT FOUND** via TryGetValue"); } Console.WriteLine("looking manually"); foreach (var pair in lookup) { if (pair.Value == lookFor) { Console.WriteLine($"Found manually: '{pair.Value}'"); var key = pair.Key; void Compare<T>(string caption, Func<CommandBytes, T> func) { T x = func(hunt), y = func(key); Console.WriteLine($"{caption}: {EqualityComparer<T>.Default.Equals(x, y)}, '{x}' vs '{y}'"); } Compare("GetHashCode", _ => _.GetHashCode()); Compare("ToString", _ => _.ToString()); Compare("Length", _ => _.Length); Compare("ToInnerString", _ => _.ToInnerString()); Console.WriteLine($"Equals: {key.Equals(hunt)}, {hunt.Equals(key)}"); var eq = EqualityComparer<CommandBytes>.Default; Console.WriteLine($"EqualityComparer: {eq.Equals(key, hunt)}, {eq.Equals(hunt, key)}"); Compare("eq GetHashCode", _ => eq.GetHashCode(_)); } } Console.WriteLine(); return result; } bool result1 = HuntFor("ping"); bool result2 = HuntFor("subscribe"); return (result1 && result2) ? 100 : -1; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Bug report thanks to @mgravell // // JIT bug affecting how fixed buffers are handled // // Affects: netcoreapp2.1, debug and release // Does not seem to affect: netcoreapp2.0, net47 // // the idea behind CommandBytes is that it is a fixed-sized string-like thing // used for matching commands; it is *implemented* as a fixed buffer // of **longs**, but: the first byte of the first element is coerced into // a byte and used to store the length; the actual text payload (ASCII) // starts at the second byte of the first element // // as far as I can tell, it is all validly implemented, and it works fine // in isolation, however: when used in a dictionary, it goes bad; // - items not being found despite having GetHashCode and Equals match // - items over 1 chunk size becoming corrupted (see: ToInnerString) // // however, if I replace the fixed buffer with the same number of // regular fields (_c0,_c1,_c2) and use *all the same code*, it // all works correctly! // // The "Main" method populates a dictionary in the expected way, // then attempts to find things - either via TryGetValue or manually; // it then compares the contents // // Yes, this code is evil; it is for a very specific optimized scenario. using System; using System.Collections.Generic; using System.Text; unsafe struct CommandBytes : IEquatable<CommandBytes> { private const int ChunkLength = 3; public const int MaxLength = (ChunkLength * 8) - 1; fixed long _chunks[ChunkLength]; public override int GetHashCode() { fixed (long* lPtr = _chunks) { var hashCode = -1923861349; long* x = lPtr; for (int i = 0; i < ChunkLength; i++) { hashCode = hashCode * -1521134295 + (*x++).GetHashCode(); } return hashCode; } } public override string ToString() { fixed (long* lPtr = _chunks) { var bPtr = (byte*)lPtr; return Encoding.ASCII.GetString(bPtr + 1, bPtr[0]); } } public int Length { get { fixed (long* lPtr = _chunks) { var bPtr = (byte*)lPtr; return bPtr[0]; } } } public byte this[int index] { get { fixed (long* lPtr = _chunks) { byte* bPtr = (byte*)lPtr; int len = bPtr[0]; if (index < 0 || index >= len) throw new IndexOutOfRangeException(); return bPtr[index + 1]; } } } public CommandBytes(string value) { value = value.ToLowerInvariant(); var len = Encoding.ASCII.GetByteCount(value); if (len > MaxLength) throw new ArgumentOutOfRangeException("Maximum command length exceeed"); fixed (long* lPtr = _chunks) { Clear(lPtr); byte* bPtr = (byte*)lPtr; bPtr[0] = (byte)len; fixed (char* cPtr = value) { Encoding.ASCII.GetBytes(cPtr, value.Length, bPtr + 1, len); } } } public override bool Equals(object obj) => obj is CommandBytes cb && Equals(cb); public string ToInnerString() { fixed (long* lPtr = _chunks) { long* x = lPtr; var sb = new StringBuilder(); for (int i = 0; i < ChunkLength; i++) { if (sb.Length != 0) sb.Append(','); sb.Append(*x++); } return sb.ToString(); } } public bool Equals(CommandBytes value) { fixed (long* lPtr = _chunks) { long* x = lPtr; long* y = value._chunks; for (int i = 0; i < ChunkLength; i++) { if (*x++ != *y++) return false; } return true; } } private static void Clear(long* ptr) { for (int i = 0; i < ChunkLength; i++) { *ptr++ = 0L; } } } static class Program { static int Main() { var lookup = new Dictionary<CommandBytes, string>(); void Add(string val) { var cb = new CommandBytes(val); // prove we didn't screw up if (cb.ToString() != val) throw new InvalidOperationException("oops!"); lookup.Add(cb, val); } Add("client"); Add("cluster"); Add("command"); Add("config"); Add("dbsize"); Add("decr"); Add("del"); Add("echo"); Add("exists"); Add("flushall"); Add("flushdb"); Add("get"); Add("incr"); Add("incrby"); Add("info"); Add("keys"); Add("llen"); Add("lpop"); Add("lpush"); Add("lrange"); Add("memory"); Add("mget"); Add("mset"); Add("ping"); Add("quit"); Add("role"); Add("rpop"); Add("rpush"); Add("sadd"); Add("scard"); Add("select"); Add("set"); Add("shutdown"); Add("sismember"); Add("spop"); Add("srem"); Add("strlen"); Add("subscribe"); Add("time"); Add("unlink"); Add("unsubscribe"); bool HuntFor(string lookFor) { Console.WriteLine($"Looking for: '{lookFor}'"); var hunt = new CommandBytes(lookFor); bool result = lookup.TryGetValue(hunt, out var found); if (result) { Console.WriteLine($"Found via TryGetValue: '{found}'"); } else { Console.WriteLine("**NOT FOUND** via TryGetValue"); } Console.WriteLine("looking manually"); foreach (var pair in lookup) { if (pair.Value == lookFor) { Console.WriteLine($"Found manually: '{pair.Value}'"); var key = pair.Key; void Compare<T>(string caption, Func<CommandBytes, T> func) { T x = func(hunt), y = func(key); Console.WriteLine($"{caption}: {EqualityComparer<T>.Default.Equals(x, y)}, '{x}' vs '{y}'"); } Compare("GetHashCode", _ => _.GetHashCode()); Compare("ToString", _ => _.ToString()); Compare("Length", _ => _.Length); Compare("ToInnerString", _ => _.ToInnerString()); Console.WriteLine($"Equals: {key.Equals(hunt)}, {hunt.Equals(key)}"); var eq = EqualityComparer<CommandBytes>.Default; Console.WriteLine($"EqualityComparer: {eq.Equals(key, hunt)}, {eq.Equals(hunt, key)}"); Compare("eq GetHashCode", _ => eq.GetHashCode(_)); } } Console.WriteLine(); return result; } bool result1 = HuntFor("ping"); bool result2 = HuntFor("subscribe"); return (result1 && result2) ? 100 : -1; } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/jit64/valuetypes/nullable/box-unbox/value/box-unbox-value043.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - Box-Unbox </Area> // <Title> Nullable type with unbox box expr </Title> // <Description> // checking type of WithMultipleGCHandleStruct using is operator // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ(ValueType o) { return Helper.Compare((WithMultipleGCHandleStruct)o, Helper.Create(default(WithMultipleGCHandleStruct))); } private static bool BoxUnboxToQ(ValueType o) { return Helper.Compare((WithMultipleGCHandleStruct?)o, Helper.Create(default(WithMultipleGCHandleStruct))); } private static int Main() { WithMultipleGCHandleStruct? s = Helper.Create(default(WithMultipleGCHandleStruct)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - Box-Unbox </Area> // <Title> Nullable type with unbox box expr </Title> // <Description> // checking type of WithMultipleGCHandleStruct using is operator // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ(ValueType o) { return Helper.Compare((WithMultipleGCHandleStruct)o, Helper.Create(default(WithMultipleGCHandleStruct))); } private static bool BoxUnboxToQ(ValueType o) { return Helper.Compare((WithMultipleGCHandleStruct?)o, Helper.Create(default(WithMultipleGCHandleStruct))); } private static int Main() { WithMultipleGCHandleStruct? s = Helper.Create(default(WithMultipleGCHandleStruct)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/GenerateGuidForTypeTests.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.Runtime.InteropServices.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public partial class GenerateGuidForTypeTests { [Fact] public void GenerateGuidForType_ComObject_ReturnsComGuid() { Assert.Equal(new Guid("927971f5-0939-11d1-8be1-00c04fd8d503"), Marshal.GenerateGuidForType(typeof(ComImportObject))); } } }
// 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.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public partial class GenerateGuidForTypeTests { [Fact] public void GenerateGuidForType_ComObject_ReturnsComGuid() { Assert.Equal(new Guid("927971f5-0939-11d1-8be1-00c04fd8d503"), Marshal.GenerateGuidForType(typeof(ComImportObject))); } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/CodeGenBringUpTests/IntConv_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="IntConv.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="IntConv.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/CodeGenBringUpTests/And1_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="And1.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="And1.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Methodical/eh/basics/throwinfinally_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType /> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="throwinfinally.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType /> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="throwinfinally.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Methodical/VT/etc/han3_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="han3.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="han3.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/baseservices/exceptions/generics/try-finally03.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 GenException<T> : Exception {} public class Gen<T> { public bool hit; public void InternalExceptionTest(bool throwException) { hit = false; try { if (throwException) { throw new GenException<T>(); } Test_try_finally03.Eval(!throwException); } finally { hit = true; throw new GenException<RefX1<T>>(); } } public void ExceptionTest(bool throwException) { try { InternalExceptionTest(throwException); Test_try_finally03.Eval(!throwException); } catch(Exception E) { Test_try_finally03.Eval(hit); Test_try_finally03.Eval(throwException); Test_try_finally03.Eval(E is GenException<RefX1<T>>); } } } public class Test_try_finally03 { 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() { new Gen<int>().ExceptionTest(true); new Gen<double>().ExceptionTest(true); new Gen<string>().ExceptionTest(true); new Gen<object>().ExceptionTest(true); new Gen<Guid>().ExceptionTest(true); new Gen<int[]>().ExceptionTest(true); new Gen<double[,]>().ExceptionTest(true); new Gen<string[][][]>().ExceptionTest(true); new Gen<object[,,,]>().ExceptionTest(true); new Gen<Guid[][,,,][]>().ExceptionTest(true); new Gen<RefX1<int>[]>().ExceptionTest(true); new Gen<RefX1<double>[,]>().ExceptionTest(true); new Gen<RefX1<string>[][][]>().ExceptionTest(true); new Gen<RefX1<object>[,,,]>().ExceptionTest(true); new Gen<RefX1<Guid>[][,,,][]>().ExceptionTest(true); new Gen<RefX2<int,int>[]>().ExceptionTest(true); new Gen<RefX2<double,double>[,]>().ExceptionTest(true); new Gen<RefX2<string,string>[][][]>().ExceptionTest(true); new Gen<RefX2<object,object>[,,,]>().ExceptionTest(true); new Gen<RefX2<Guid,Guid>[][,,,][]>().ExceptionTest(true); new Gen<ValX1<int>[]>().ExceptionTest(true); new Gen<ValX1<double>[,]>().ExceptionTest(true); new Gen<ValX1<string>[][][]>().ExceptionTest(true); new Gen<ValX1<object>[,,,]>().ExceptionTest(true); new Gen<ValX1<Guid>[][,,,][]>().ExceptionTest(true); new Gen<ValX2<int,int>[]>().ExceptionTest(true); new Gen<ValX2<double,double>[,]>().ExceptionTest(true); new Gen<ValX2<string,string>[][][]>().ExceptionTest(true); new Gen<ValX2<object,object>[,,,]>().ExceptionTest(true); new Gen<ValX2<Guid,Guid>[][,,,][]>().ExceptionTest(true); new Gen<RefX1<int>>().ExceptionTest(true); new Gen<RefX1<ValX1<int>>>().ExceptionTest(true); new Gen<RefX2<int,string>>().ExceptionTest(true); new Gen<RefX3<int,string,Guid>>().ExceptionTest(true); new Gen<RefX1<RefX1<int>>>().ExceptionTest(true); new Gen<RefX1<RefX1<RefX1<string>>>>().ExceptionTest(true); new Gen<RefX1<RefX1<RefX1<RefX1<Guid>>>>>().ExceptionTest(true); new Gen<RefX1<RefX2<int,string>>>().ExceptionTest(true); new Gen<RefX2<RefX2<RefX1<int>,RefX3<int,string, RefX1<RefX2<int,string>>>>,RefX2<RefX1<int>,RefX3<int,string, RefX1<RefX2<int,string>>>>>>().ExceptionTest(true); new Gen<RefX3<RefX1<int[][,,,]>,RefX2<object[,,,][][],Guid[][][]>,RefX3<double[,,,,,,,,,,],Guid[][][][,,,,][,,,,][][][],string[][][][][][][][][][][]>>>().ExceptionTest(true); new Gen<ValX1<int>>().ExceptionTest(true); new Gen<ValX1<RefX1<int>>>().ExceptionTest(true); new Gen<ValX2<int,string>>().ExceptionTest(true); new Gen<ValX3<int,string,Guid>>().ExceptionTest(true); new Gen<ValX1<ValX1<int>>>().ExceptionTest(true); new Gen<ValX1<ValX1<ValX1<string>>>>().ExceptionTest(true); new Gen<ValX1<ValX1<ValX1<ValX1<Guid>>>>>().ExceptionTest(true); new Gen<ValX1<ValX2<int,string>>>().ExceptionTest(true); new Gen<ValX2<ValX2<ValX1<int>,ValX3<int,string, ValX1<ValX2<int,string>>>>,ValX2<ValX1<int>,ValX3<int,string, ValX1<ValX2<int,string>>>>>>().ExceptionTest(true); new Gen<ValX3<ValX1<int[][,,,]>,ValX2<object[,,,][][],Guid[][][]>,ValX3<double[,,,,,,,,,,],Guid[][][][,,,,][,,,,][][][],string[][][][][][][][][][][]>>>().ExceptionTest(true); 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 GenException<T> : Exception {} public class Gen<T> { public bool hit; public void InternalExceptionTest(bool throwException) { hit = false; try { if (throwException) { throw new GenException<T>(); } Test_try_finally03.Eval(!throwException); } finally { hit = true; throw new GenException<RefX1<T>>(); } } public void ExceptionTest(bool throwException) { try { InternalExceptionTest(throwException); Test_try_finally03.Eval(!throwException); } catch(Exception E) { Test_try_finally03.Eval(hit); Test_try_finally03.Eval(throwException); Test_try_finally03.Eval(E is GenException<RefX1<T>>); } } } public class Test_try_finally03 { 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() { new Gen<int>().ExceptionTest(true); new Gen<double>().ExceptionTest(true); new Gen<string>().ExceptionTest(true); new Gen<object>().ExceptionTest(true); new Gen<Guid>().ExceptionTest(true); new Gen<int[]>().ExceptionTest(true); new Gen<double[,]>().ExceptionTest(true); new Gen<string[][][]>().ExceptionTest(true); new Gen<object[,,,]>().ExceptionTest(true); new Gen<Guid[][,,,][]>().ExceptionTest(true); new Gen<RefX1<int>[]>().ExceptionTest(true); new Gen<RefX1<double>[,]>().ExceptionTest(true); new Gen<RefX1<string>[][][]>().ExceptionTest(true); new Gen<RefX1<object>[,,,]>().ExceptionTest(true); new Gen<RefX1<Guid>[][,,,][]>().ExceptionTest(true); new Gen<RefX2<int,int>[]>().ExceptionTest(true); new Gen<RefX2<double,double>[,]>().ExceptionTest(true); new Gen<RefX2<string,string>[][][]>().ExceptionTest(true); new Gen<RefX2<object,object>[,,,]>().ExceptionTest(true); new Gen<RefX2<Guid,Guid>[][,,,][]>().ExceptionTest(true); new Gen<ValX1<int>[]>().ExceptionTest(true); new Gen<ValX1<double>[,]>().ExceptionTest(true); new Gen<ValX1<string>[][][]>().ExceptionTest(true); new Gen<ValX1<object>[,,,]>().ExceptionTest(true); new Gen<ValX1<Guid>[][,,,][]>().ExceptionTest(true); new Gen<ValX2<int,int>[]>().ExceptionTest(true); new Gen<ValX2<double,double>[,]>().ExceptionTest(true); new Gen<ValX2<string,string>[][][]>().ExceptionTest(true); new Gen<ValX2<object,object>[,,,]>().ExceptionTest(true); new Gen<ValX2<Guid,Guid>[][,,,][]>().ExceptionTest(true); new Gen<RefX1<int>>().ExceptionTest(true); new Gen<RefX1<ValX1<int>>>().ExceptionTest(true); new Gen<RefX2<int,string>>().ExceptionTest(true); new Gen<RefX3<int,string,Guid>>().ExceptionTest(true); new Gen<RefX1<RefX1<int>>>().ExceptionTest(true); new Gen<RefX1<RefX1<RefX1<string>>>>().ExceptionTest(true); new Gen<RefX1<RefX1<RefX1<RefX1<Guid>>>>>().ExceptionTest(true); new Gen<RefX1<RefX2<int,string>>>().ExceptionTest(true); new Gen<RefX2<RefX2<RefX1<int>,RefX3<int,string, RefX1<RefX2<int,string>>>>,RefX2<RefX1<int>,RefX3<int,string, RefX1<RefX2<int,string>>>>>>().ExceptionTest(true); new Gen<RefX3<RefX1<int[][,,,]>,RefX2<object[,,,][][],Guid[][][]>,RefX3<double[,,,,,,,,,,],Guid[][][][,,,,][,,,,][][][],string[][][][][][][][][][][]>>>().ExceptionTest(true); new Gen<ValX1<int>>().ExceptionTest(true); new Gen<ValX1<RefX1<int>>>().ExceptionTest(true); new Gen<ValX2<int,string>>().ExceptionTest(true); new Gen<ValX3<int,string,Guid>>().ExceptionTest(true); new Gen<ValX1<ValX1<int>>>().ExceptionTest(true); new Gen<ValX1<ValX1<ValX1<string>>>>().ExceptionTest(true); new Gen<ValX1<ValX1<ValX1<ValX1<Guid>>>>>().ExceptionTest(true); new Gen<ValX1<ValX2<int,string>>>().ExceptionTest(true); new Gen<ValX2<ValX2<ValX1<int>,ValX3<int,string, ValX1<ValX2<int,string>>>>,ValX2<ValX1<int>,ValX3<int,string, ValX1<ValX2<int,string>>>>>>().ExceptionTest(true); new Gen<ValX3<ValX1<int[][,,,]>,ValX2<object[,,,][][],Guid[][][]>,ValX3<double[,,,,,,,,,,],Guid[][][][,,,,][,,,,][][][],string[][][][][][][][][][][]>>>().ExceptionTest(true); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/FusedAddHalving.Vector64.Int32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void FusedAddHalving_Vector64_Int32() { var test = new SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector64<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32 testClass) { var result = AdvSimd.FusedAddHalving(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) { var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector64<Int32> _clsVar2; private Vector64<Int32> _fld1; private Vector64<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.FusedAddHalving( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.FusedAddHalving), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.FusedAddHalving), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.FusedAddHalving( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector64<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector64((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<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.FusedAddHalving(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((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.FusedAddHalving(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32(); var result = AdvSimd.FusedAddHalving(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__FusedAddHalving_Vector64_Int32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector64<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.FusedAddHalving(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) { var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.FusedAddHalving(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.FusedAddHalving( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector64((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(Vector64<Int32> op1, Vector64<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<Vector64<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<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.FusedAddHalving(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.FusedAddHalving)}<Int32>(Vector64<Int32>, Vector64<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void FusedAddHalving_Vector64_Int32() { var test = new SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector64<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32 testClass) { var result = AdvSimd.FusedAddHalving(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) { var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector64<Int32> _clsVar2; private Vector64<Int32> _fld1; private Vector64<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.FusedAddHalving( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.FusedAddHalving), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.FusedAddHalving), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.FusedAddHalving( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector64<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector64((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<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.FusedAddHalving(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((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.FusedAddHalving(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__FusedAddHalving_Vector64_Int32(); var result = AdvSimd.FusedAddHalving(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__FusedAddHalving_Vector64_Int32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector64<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.FusedAddHalving(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) { var result = AdvSimd.FusedAddHalving( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector64((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.FusedAddHalving(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.FusedAddHalving( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector64((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(Vector64<Int32> op1, Vector64<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<Vector64<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<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.FusedAddHalving(left[i], right[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.FusedAddHalving)}<Int32>(Vector64<Int32>, Vector64<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,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/coreclr/tools/Common/Compiler/CompilerTypeSystemContext.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.MemoryMappedFiles; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler { public partial class CompilerTypeSystemContext : MetadataTypeSystemContext, IMetadataStringDecoderProvider { private readonly MetadataRuntimeInterfacesAlgorithm _metadataRuntimeInterfacesAlgorithm = new MetadataRuntimeInterfacesAlgorithm(); private readonly MetadataVirtualMethodAlgorithm _virtualMethodAlgorithm = new MetadataVirtualMethodAlgorithm(); private MetadataStringDecoder _metadataStringDecoder; private class ModuleData { public string SimpleName; public string FilePath; public EcmaModule Module; public MemoryMappedViewAccessor MappedViewAccessor; } private class ModuleHashtable : LockFreeReaderHashtable<EcmaModule, ModuleData> { protected override int GetKeyHashCode(EcmaModule key) { return key.GetHashCode(); } protected override int GetValueHashCode(ModuleData value) { return value.Module.GetHashCode(); } protected override bool CompareKeyToValue(EcmaModule key, ModuleData value) { return Object.ReferenceEquals(key, value.Module); } protected override bool CompareValueToValue(ModuleData value1, ModuleData value2) { return Object.ReferenceEquals(value1.Module, value2.Module); } protected override ModuleData CreateValueFromKey(EcmaModule key) { Debug.Fail("CreateValueFromKey not supported"); return null; } } private readonly ModuleHashtable _moduleHashtable = new ModuleHashtable(); private class SimpleNameHashtable : LockFreeReaderHashtable<string, ModuleData> { StringComparer _comparer = StringComparer.OrdinalIgnoreCase; protected override int GetKeyHashCode(string key) { return _comparer.GetHashCode(key); } protected override int GetValueHashCode(ModuleData value) { return _comparer.GetHashCode(value.SimpleName); } protected override bool CompareKeyToValue(string key, ModuleData value) { return _comparer.Equals(key, value.SimpleName); } protected override bool CompareValueToValue(ModuleData value1, ModuleData value2) { return _comparer.Equals(value1.SimpleName, value2.SimpleName); } protected override ModuleData CreateValueFromKey(string key) { Debug.Fail("CreateValueFromKey not supported"); return null; } } private readonly SimpleNameHashtable _simpleNameHashtable = new SimpleNameHashtable(); private readonly SharedGenericsMode _genericsMode; public IReadOnlyDictionary<string, string> InputFilePaths { get; set; } public IReadOnlyDictionary<string, string> ReferenceFilePaths { get; set; } public override ModuleDesc ResolveAssembly(System.Reflection.AssemblyName name, bool throwIfNotFound) { // TODO: catch typesystem BadImageFormatException and throw a new one that also captures the // assembly name that caused the failure. (Along with the reason, which makes this rather annoying). return GetModuleForSimpleName(name.Name, throwIfNotFound); } public EcmaModule GetModuleForSimpleName(string simpleName, bool throwIfNotFound = true) { if (_simpleNameHashtable.TryGetValue(simpleName, out ModuleData existing)) return existing.Module; if (InputFilePaths.TryGetValue(simpleName, out string filePath) || ReferenceFilePaths.TryGetValue(simpleName, out filePath)) return AddModule(filePath, simpleName, true); // TODO: the exception is wrong for two reasons: for one, this should be assembly full name, not simple name. // The other reason is that on CoreCLR, the exception also captures the reason. We should be passing two // string IDs. This makes this rather annoying. if (throwIfNotFound) ThrowHelper.ThrowFileNotFoundException(ExceptionStringID.FileLoadErrorGeneric, simpleName); return null; } public EcmaModule GetModuleFromPath(string filePath) { return GetOrAddModuleFromPath(filePath, true); } public EcmaModule GetMetadataOnlyModuleFromPath(string filePath) { return GetOrAddModuleFromPath(filePath, false); } private EcmaModule GetOrAddModuleFromPath(string filePath, bool useForBinding) { // This method is not expected to be called frequently. Linear search is acceptable. foreach (var entry in ModuleHashtable.Enumerator.Get(_moduleHashtable)) { if (entry.FilePath == filePath) return entry.Module; } return AddModule(filePath, null, useForBinding); } public static unsafe PEReader OpenPEFile(string filePath, out MemoryMappedViewAccessor mappedViewAccessor) { // System.Reflection.Metadata has heuristic that tries to save virtual address space. This heuristic does not work // well for us since it can make IL access very slow (call to OS for each method IL query). We will map the file // ourselves to get the desired performance characteristics reliably. FileStream fileStream = null; MemoryMappedFile mappedFile = null; MemoryMappedViewAccessor accessor = null; try { // Create stream because CreateFromFile(string, ...) uses FileShare.None which is too strict fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1); mappedFile = MemoryMappedFile.CreateFromFile( fileStream, null, fileStream.Length, MemoryMappedFileAccess.Read, HandleInheritability.None, true); accessor = mappedFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); var safeBuffer = accessor.SafeMemoryMappedViewHandle; var peReader = new PEReader((byte*)safeBuffer.DangerousGetHandle(), (int)safeBuffer.ByteLength); // MemoryMappedFile does not need to be kept around. MemoryMappedViewAccessor is enough. mappedViewAccessor = accessor; accessor = null; return peReader; } finally { accessor?.Dispose(); mappedFile?.Dispose(); fileStream?.Dispose(); } } private EcmaModule AddModule(string filePath, string expectedSimpleName, bool useForBinding, ModuleData oldModuleData = null) { PEReader peReader = null; MemoryMappedViewAccessor mappedViewAccessor = null; PdbSymbolReader pdbReader = null; try { if (oldModuleData == null) { peReader = OpenPEFile(filePath, out mappedViewAccessor); #if !READYTORUN if (peReader.HasMetadata && (peReader.PEHeaders.CorHeader.Flags & (CorFlags.ILLibrary | CorFlags.ILOnly)) == 0) throw new NotSupportedException($"Error: C++/CLI is not supported: '{filePath}'"); #endif pdbReader = PortablePdbSymbolReader.TryOpenEmbedded(peReader, GetMetadataStringDecoder()) ?? OpenAssociatedSymbolFile(filePath, peReader); } else { filePath = oldModuleData.FilePath; peReader = oldModuleData.Module.PEReader; mappedViewAccessor = oldModuleData.MappedViewAccessor; pdbReader = oldModuleData.Module.PdbReader; } EcmaModule module = EcmaModule.Create(this, peReader, containingAssembly: null, pdbReader); MetadataReader metadataReader = module.MetadataReader; string simpleName = metadataReader.GetString(metadataReader.GetAssemblyDefinition().Name); if (expectedSimpleName != null && !simpleName.Equals(expectedSimpleName, StringComparison.OrdinalIgnoreCase)) throw new FileNotFoundException("Assembly name does not match filename " + filePath); ModuleData moduleData = new ModuleData() { SimpleName = simpleName, FilePath = filePath, Module = module, MappedViewAccessor = mappedViewAccessor }; lock (this) { if (useForBinding) { ModuleData actualModuleData = _simpleNameHashtable.AddOrGetExisting(moduleData); if (actualModuleData != moduleData) { if (actualModuleData.FilePath != filePath) throw new FileNotFoundException("Module with same simple name already exists " + filePath); return actualModuleData.Module; } } mappedViewAccessor = null; // Ownership has been transfered pdbReader = null; // Ownership has been transferred _moduleHashtable.AddOrGetExisting(moduleData); } return module; } finally { if (mappedViewAccessor != null) mappedViewAccessor.Dispose(); if (pdbReader != null) pdbReader.Dispose(); } } protected void InheritOpenModules(CompilerTypeSystemContext oldTypeSystemContext) { foreach (ModuleData oldModuleData in ModuleHashtable.Enumerator.Get(oldTypeSystemContext._moduleHashtable)) { AddModule(null, null, true, oldModuleData); } } protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForDefType(DefType type) { return _metadataRuntimeInterfacesAlgorithm; } public override VirtualMethodAlgorithm GetVirtualMethodAlgorithmForType(TypeDesc type) { Debug.Assert(!type.IsArray, "Wanted to call GetClosestMetadataType?"); return _virtualMethodAlgorithm; } protected override Instantiation ConvertInstantiationToCanonForm(Instantiation instantiation, CanonicalFormKind kind, out bool changed) { if (_genericsMode == SharedGenericsMode.CanonicalReferenceTypes) return RuntimeDeterminedCanonicalizationAlgorithm.ConvertInstantiationToCanonForm(instantiation, kind, out changed); Debug.Assert(_genericsMode == SharedGenericsMode.Disabled); changed = false; return instantiation; } protected override TypeDesc ConvertToCanon(TypeDesc typeToConvert, CanonicalFormKind kind) { if (_genericsMode == SharedGenericsMode.CanonicalReferenceTypes) return RuntimeDeterminedCanonicalizationAlgorithm.ConvertToCanon(typeToConvert, kind); Debug.Assert(_genericsMode == SharedGenericsMode.Disabled); return typeToConvert; } protected override TypeDesc ConvertToCanon(TypeDesc typeToConvert, ref CanonicalFormKind kind) { if (_genericsMode == SharedGenericsMode.CanonicalReferenceTypes) return RuntimeDeterminedCanonicalizationAlgorithm.ConvertToCanon(typeToConvert, ref kind); Debug.Assert(_genericsMode == SharedGenericsMode.Disabled); return typeToConvert; } public override bool SupportsUniversalCanon => false; public override bool SupportsCanon => _genericsMode != SharedGenericsMode.Disabled; public MetadataStringDecoder GetMetadataStringDecoder() { if (_metadataStringDecoder == null) _metadataStringDecoder = new CachingMetadataStringDecoder(0x10000); // TODO: Tune the size return _metadataStringDecoder; } // // Symbols // private PdbSymbolReader OpenAssociatedSymbolFile(string peFilePath, PEReader peReader) { // Assume that the .pdb file is next to the binary var pdbFilename = Path.ChangeExtension(peFilePath, ".pdb"); string searchPath = ""; if (!File.Exists(pdbFilename)) { pdbFilename = null; // If the file doesn't exist, try the path specified in the CodeView section of the image foreach (DebugDirectoryEntry debugEntry in peReader.ReadDebugDirectory()) { if (debugEntry.Type != DebugDirectoryEntryType.CodeView) continue; string candidateFileName = peReader.ReadCodeViewDebugDirectoryData(debugEntry).Path; if (Path.IsPathRooted(candidateFileName) && File.Exists(candidateFileName)) { pdbFilename = candidateFileName; searchPath = Path.GetDirectoryName(pdbFilename); break; } } if (pdbFilename == null) return null; } // Try to open the symbol file as portable pdb first PdbSymbolReader reader = PortablePdbSymbolReader.TryOpen(pdbFilename, GetMetadataStringDecoder()); if (reader == null) { // Fallback to the diasymreader for non-portable pdbs reader = UnmanagedPdbSymbolReader.TryOpenSymbolReaderForMetadataFile(peFilePath, searchPath); } return reader; } } /// <summary> /// Specifies the mode in which canonicalization should occur. /// </summary> public enum SharedGenericsMode { Disabled, CanonicalReferenceTypes, } }
// 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.MemoryMappedFiles; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler { public partial class CompilerTypeSystemContext : MetadataTypeSystemContext, IMetadataStringDecoderProvider { private readonly MetadataRuntimeInterfacesAlgorithm _metadataRuntimeInterfacesAlgorithm = new MetadataRuntimeInterfacesAlgorithm(); private readonly MetadataVirtualMethodAlgorithm _virtualMethodAlgorithm = new MetadataVirtualMethodAlgorithm(); private MetadataStringDecoder _metadataStringDecoder; private class ModuleData { public string SimpleName; public string FilePath; public EcmaModule Module; public MemoryMappedViewAccessor MappedViewAccessor; } private class ModuleHashtable : LockFreeReaderHashtable<EcmaModule, ModuleData> { protected override int GetKeyHashCode(EcmaModule key) { return key.GetHashCode(); } protected override int GetValueHashCode(ModuleData value) { return value.Module.GetHashCode(); } protected override bool CompareKeyToValue(EcmaModule key, ModuleData value) { return Object.ReferenceEquals(key, value.Module); } protected override bool CompareValueToValue(ModuleData value1, ModuleData value2) { return Object.ReferenceEquals(value1.Module, value2.Module); } protected override ModuleData CreateValueFromKey(EcmaModule key) { Debug.Fail("CreateValueFromKey not supported"); return null; } } private readonly ModuleHashtable _moduleHashtable = new ModuleHashtable(); private class SimpleNameHashtable : LockFreeReaderHashtable<string, ModuleData> { StringComparer _comparer = StringComparer.OrdinalIgnoreCase; protected override int GetKeyHashCode(string key) { return _comparer.GetHashCode(key); } protected override int GetValueHashCode(ModuleData value) { return _comparer.GetHashCode(value.SimpleName); } protected override bool CompareKeyToValue(string key, ModuleData value) { return _comparer.Equals(key, value.SimpleName); } protected override bool CompareValueToValue(ModuleData value1, ModuleData value2) { return _comparer.Equals(value1.SimpleName, value2.SimpleName); } protected override ModuleData CreateValueFromKey(string key) { Debug.Fail("CreateValueFromKey not supported"); return null; } } private readonly SimpleNameHashtable _simpleNameHashtable = new SimpleNameHashtable(); private readonly SharedGenericsMode _genericsMode; public IReadOnlyDictionary<string, string> InputFilePaths { get; set; } public IReadOnlyDictionary<string, string> ReferenceFilePaths { get; set; } public override ModuleDesc ResolveAssembly(System.Reflection.AssemblyName name, bool throwIfNotFound) { // TODO: catch typesystem BadImageFormatException and throw a new one that also captures the // assembly name that caused the failure. (Along with the reason, which makes this rather annoying). return GetModuleForSimpleName(name.Name, throwIfNotFound); } public EcmaModule GetModuleForSimpleName(string simpleName, bool throwIfNotFound = true) { if (_simpleNameHashtable.TryGetValue(simpleName, out ModuleData existing)) return existing.Module; if (InputFilePaths.TryGetValue(simpleName, out string filePath) || ReferenceFilePaths.TryGetValue(simpleName, out filePath)) return AddModule(filePath, simpleName, true); // TODO: the exception is wrong for two reasons: for one, this should be assembly full name, not simple name. // The other reason is that on CoreCLR, the exception also captures the reason. We should be passing two // string IDs. This makes this rather annoying. if (throwIfNotFound) ThrowHelper.ThrowFileNotFoundException(ExceptionStringID.FileLoadErrorGeneric, simpleName); return null; } public EcmaModule GetModuleFromPath(string filePath) { return GetOrAddModuleFromPath(filePath, true); } public EcmaModule GetMetadataOnlyModuleFromPath(string filePath) { return GetOrAddModuleFromPath(filePath, false); } private EcmaModule GetOrAddModuleFromPath(string filePath, bool useForBinding) { // This method is not expected to be called frequently. Linear search is acceptable. foreach (var entry in ModuleHashtable.Enumerator.Get(_moduleHashtable)) { if (entry.FilePath == filePath) return entry.Module; } return AddModule(filePath, null, useForBinding); } public static unsafe PEReader OpenPEFile(string filePath, out MemoryMappedViewAccessor mappedViewAccessor) { // System.Reflection.Metadata has heuristic that tries to save virtual address space. This heuristic does not work // well for us since it can make IL access very slow (call to OS for each method IL query). We will map the file // ourselves to get the desired performance characteristics reliably. FileStream fileStream = null; MemoryMappedFile mappedFile = null; MemoryMappedViewAccessor accessor = null; try { // Create stream because CreateFromFile(string, ...) uses FileShare.None which is too strict fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1); mappedFile = MemoryMappedFile.CreateFromFile( fileStream, null, fileStream.Length, MemoryMappedFileAccess.Read, HandleInheritability.None, true); accessor = mappedFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); var safeBuffer = accessor.SafeMemoryMappedViewHandle; var peReader = new PEReader((byte*)safeBuffer.DangerousGetHandle(), (int)safeBuffer.ByteLength); // MemoryMappedFile does not need to be kept around. MemoryMappedViewAccessor is enough. mappedViewAccessor = accessor; accessor = null; return peReader; } finally { accessor?.Dispose(); mappedFile?.Dispose(); fileStream?.Dispose(); } } private EcmaModule AddModule(string filePath, string expectedSimpleName, bool useForBinding, ModuleData oldModuleData = null) { PEReader peReader = null; MemoryMappedViewAccessor mappedViewAccessor = null; PdbSymbolReader pdbReader = null; try { if (oldModuleData == null) { peReader = OpenPEFile(filePath, out mappedViewAccessor); #if !READYTORUN if (peReader.HasMetadata && (peReader.PEHeaders.CorHeader.Flags & (CorFlags.ILLibrary | CorFlags.ILOnly)) == 0) throw new NotSupportedException($"Error: C++/CLI is not supported: '{filePath}'"); #endif pdbReader = PortablePdbSymbolReader.TryOpenEmbedded(peReader, GetMetadataStringDecoder()) ?? OpenAssociatedSymbolFile(filePath, peReader); } else { filePath = oldModuleData.FilePath; peReader = oldModuleData.Module.PEReader; mappedViewAccessor = oldModuleData.MappedViewAccessor; pdbReader = oldModuleData.Module.PdbReader; } EcmaModule module = EcmaModule.Create(this, peReader, containingAssembly: null, pdbReader); MetadataReader metadataReader = module.MetadataReader; string simpleName = metadataReader.GetString(metadataReader.GetAssemblyDefinition().Name); if (expectedSimpleName != null && !simpleName.Equals(expectedSimpleName, StringComparison.OrdinalIgnoreCase)) throw new FileNotFoundException("Assembly name does not match filename " + filePath); ModuleData moduleData = new ModuleData() { SimpleName = simpleName, FilePath = filePath, Module = module, MappedViewAccessor = mappedViewAccessor }; lock (this) { if (useForBinding) { ModuleData actualModuleData = _simpleNameHashtable.AddOrGetExisting(moduleData); if (actualModuleData != moduleData) { if (actualModuleData.FilePath != filePath) throw new FileNotFoundException("Module with same simple name already exists " + filePath); return actualModuleData.Module; } } mappedViewAccessor = null; // Ownership has been transfered pdbReader = null; // Ownership has been transferred _moduleHashtable.AddOrGetExisting(moduleData); } return module; } finally { if (mappedViewAccessor != null) mappedViewAccessor.Dispose(); if (pdbReader != null) pdbReader.Dispose(); } } protected void InheritOpenModules(CompilerTypeSystemContext oldTypeSystemContext) { foreach (ModuleData oldModuleData in ModuleHashtable.Enumerator.Get(oldTypeSystemContext._moduleHashtable)) { AddModule(null, null, true, oldModuleData); } } protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForDefType(DefType type) { return _metadataRuntimeInterfacesAlgorithm; } public override VirtualMethodAlgorithm GetVirtualMethodAlgorithmForType(TypeDesc type) { Debug.Assert(!type.IsArray, "Wanted to call GetClosestMetadataType?"); return _virtualMethodAlgorithm; } protected override Instantiation ConvertInstantiationToCanonForm(Instantiation instantiation, CanonicalFormKind kind, out bool changed) { if (_genericsMode == SharedGenericsMode.CanonicalReferenceTypes) return RuntimeDeterminedCanonicalizationAlgorithm.ConvertInstantiationToCanonForm(instantiation, kind, out changed); Debug.Assert(_genericsMode == SharedGenericsMode.Disabled); changed = false; return instantiation; } protected override TypeDesc ConvertToCanon(TypeDesc typeToConvert, CanonicalFormKind kind) { if (_genericsMode == SharedGenericsMode.CanonicalReferenceTypes) return RuntimeDeterminedCanonicalizationAlgorithm.ConvertToCanon(typeToConvert, kind); Debug.Assert(_genericsMode == SharedGenericsMode.Disabled); return typeToConvert; } protected override TypeDesc ConvertToCanon(TypeDesc typeToConvert, ref CanonicalFormKind kind) { if (_genericsMode == SharedGenericsMode.CanonicalReferenceTypes) return RuntimeDeterminedCanonicalizationAlgorithm.ConvertToCanon(typeToConvert, ref kind); Debug.Assert(_genericsMode == SharedGenericsMode.Disabled); return typeToConvert; } public override bool SupportsUniversalCanon => false; public override bool SupportsCanon => _genericsMode != SharedGenericsMode.Disabled; public MetadataStringDecoder GetMetadataStringDecoder() { if (_metadataStringDecoder == null) _metadataStringDecoder = new CachingMetadataStringDecoder(0x10000); // TODO: Tune the size return _metadataStringDecoder; } // // Symbols // private PdbSymbolReader OpenAssociatedSymbolFile(string peFilePath, PEReader peReader) { // Assume that the .pdb file is next to the binary var pdbFilename = Path.ChangeExtension(peFilePath, ".pdb"); string searchPath = ""; if (!File.Exists(pdbFilename)) { pdbFilename = null; // If the file doesn't exist, try the path specified in the CodeView section of the image foreach (DebugDirectoryEntry debugEntry in peReader.ReadDebugDirectory()) { if (debugEntry.Type != DebugDirectoryEntryType.CodeView) continue; string candidateFileName = peReader.ReadCodeViewDebugDirectoryData(debugEntry).Path; if (Path.IsPathRooted(candidateFileName) && File.Exists(candidateFileName)) { pdbFilename = candidateFileName; searchPath = Path.GetDirectoryName(pdbFilename); break; } } if (pdbFilename == null) return null; } // Try to open the symbol file as portable pdb first PdbSymbolReader reader = PortablePdbSymbolReader.TryOpen(pdbFilename, GetMetadataStringDecoder()); if (reader == null) { // Fallback to the diasymreader for non-portable pdbs reader = UnmanagedPdbSymbolReader.TryOpenSymbolReaderForMetadataFile(peFilePath, searchPath); } return reader; } } /// <summary> /// Specifies the mode in which canonicalization should occur. /// </summary> public enum SharedGenericsMode { Disabled, CanonicalReferenceTypes, } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/Microsoft.Bcl.AsyncInterfaces/src/Microsoft.Bcl.AsyncInterfaces.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0;$(NetFrameworkMinimum);netstandard2.1</TargetFrameworks> <IsPackable>true</IsPackable> <!-- This assembly should never be placed inbox as it is only for downlevel compatibility. --> <PackageDescription>Provides the IAsyncEnumerable&lt;T&gt; and IAsyncDisposable interfaces and helper types for .NET Standard 2.0. This package is not required starting with .NET Standard 2.1 and .NET Core 3.0. Commonly Used Types: System.IAsyncDisposable System.Collections.Generic.IAsyncEnumerable System.Collections.Generic.IAsyncEnumerator</PackageDescription> </PropertyGroup> <PropertyGroup> <IsPartialFacadeAssembly Condition="'$(TargetFramework)' == 'netstandard2.1'">true</IsPartialFacadeAssembly> </PropertyGroup> <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'"> <Compile Include="System\Threading\Tasks\Sources\ManualResetValueTaskSourceCore.cs" /> <Compile Include="System\Runtime\CompilerServices\AsyncIteratorMethodBuilder.cs" /> <Compile Include="$(CoreLibSharedDir)\System\Collections\Generic\IAsyncEnumerable.cs"> <Link>System.Private.CoreLib\System\Collections\Generic\IAsyncEnumerable.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\Collections\Generic\IAsyncEnumerator.cs"> <Link>System.Private.CoreLib\System\Collections\Generic\IAsyncEnumerator.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\IAsyncDisposable.cs"> <Link>System.Private.CoreLib\System\IAsyncDisposable.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\Runtime\CompilerServices\AsyncIteratorStateMachineAttribute.cs"> <Link>System.Private.CoreLib\System\Runtime\CompilerServices\AsyncIteratorStateMachineAttribute.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\Runtime\CompilerServices\ConfiguredAsyncDisposable.cs"> <Link>System.Private.CoreLib\System\Runtime\CompilerServices\ConfiguredAsyncDisposable.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\Runtime\CompilerServices\ConfiguredCancelableAsyncEnumerable.cs"> <Link>System.Private.CoreLib\System\Runtime\CompilerServices\ConfiguredCancelableAsyncEnumerable.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\Threading\Tasks\TaskAsyncEnumerableExtensions.cs"> <Link>System.Private.CoreLib\System\Threading\Tasks\TaskAsyncEnumerableExtensions.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\Runtime\CompilerServices\EnumeratorCancellationAttribute.cs"> <Link>System.Private.CoreLib\System\Runtime\CompilerServices\EnumeratorCancellationAttribute.cs</Link> </Compile> </ItemGroup> <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'"> <PackageReference Include="System.Threading.Tasks.Extensions" Version="$(SystemThreadingTasksExtensionsVersion)" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0;$(NetFrameworkMinimum);netstandard2.1</TargetFrameworks> <IsPackable>true</IsPackable> <!-- This assembly should never be placed inbox as it is only for downlevel compatibility. --> <PackageDescription>Provides the IAsyncEnumerable&lt;T&gt; and IAsyncDisposable interfaces and helper types for .NET Standard 2.0. This package is not required starting with .NET Standard 2.1 and .NET Core 3.0. Commonly Used Types: System.IAsyncDisposable System.Collections.Generic.IAsyncEnumerable System.Collections.Generic.IAsyncEnumerator</PackageDescription> </PropertyGroup> <PropertyGroup> <IsPartialFacadeAssembly Condition="'$(TargetFramework)' == 'netstandard2.1'">true</IsPartialFacadeAssembly> </PropertyGroup> <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'"> <Compile Include="System\Threading\Tasks\Sources\ManualResetValueTaskSourceCore.cs" /> <Compile Include="System\Runtime\CompilerServices\AsyncIteratorMethodBuilder.cs" /> <Compile Include="$(CoreLibSharedDir)\System\Collections\Generic\IAsyncEnumerable.cs"> <Link>System.Private.CoreLib\System\Collections\Generic\IAsyncEnumerable.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\Collections\Generic\IAsyncEnumerator.cs"> <Link>System.Private.CoreLib\System\Collections\Generic\IAsyncEnumerator.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\IAsyncDisposable.cs"> <Link>System.Private.CoreLib\System\IAsyncDisposable.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\Runtime\CompilerServices\AsyncIteratorStateMachineAttribute.cs"> <Link>System.Private.CoreLib\System\Runtime\CompilerServices\AsyncIteratorStateMachineAttribute.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\Runtime\CompilerServices\ConfiguredAsyncDisposable.cs"> <Link>System.Private.CoreLib\System\Runtime\CompilerServices\ConfiguredAsyncDisposable.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\Runtime\CompilerServices\ConfiguredCancelableAsyncEnumerable.cs"> <Link>System.Private.CoreLib\System\Runtime\CompilerServices\ConfiguredCancelableAsyncEnumerable.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\Threading\Tasks\TaskAsyncEnumerableExtensions.cs"> <Link>System.Private.CoreLib\System\Threading\Tasks\TaskAsyncEnumerableExtensions.cs</Link> </Compile> <Compile Include="$(CoreLibSharedDir)\System\Runtime\CompilerServices\EnumeratorCancellationAttribute.cs"> <Link>System.Private.CoreLib\System\Runtime\CompilerServices\EnumeratorCancellationAttribute.cs</Link> </Compile> </ItemGroup> <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'"> <PackageReference Include="System.Threading.Tasks.Extensions" Version="$(SystemThreadingTasksExtensionsVersion)" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/Fakes/CircularReferences/IndirectCircularDependencyC.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes { public class IndirectCircularDependencyC { public IndirectCircularDependencyC(IndirectCircularDependencyA a) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Extensions.DependencyInjection.Tests.Fakes { public class IndirectCircularDependencyC { public IndirectCircularDependencyC(IndirectCircularDependencyA a) { } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Formats.Cbor/tests/Writer/CborWriterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using Test.Cryptography; using Xunit; namespace System.Formats.Cbor.Tests { public partial class CborWriterTests { [Fact] public static void IsWriteCompleted_OnWrittenPrimitive_ShouldBeTrue() { var writer = new CborWriter(); Assert.False(writer.IsWriteCompleted); writer.WriteInt64(42); Assert.True(writer.IsWriteCompleted); } [Fact] public static void GetEncoding_OnInCompleteValue_ShouldThrowInvalidOperationExceptoin() { var writer = new CborWriter(); Assert.Throws<InvalidOperationException>(() => writer.Encode()); } [Fact] public static void CborWriter_WritingTwoPrimitiveValues_ShouldThrowInvalidOperationException() { var writer = new CborWriter(); writer.WriteInt64(42); int bytesWritten = writer.BytesWritten; Assert.Throws<InvalidOperationException>(() => writer.WriteTextString("lorem ipsum")); Assert.Equal(bytesWritten, writer.BytesWritten); } [Theory] [InlineData(1, 2, "0101")] [InlineData(10, 10, "0a0a0a0a0a0a0a0a0a0a")] [InlineData(new object[] { 1, 2 }, 3, "820102820102820102")] public static void CborWriter_MultipleRootLevelValuesAllowed_WritingMultipleRootValues_HappyPath(object value, int repetitions, string expectedHexEncoding) { byte[] expectedEncoding = expectedHexEncoding.HexToByteArray(); var writer = new CborWriter(allowMultipleRootLevelValues: true); for (int i = 0; i < repetitions; i++) { Helpers.WriteValue(writer, value); } AssertHelper.HexEqual(expectedEncoding, writer.Encode()); } [Fact] public static void GetEncoding_MultipleRootLevelValuesAllowed_PartialRootValue_ShouldThrowInvalidOperationException() { var writer = new CborWriter(allowMultipleRootLevelValues: true); writer.WriteStartArray(1); writer.WriteDouble(3.14); writer.WriteEndArray(); writer.WriteStartArray(1); writer.WriteDouble(3.14); // misses writer.WriteEndArray(); Assert.Throws<InvalidOperationException>(() => writer.Encode()); } [Fact] public static void BytesWritten_SingleValue_ShouldReturnBytesWritten() { var writer = new CborWriter(); Assert.Equal(0, writer.BytesWritten); writer.WriteTextString("test"); Assert.Equal(5, writer.BytesWritten); } [Fact] public static void Reset_NonTrivialWriter_HappyPath() { // Set up: build a nontrivial writer state. // Favor maps and Ctap2 canonicalization since // since that utilizes most of the moving parts. var writer = new CborWriter(conformanceMode: CborConformanceMode.Ctap2Canonical); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { writer.WriteStartMap(100); } else { writer.WriteStartArray(100); } } writer.WriteStartMap(3); writer.WriteInt32(1); // key writer.WriteInt32(2); // value writer.WriteInt32(-1); // key writer.WriteInt32(1); // value // End set up Assert.Equal(11, writer.CurrentDepth); Assert.True(writer.BytesWritten > 11, "must have written a nontrivial number of bytes to the buffer"); writer.Reset(); Assert.Equal(0, writer.CurrentDepth); Assert.Equal(0, writer.BytesWritten); // Write an object from scratch and validate that it is correct writer.WriteInt32(42); Assert.Equal(new byte[] { 0x18, 0x2a }, writer.Encode()); } [Fact] public static void ConformanceMode_DefaultValue_ShouldEqualStrict() { var writer = new CborWriter(); Assert.Equal(CborConformanceMode.Strict, writer.ConformanceMode); } [Fact] public static void ConvertIndefiniteLengthEncodings_DefaultValue_ShouldEqualFalse() { var writer = new CborWriter(); Assert.False(writer.ConvertIndefiniteLengthEncodings); } [Theory] [MemberData(nameof(EncodedValueInputs))] public static void WriteEncodedValue_RootValue_HappyPath(string hexEncodedValue) { byte[] encodedValue = hexEncodedValue.HexToByteArray(); var writer = new CborWriter(); writer.WriteEncodedValue(encodedValue); string hexResult = writer.Encode().ByteArrayToHex(); Assert.Equal(hexEncodedValue, hexResult.ToLower()); } [Theory] [InlineData(42)] [InlineData("value1")] [InlineData(new object[] { new object[] { 1, 2, 3 } })] public static void EncodeSpan_HappyPath(object value) { var writer = new CborWriter(); Helpers.WriteValue(writer, value); byte[] target = new byte[writer.BytesWritten]; int bytesWritten = writer.Encode(target); byte[] encoding = writer.Encode(); Assert.Equal(encoding.Length, bytesWritten); Assert.Equal(encoding, target); } [Theory] [InlineData(42)] [InlineData("value1")] [InlineData(new object[] { new object[] { 1, 2, 3 } })] public static void EncodeSpan_DestinationTooSmall_ShouldThrowArgumentException(object value) { var writer = new CborWriter(); Helpers.WriteValue(writer, value); byte[] encoding = writer.Encode(); byte[] target = new byte[encoding.Length - 1]; Assert.Throws<ArgumentException>(() => writer.Encode(target)); Assert.All(target, b => Assert.Equal(0, b)); } [Theory] [InlineData(42)] [InlineData("value1")] [InlineData(new object[] { new object[] { 1, 2, 3 } })] public static void TryEncode_HappyPath(object value) { var writer = new CborWriter(); Helpers.WriteValue(writer, value); byte[] encoding = writer.Encode(); byte[] target = new byte[encoding.Length]; bool result = writer.TryEncode(target, out int bytesWritten); Assert.True(result); Assert.Equal(encoding.Length, bytesWritten); Assert.Equal(encoding, target); } [Theory] [InlineData(42)] [InlineData("value1")] [InlineData(new object[] { new object[] { 1, 2, 3 } })] public static void TryEncode_DestinationTooSmall_ShouldReturnFalse(object value) { var writer = new CborWriter(); Helpers.WriteValue(writer, value); byte[] encoding = writer.Encode(); byte[] target = new byte[encoding.Length - 1]; bool result = writer.TryEncode(target, out int bytesWritten); Assert.False(result); Assert.Equal(0, bytesWritten); Assert.All(target, b => Assert.Equal(0, b)); } [Theory] [MemberData(nameof(EncodedValueInputs))] public static void WriteEncodedValue_NestedValue_HappyPath(string hexEncodedValue) { byte[] encodedValue = hexEncodedValue.HexToByteArray(); var writer = new CborWriter(); writer.WriteStartArray(3); writer.WriteInt64(1); writer.WriteEncodedValue(encodedValue); writer.WriteTextString(""); writer.WriteEndArray(); string hexResult = writer.Encode().ByteArrayToHex(); Assert.Equal("8301" + hexEncodedValue + "60", hexResult.ToLower()); } public const string Enc = Helpers.EncodedPrefixIdentifier; [Theory] [InlineData(new object[] { new object[] { Enc, "8101" } }, true, "818101")] [InlineData(new object[] { new object[] { Enc, "8101" } }, false, "9f8101ff")] [InlineData(new object[] { Map, new object[] { Enc, "8101" }, 42 }, true, "a18101182a")] [InlineData(new object[] { Map, new object[] { Enc, "8101" }, 42 }, false, "bf8101182aff")] [InlineData(new object[] { Map, 42, new object[] { Enc, "8101" } }, true, "a1182a8101")] [InlineData(new object[] { Map, 42, new object[] { Enc, "8101" } }, false, "bf182a8101ff")] public static void WriteEncodedValue_ContextScenaria_HappyPath(object value, bool useDefiniteLengthEncoding, string hexExpectedEncoding) { var writer = new CborWriter(convertIndefiniteLengthEncodings: useDefiniteLengthEncoding); Helpers.WriteValue(writer, value, useDefiniteLengthCollections: useDefiniteLengthEncoding); string hexEncoding = writer.Encode().ByteArrayToHex().ToLower(); Assert.Equal(hexExpectedEncoding, hexEncoding); } [Fact] public static void WriteEncodedValue_IndefiniteLengthTextString_HappyPath() { var writer = new CborWriter(convertIndefiniteLengthEncodings: false); writer.WriteStartIndefiniteLengthTextString(); writer.WriteTextString("foo"); writer.WriteEncodedValue("63626172".HexToByteArray()); writer.WriteEndIndefiniteLengthTextString(); byte[] encoding = writer.Encode(); Assert.Equal("7f63666f6f63626172ff", encoding.ByteArrayToHex().ToLower()); } [Fact] public static void WriteEncodedValue_IndefiniteLengthByteString_HappyPath() { var writer = new CborWriter(convertIndefiniteLengthEncodings: false); writer.WriteStartIndefiniteLengthByteString(); writer.WriteByteString(new byte[] { 1, 1, 1 }); writer.WriteEncodedValue("43020202".HexToByteArray()); writer.WriteEndIndefiniteLengthByteString(); byte[] encoding = writer.Encode(); Assert.Equal("5f4301010143020202ff", encoding.ByteArrayToHex().ToLower()); } [Fact] public static void WriteEncodedValue_BadIndefiniteLengthStringValue_ShouldThrowInvalidOperationException() { var writer = new CborWriter(); writer.WriteStartIndefiniteLengthTextString(); Assert.Throws<InvalidOperationException>(() => writer.WriteEncodedValue(new byte[] { 0x01 })); } [Fact] public static void WriteEncodedValue_AtEndOfDefiniteLengthCollection_ShouldThrowInvalidOperationException() { var writer = new CborWriter(); writer.WriteInt64(0); Assert.Throws<InvalidOperationException>(() => writer.WriteEncodedValue(new byte[] { 0x01 })); } [Theory] [MemberData(nameof(EncodedValueBadInputs))] public static void WriteEncodedValue_InvalidCbor_ShouldThrowArgumentException(string hexEncodedInput) { byte[] encodedInput = hexEncodedInput.HexToByteArray(); var writer = new CborWriter(); Assert.Throws<ArgumentException>(() => writer.WriteEncodedValue(encodedInput)); } [Theory] [InlineData(CborConformanceMode.Strict, "a201010101")] // duplicate key encodings [InlineData(CborConformanceMode.Canonical, "9f01ff")] // indefinite-length array [InlineData(CborConformanceMode.Ctap2Canonical, "a280800101")] // unsorted key encodings public static void WriteEncodedValue_InvalidConformance_ShouldThrowArgumentException(CborConformanceMode conformanceMode, string hexEncodedInput) { byte[] encodedInput = hexEncodedInput.HexToByteArray(); var writer = new CborWriter(conformanceMode); Assert.Throws<ArgumentException>(() => writer.WriteEncodedValue(encodedInput)); } [Fact] public static void WriteEncodedValue_ValidPayloadWithTrailingBytes_ShouldThrowArgumentException() { var writer = new CborWriter(); Assert.Throws<ArgumentException>(() => writer.WriteEncodedValue(new byte[] { 0x01, 0x01 })); } [Theory] [InlineData((CborConformanceMode)(-1))] public static void InvalidConformanceMode_ShouldThrowArgumentOutOfRangeException(CborConformanceMode mode) { Assert.Throws<ArgumentOutOfRangeException>(() => new CborWriter(conformanceMode: mode)); } public static IEnumerable<object[]> EncodedValueInputs => CborReaderTests.SampleCborValues.Select(x => new [] { x }); public static IEnumerable<object[]> EncodedValueBadInputs => CborReaderTests.InvalidCborValues.Select(x => new[] { x }); [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/37669", TestPlatforms.Browser)] [InlineData("a501020326200121582065eda5a12577c2bae829437fe338701a10aaa375e1bb5b5de108de439c08551d2258201e52ed75701163f7f9e40ddf9f341b3dc9ba860af7e0ca7ca7e9eecd0084d19c", "65eda5a12577c2bae829437fe338701a10aaa375e1bb5b5de108de439c08551d", "1e52ed75701163f7f9e40ddf9f341b3dc9ba860af7e0ca7ca7e9eecd0084d19c", "SHA256", "ECDSA_P256")] [InlineData("a501020338222002215830ed57d8608c5734a5ed5d22026bad8700636823e45297306479beb61a5bd6b04688c34a2f0de51d91064355eef7548bdd22583024376b4fee60ba65db61de54234575eec5d37e1184fbafa1f49d71e1795bba6bda9cbe2ebb815f9b49b371486b38fa1b", "ed57d8608c5734a5ed5d22026bad8700636823e45297306479beb61a5bd6b04688c34a2f0de51d91064355eef7548bdd", "24376b4fee60ba65db61de54234575eec5d37e1184fbafa1f49d71e1795bba6bda9cbe2ebb815f9b49b371486b38fa1b", "SHA384", "ECDSA_P384")] [InlineData("a50102033823200321584200b03811bef65e330bb974224ec3ab0a5469f038c92177b4171f6f66f91244d4476e016ee77cf7e155a4f73567627b5d72eaf0cb4a6036c6509a6432d7cd6a3b325c2258420114b597b6c271d8435cfa02e890608c93f5bc118ca7f47bf191e9f9e49a22f8a15962315f0729781e1d78b302970c832db2fa8f7f782a33f8e1514950dc7499035f", "00b03811bef65e330bb974224ec3ab0a5469f038c92177b4171f6f66f91244d4476e016ee77cf7e155a4f73567627b5d72eaf0cb4a6036c6509a6432d7cd6a3b325c", "0114b597b6c271d8435cfa02e890608c93f5bc118ca7f47bf191e9f9e49a22f8a15962315f0729781e1d78b302970c832db2fa8f7f782a33f8e1514950dc7499035f", "SHA512", "ECDSA_P521")] [InlineData("a40102200121582065eda5a12577c2bae829437fe338701a10aaa375e1bb5b5de108de439c08551d2258201e52ed75701163f7f9e40ddf9f341b3dc9ba860af7e0ca7ca7e9eecd0084d19c", "65eda5a12577c2bae829437fe338701a10aaa375e1bb5b5de108de439c08551d", "1e52ed75701163f7f9e40ddf9f341b3dc9ba860af7e0ca7ca7e9eecd0084d19c", null, "ECDSA_P256")] public static void CoseKeyHelpers_ECDsaExportCosePublicKey_HappyPath(string expectedHexEncoding, string hexQx, string hexQy, string? hashAlgorithmName, string curveFriendlyName) { byte[] expectedEncoding = expectedHexEncoding.HexToByteArray(); var hashAlgName = hashAlgorithmName != null ? new HashAlgorithmName(hashAlgorithmName) : (HashAlgorithmName?)null; var ecParameters = new ECParameters() { Curve = ECCurve.CreateFromFriendlyName(curveFriendlyName), Q = new ECPoint() { X = hexQx.HexToByteArray(), Y = hexQy.HexToByteArray() }, }; using ECDsa ecDsa = ECDsa.Create(ecParameters); byte[] coseKeyEncoding = CborCoseKeyHelpers.ExportECDsaPublicKey(ecDsa, hashAlgName); AssertHelper.HexEqual(expectedEncoding, coseKeyEncoding); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using Test.Cryptography; using Xunit; namespace System.Formats.Cbor.Tests { public partial class CborWriterTests { [Fact] public static void IsWriteCompleted_OnWrittenPrimitive_ShouldBeTrue() { var writer = new CborWriter(); Assert.False(writer.IsWriteCompleted); writer.WriteInt64(42); Assert.True(writer.IsWriteCompleted); } [Fact] public static void GetEncoding_OnInCompleteValue_ShouldThrowInvalidOperationExceptoin() { var writer = new CborWriter(); Assert.Throws<InvalidOperationException>(() => writer.Encode()); } [Fact] public static void CborWriter_WritingTwoPrimitiveValues_ShouldThrowInvalidOperationException() { var writer = new CborWriter(); writer.WriteInt64(42); int bytesWritten = writer.BytesWritten; Assert.Throws<InvalidOperationException>(() => writer.WriteTextString("lorem ipsum")); Assert.Equal(bytesWritten, writer.BytesWritten); } [Theory] [InlineData(1, 2, "0101")] [InlineData(10, 10, "0a0a0a0a0a0a0a0a0a0a")] [InlineData(new object[] { 1, 2 }, 3, "820102820102820102")] public static void CborWriter_MultipleRootLevelValuesAllowed_WritingMultipleRootValues_HappyPath(object value, int repetitions, string expectedHexEncoding) { byte[] expectedEncoding = expectedHexEncoding.HexToByteArray(); var writer = new CborWriter(allowMultipleRootLevelValues: true); for (int i = 0; i < repetitions; i++) { Helpers.WriteValue(writer, value); } AssertHelper.HexEqual(expectedEncoding, writer.Encode()); } [Fact] public static void GetEncoding_MultipleRootLevelValuesAllowed_PartialRootValue_ShouldThrowInvalidOperationException() { var writer = new CborWriter(allowMultipleRootLevelValues: true); writer.WriteStartArray(1); writer.WriteDouble(3.14); writer.WriteEndArray(); writer.WriteStartArray(1); writer.WriteDouble(3.14); // misses writer.WriteEndArray(); Assert.Throws<InvalidOperationException>(() => writer.Encode()); } [Fact] public static void BytesWritten_SingleValue_ShouldReturnBytesWritten() { var writer = new CborWriter(); Assert.Equal(0, writer.BytesWritten); writer.WriteTextString("test"); Assert.Equal(5, writer.BytesWritten); } [Fact] public static void Reset_NonTrivialWriter_HappyPath() { // Set up: build a nontrivial writer state. // Favor maps and Ctap2 canonicalization since // since that utilizes most of the moving parts. var writer = new CborWriter(conformanceMode: CborConformanceMode.Ctap2Canonical); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { writer.WriteStartMap(100); } else { writer.WriteStartArray(100); } } writer.WriteStartMap(3); writer.WriteInt32(1); // key writer.WriteInt32(2); // value writer.WriteInt32(-1); // key writer.WriteInt32(1); // value // End set up Assert.Equal(11, writer.CurrentDepth); Assert.True(writer.BytesWritten > 11, "must have written a nontrivial number of bytes to the buffer"); writer.Reset(); Assert.Equal(0, writer.CurrentDepth); Assert.Equal(0, writer.BytesWritten); // Write an object from scratch and validate that it is correct writer.WriteInt32(42); Assert.Equal(new byte[] { 0x18, 0x2a }, writer.Encode()); } [Fact] public static void ConformanceMode_DefaultValue_ShouldEqualStrict() { var writer = new CborWriter(); Assert.Equal(CborConformanceMode.Strict, writer.ConformanceMode); } [Fact] public static void ConvertIndefiniteLengthEncodings_DefaultValue_ShouldEqualFalse() { var writer = new CborWriter(); Assert.False(writer.ConvertIndefiniteLengthEncodings); } [Theory] [MemberData(nameof(EncodedValueInputs))] public static void WriteEncodedValue_RootValue_HappyPath(string hexEncodedValue) { byte[] encodedValue = hexEncodedValue.HexToByteArray(); var writer = new CborWriter(); writer.WriteEncodedValue(encodedValue); string hexResult = writer.Encode().ByteArrayToHex(); Assert.Equal(hexEncodedValue, hexResult.ToLower()); } [Theory] [InlineData(42)] [InlineData("value1")] [InlineData(new object[] { new object[] { 1, 2, 3 } })] public static void EncodeSpan_HappyPath(object value) { var writer = new CborWriter(); Helpers.WriteValue(writer, value); byte[] target = new byte[writer.BytesWritten]; int bytesWritten = writer.Encode(target); byte[] encoding = writer.Encode(); Assert.Equal(encoding.Length, bytesWritten); Assert.Equal(encoding, target); } [Theory] [InlineData(42)] [InlineData("value1")] [InlineData(new object[] { new object[] { 1, 2, 3 } })] public static void EncodeSpan_DestinationTooSmall_ShouldThrowArgumentException(object value) { var writer = new CborWriter(); Helpers.WriteValue(writer, value); byte[] encoding = writer.Encode(); byte[] target = new byte[encoding.Length - 1]; Assert.Throws<ArgumentException>(() => writer.Encode(target)); Assert.All(target, b => Assert.Equal(0, b)); } [Theory] [InlineData(42)] [InlineData("value1")] [InlineData(new object[] { new object[] { 1, 2, 3 } })] public static void TryEncode_HappyPath(object value) { var writer = new CborWriter(); Helpers.WriteValue(writer, value); byte[] encoding = writer.Encode(); byte[] target = new byte[encoding.Length]; bool result = writer.TryEncode(target, out int bytesWritten); Assert.True(result); Assert.Equal(encoding.Length, bytesWritten); Assert.Equal(encoding, target); } [Theory] [InlineData(42)] [InlineData("value1")] [InlineData(new object[] { new object[] { 1, 2, 3 } })] public static void TryEncode_DestinationTooSmall_ShouldReturnFalse(object value) { var writer = new CborWriter(); Helpers.WriteValue(writer, value); byte[] encoding = writer.Encode(); byte[] target = new byte[encoding.Length - 1]; bool result = writer.TryEncode(target, out int bytesWritten); Assert.False(result); Assert.Equal(0, bytesWritten); Assert.All(target, b => Assert.Equal(0, b)); } [Theory] [MemberData(nameof(EncodedValueInputs))] public static void WriteEncodedValue_NestedValue_HappyPath(string hexEncodedValue) { byte[] encodedValue = hexEncodedValue.HexToByteArray(); var writer = new CborWriter(); writer.WriteStartArray(3); writer.WriteInt64(1); writer.WriteEncodedValue(encodedValue); writer.WriteTextString(""); writer.WriteEndArray(); string hexResult = writer.Encode().ByteArrayToHex(); Assert.Equal("8301" + hexEncodedValue + "60", hexResult.ToLower()); } public const string Enc = Helpers.EncodedPrefixIdentifier; [Theory] [InlineData(new object[] { new object[] { Enc, "8101" } }, true, "818101")] [InlineData(new object[] { new object[] { Enc, "8101" } }, false, "9f8101ff")] [InlineData(new object[] { Map, new object[] { Enc, "8101" }, 42 }, true, "a18101182a")] [InlineData(new object[] { Map, new object[] { Enc, "8101" }, 42 }, false, "bf8101182aff")] [InlineData(new object[] { Map, 42, new object[] { Enc, "8101" } }, true, "a1182a8101")] [InlineData(new object[] { Map, 42, new object[] { Enc, "8101" } }, false, "bf182a8101ff")] public static void WriteEncodedValue_ContextScenaria_HappyPath(object value, bool useDefiniteLengthEncoding, string hexExpectedEncoding) { var writer = new CborWriter(convertIndefiniteLengthEncodings: useDefiniteLengthEncoding); Helpers.WriteValue(writer, value, useDefiniteLengthCollections: useDefiniteLengthEncoding); string hexEncoding = writer.Encode().ByteArrayToHex().ToLower(); Assert.Equal(hexExpectedEncoding, hexEncoding); } [Fact] public static void WriteEncodedValue_IndefiniteLengthTextString_HappyPath() { var writer = new CborWriter(convertIndefiniteLengthEncodings: false); writer.WriteStartIndefiniteLengthTextString(); writer.WriteTextString("foo"); writer.WriteEncodedValue("63626172".HexToByteArray()); writer.WriteEndIndefiniteLengthTextString(); byte[] encoding = writer.Encode(); Assert.Equal("7f63666f6f63626172ff", encoding.ByteArrayToHex().ToLower()); } [Fact] public static void WriteEncodedValue_IndefiniteLengthByteString_HappyPath() { var writer = new CborWriter(convertIndefiniteLengthEncodings: false); writer.WriteStartIndefiniteLengthByteString(); writer.WriteByteString(new byte[] { 1, 1, 1 }); writer.WriteEncodedValue("43020202".HexToByteArray()); writer.WriteEndIndefiniteLengthByteString(); byte[] encoding = writer.Encode(); Assert.Equal("5f4301010143020202ff", encoding.ByteArrayToHex().ToLower()); } [Fact] public static void WriteEncodedValue_BadIndefiniteLengthStringValue_ShouldThrowInvalidOperationException() { var writer = new CborWriter(); writer.WriteStartIndefiniteLengthTextString(); Assert.Throws<InvalidOperationException>(() => writer.WriteEncodedValue(new byte[] { 0x01 })); } [Fact] public static void WriteEncodedValue_AtEndOfDefiniteLengthCollection_ShouldThrowInvalidOperationException() { var writer = new CborWriter(); writer.WriteInt64(0); Assert.Throws<InvalidOperationException>(() => writer.WriteEncodedValue(new byte[] { 0x01 })); } [Theory] [MemberData(nameof(EncodedValueBadInputs))] public static void WriteEncodedValue_InvalidCbor_ShouldThrowArgumentException(string hexEncodedInput) { byte[] encodedInput = hexEncodedInput.HexToByteArray(); var writer = new CborWriter(); Assert.Throws<ArgumentException>(() => writer.WriteEncodedValue(encodedInput)); } [Theory] [InlineData(CborConformanceMode.Strict, "a201010101")] // duplicate key encodings [InlineData(CborConformanceMode.Canonical, "9f01ff")] // indefinite-length array [InlineData(CborConformanceMode.Ctap2Canonical, "a280800101")] // unsorted key encodings public static void WriteEncodedValue_InvalidConformance_ShouldThrowArgumentException(CborConformanceMode conformanceMode, string hexEncodedInput) { byte[] encodedInput = hexEncodedInput.HexToByteArray(); var writer = new CborWriter(conformanceMode); Assert.Throws<ArgumentException>(() => writer.WriteEncodedValue(encodedInput)); } [Fact] public static void WriteEncodedValue_ValidPayloadWithTrailingBytes_ShouldThrowArgumentException() { var writer = new CborWriter(); Assert.Throws<ArgumentException>(() => writer.WriteEncodedValue(new byte[] { 0x01, 0x01 })); } [Theory] [InlineData((CborConformanceMode)(-1))] public static void InvalidConformanceMode_ShouldThrowArgumentOutOfRangeException(CborConformanceMode mode) { Assert.Throws<ArgumentOutOfRangeException>(() => new CborWriter(conformanceMode: mode)); } public static IEnumerable<object[]> EncodedValueInputs => CborReaderTests.SampleCborValues.Select(x => new [] { x }); public static IEnumerable<object[]> EncodedValueBadInputs => CborReaderTests.InvalidCborValues.Select(x => new[] { x }); [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/37669", TestPlatforms.Browser)] [InlineData("a501020326200121582065eda5a12577c2bae829437fe338701a10aaa375e1bb5b5de108de439c08551d2258201e52ed75701163f7f9e40ddf9f341b3dc9ba860af7e0ca7ca7e9eecd0084d19c", "65eda5a12577c2bae829437fe338701a10aaa375e1bb5b5de108de439c08551d", "1e52ed75701163f7f9e40ddf9f341b3dc9ba860af7e0ca7ca7e9eecd0084d19c", "SHA256", "ECDSA_P256")] [InlineData("a501020338222002215830ed57d8608c5734a5ed5d22026bad8700636823e45297306479beb61a5bd6b04688c34a2f0de51d91064355eef7548bdd22583024376b4fee60ba65db61de54234575eec5d37e1184fbafa1f49d71e1795bba6bda9cbe2ebb815f9b49b371486b38fa1b", "ed57d8608c5734a5ed5d22026bad8700636823e45297306479beb61a5bd6b04688c34a2f0de51d91064355eef7548bdd", "24376b4fee60ba65db61de54234575eec5d37e1184fbafa1f49d71e1795bba6bda9cbe2ebb815f9b49b371486b38fa1b", "SHA384", "ECDSA_P384")] [InlineData("a50102033823200321584200b03811bef65e330bb974224ec3ab0a5469f038c92177b4171f6f66f91244d4476e016ee77cf7e155a4f73567627b5d72eaf0cb4a6036c6509a6432d7cd6a3b325c2258420114b597b6c271d8435cfa02e890608c93f5bc118ca7f47bf191e9f9e49a22f8a15962315f0729781e1d78b302970c832db2fa8f7f782a33f8e1514950dc7499035f", "00b03811bef65e330bb974224ec3ab0a5469f038c92177b4171f6f66f91244d4476e016ee77cf7e155a4f73567627b5d72eaf0cb4a6036c6509a6432d7cd6a3b325c", "0114b597b6c271d8435cfa02e890608c93f5bc118ca7f47bf191e9f9e49a22f8a15962315f0729781e1d78b302970c832db2fa8f7f782a33f8e1514950dc7499035f", "SHA512", "ECDSA_P521")] [InlineData("a40102200121582065eda5a12577c2bae829437fe338701a10aaa375e1bb5b5de108de439c08551d2258201e52ed75701163f7f9e40ddf9f341b3dc9ba860af7e0ca7ca7e9eecd0084d19c", "65eda5a12577c2bae829437fe338701a10aaa375e1bb5b5de108de439c08551d", "1e52ed75701163f7f9e40ddf9f341b3dc9ba860af7e0ca7ca7e9eecd0084d19c", null, "ECDSA_P256")] public static void CoseKeyHelpers_ECDsaExportCosePublicKey_HappyPath(string expectedHexEncoding, string hexQx, string hexQy, string? hashAlgorithmName, string curveFriendlyName) { byte[] expectedEncoding = expectedHexEncoding.HexToByteArray(); var hashAlgName = hashAlgorithmName != null ? new HashAlgorithmName(hashAlgorithmName) : (HashAlgorithmName?)null; var ecParameters = new ECParameters() { Curve = ECCurve.CreateFromFriendlyName(curveFriendlyName), Q = new ECPoint() { X = hexQx.HexToByteArray(), Y = hexQy.HexToByteArray() }, }; using ECDsa ecDsa = ECDsa.Create(ecParameters); byte[] coseKeyEncoding = CborCoseKeyHelpers.ExportECDsaPublicKey(ecDsa, hashAlgName); AssertHelper.HexEqual(expectedEncoding, coseKeyEncoding); } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Store.Vector64.Int32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; 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 Store_Vector64_Int32() { var test = new StoreUnaryOpTest__Store_Vector64_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class StoreUnaryOpTest__Store_Vector64_Int32 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(StoreUnaryOpTest__Store_Vector64_Int32 testClass) { AdvSimd.Store((Int32*)testClass._dataTable.outArrayPtr, _fld1); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(StoreUnaryOpTest__Store_Vector64_Int32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) { AdvSimd.Store((Int32*)testClass._dataTable.outArrayPtr, AdvSimd.LoadVector64((Int32*)(pFld1))); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Vector64<Int32> _clsVar1; private Vector64<Int32> _fld1; private DataTable _dataTable; static StoreUnaryOpTest__Store_Vector64_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public StoreUnaryOpTest__Store_Vector64_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr))); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); typeof(AdvSimd).GetMethod(nameof(AdvSimd.Store), new Type[] { typeof(Int32*), typeof(Vector64<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); typeof(AdvSimd).GetMethod(nameof(AdvSimd.Store), new Type[] { typeof(Int32*), typeof(Vector64<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, _clsVar1); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) { AdvSimd.Store((Int32*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int32*)(pClsVar1))); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, op1); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, op1); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new StoreUnaryOpTest__Store_Vector64_Int32(); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, test._fld1); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new StoreUnaryOpTest__Store_Vector64_Int32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) { AdvSimd.Store((Int32*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int32*)(pFld1))); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, _fld1); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) { AdvSimd.Store((Int32*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int32*)(pFld1))); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, test._fld1); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int32*)(&test._fld1))); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> op1, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < RetElementCount; i++) { if (firstOp[i] != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Store)}<Int32>(Vector64<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; 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 Store_Vector64_Int32() { var test = new StoreUnaryOpTest__Store_Vector64_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class StoreUnaryOpTest__Store_Vector64_Int32 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(StoreUnaryOpTest__Store_Vector64_Int32 testClass) { AdvSimd.Store((Int32*)testClass._dataTable.outArrayPtr, _fld1); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(StoreUnaryOpTest__Store_Vector64_Int32 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) { AdvSimd.Store((Int32*)testClass._dataTable.outArrayPtr, AdvSimd.LoadVector64((Int32*)(pFld1))); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Vector64<Int32> _clsVar1; private Vector64<Int32> _fld1; private DataTable _dataTable; static StoreUnaryOpTest__Store_Vector64_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public StoreUnaryOpTest__Store_Vector64_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr))); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); typeof(AdvSimd).GetMethod(nameof(AdvSimd.Store), new Type[] { typeof(Int32*), typeof(Vector64<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); typeof(AdvSimd).GetMethod(nameof(AdvSimd.Store), new Type[] { typeof(Int32*), typeof(Vector64<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, _clsVar1); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) { AdvSimd.Store((Int32*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int32*)(pClsVar1))); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, op1); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, op1); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new StoreUnaryOpTest__Store_Vector64_Int32(); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, test._fld1); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new StoreUnaryOpTest__Store_Vector64_Int32(); fixed (Vector64<Int32>* pFld1 = &test._fld1) { AdvSimd.Store((Int32*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int32*)(pFld1))); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, _fld1); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) { AdvSimd.Store((Int32*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int32*)(pFld1))); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, test._fld1); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); AdvSimd.Store((Int32*)_dataTable.outArrayPtr, AdvSimd.LoadVector64((Int32*)(&test._fld1))); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> op1, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < RetElementCount; i++) { if (firstOp[i] != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Store)}<Int32>(Vector64<Int32>): {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,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/baseservices/exceptions/generics/genericexceptions03.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.Globalization; using System.IO; class MyException : Exception { } public class Help { public static Exception s_exceptionToThrow; public static bool s_matchingException; public static Object s_object = new object(); } public class A<T> where T: Exception { public static void StaticFunctionWithFewArgs() { try { throw Help.s_exceptionToThrow; } catch (T match) { if (!Help.s_matchingException) throw new Exception("This should not have been caught here", match); Console.WriteLine("Caught matching " + match.GetType()); } catch (Exception mismatch) { if (Help.s_matchingException) throw new Exception("Should have been caught above", mismatch); Console.WriteLine("Expected mismatch " + mismatch.GetType()); } } } public class GenericExceptions { public static void StaticFunctionWithFewArgs() { Help.s_matchingException = true; Help.s_exceptionToThrow = new MyException(); A<Exception>.StaticFunctionWithFewArgs(); A<MyException>.StaticFunctionWithFewArgs(); Help.s_matchingException = false; Help.s_exceptionToThrow = new Exception(); A<MyException>.StaticFunctionWithFewArgs(); } [System.Runtime.CompilerServices.MethodImpl( System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static int Main() { try { Console.WriteLine("This test checks that we can catch generic exceptions."); Console.WriteLine("All exceptions should be handled by the test itself"); StaticFunctionWithFewArgs(); } catch(Exception) { Console.WriteLine("Test Failed"); return -1; } Console.WriteLine("Test Passed"); return 100; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Globalization; using System.IO; class MyException : Exception { } public class Help { public static Exception s_exceptionToThrow; public static bool s_matchingException; public static Object s_object = new object(); } public class A<T> where T: Exception { public static void StaticFunctionWithFewArgs() { try { throw Help.s_exceptionToThrow; } catch (T match) { if (!Help.s_matchingException) throw new Exception("This should not have been caught here", match); Console.WriteLine("Caught matching " + match.GetType()); } catch (Exception mismatch) { if (Help.s_matchingException) throw new Exception("Should have been caught above", mismatch); Console.WriteLine("Expected mismatch " + mismatch.GetType()); } } } public class GenericExceptions { public static void StaticFunctionWithFewArgs() { Help.s_matchingException = true; Help.s_exceptionToThrow = new MyException(); A<Exception>.StaticFunctionWithFewArgs(); A<MyException>.StaticFunctionWithFewArgs(); Help.s_matchingException = false; Help.s_exceptionToThrow = new Exception(); A<MyException>.StaticFunctionWithFewArgs(); } [System.Runtime.CompilerServices.MethodImpl( System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static int Main() { try { Console.WriteLine("This test checks that we can catch generic exceptions."); Console.WriteLine("All exceptions should be handled by the test itself"); StaticFunctionWithFewArgs(); } catch(Exception) { Console.WriteLine("Test Failed"); return -1; } Console.WriteLine("Test Passed"); return 100; } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Reflection.DispatchProxy/tests/DispatchProxyTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Loader; using System.Text; using Xunit; namespace DispatchProxyTests { public static class DispatchProxyTests { [Fact] public static void Create_Proxy_Derives_From_DispatchProxy_BaseType() { TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); Assert.NotNull(proxy); Assert.IsAssignableFrom<TestDispatchProxy>(proxy); } [Fact] public static void Create_Proxy_Implements_All_Interfaces() { TestType_IHelloAndGoodbyeService proxy = DispatchProxy.Create<TestType_IHelloAndGoodbyeService, TestDispatchProxy>(); Assert.NotNull(proxy); Type[] implementedInterfaces = typeof(TestType_IHelloAndGoodbyeService).GetTypeInfo().ImplementedInterfaces.ToArray(); foreach (Type t in implementedInterfaces) { Assert.IsAssignableFrom(t, proxy); } } [Fact] public static void Create_Proxy_Internal_Interface() { TestType_InternalInterfaceService proxy = DispatchProxy.Create<TestType_InternalInterfaceService, TestDispatchProxy>(); Assert.NotNull(proxy); } [Fact] public static void Create_Proxy_Implements_Internal_Interfaces() { TestType_InternalInterfaceService proxy = DispatchProxy.Create<TestType_PublicInterfaceService_Implements_Internal, TestDispatchProxy>(); Assert.NotNull(proxy); // ensure we emit a valid attribute definition Type iactAttributeType = proxy.GetType().Assembly.GetType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute"); Assert.NotNull(iactAttributeType); ConstructorInfo constructor = iactAttributeType.GetConstructor(new[] { typeof(string) }); Assert.NotNull(constructor); PropertyInfo propertyInfo = iactAttributeType.GetProperty("AssemblyName"); Assert.NotNull(propertyInfo); Assert.NotNull(propertyInfo.GetMethod); string name = "anAssemblyName"; object attributeInstance = constructor.Invoke(new object[] { name }); Assert.NotNull(attributeInstance); object actualName = propertyInfo.GetMethod.Invoke(attributeInstance, null); Assert.Equal(name, actualName); } [Fact] public static void Create_Same_Proxy_Type_And_Base_Type_Reuses_Same_Generated_Type() { TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); TestType_IHelloService proxy2 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); Assert.NotNull(proxy1); Assert.NotNull(proxy2); Assert.IsType(proxy1.GetType(), proxy2); } [Fact] public static void Create_Proxy_Instances_Of_Same_Proxy_And_Base_Type_Are_Unique() { TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); TestType_IHelloService proxy2 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); Assert.NotNull(proxy1); Assert.NotNull(proxy2); Assert.False(object.ReferenceEquals(proxy1, proxy2), string.Format("First and second instance of proxy type {0} were the same instance", proxy1.GetType().ToString())); } [Fact] public static void Create_Same_Proxy_Type_With_Different_BaseType_Uses_Different_Generated_Type() { TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); TestType_IHelloService proxy2 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy2>(); Assert.NotNull(proxy1); Assert.NotNull(proxy2); Assert.False(proxy1.GetType() == proxy2.GetType(), string.Format("Proxy generated for base type {0} used same for base type {1}", typeof(TestDispatchProxy).Name, typeof(TestDispatchProxy).Name)); } [Fact] public static void Created_Proxy_With_Different_Proxy_Type_Use_Different_Generated_Type() { TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); TestType_IGoodbyeService proxy2 = DispatchProxy.Create<TestType_IGoodbyeService, TestDispatchProxy>(); Assert.NotNull(proxy1); Assert.NotNull(proxy2); Assert.False(proxy1.GetType() == proxy2.GetType(), string.Format("Proxy generated for type {0} used same for type {1}", typeof(TestType_IHelloService).Name, typeof(TestType_IGoodbyeService).Name)); } [Fact] public static void Create_Using_Concrete_Proxy_Type_Throws_ArgumentException() { AssertExtensions.Throws<ArgumentException>("T", () => DispatchProxy.Create<TestType_ConcreteClass, TestDispatchProxy>()); } [Fact] public static void Create_Using_Sealed_BaseType_Throws_ArgumentException() { AssertExtensions.Throws<ArgumentException>("TProxy", () => DispatchProxy.Create<TestType_IHelloService, Sealed_TestDispatchProxy>()); } [Fact] public static void Create_Using_Abstract_BaseType_Throws_ArgumentException() { AssertExtensions.Throws<ArgumentException>("TProxy", () => DispatchProxy.Create<TestType_IHelloService, Abstract_TestDispatchProxy>()); } [Fact] public static void Create_Using_BaseType_Without_Default_Ctor_Throws_ArgumentException() { AssertExtensions.Throws<ArgumentException>("TProxy", () => DispatchProxy.Create<TestType_IHelloService, NoDefaultCtor_TestDispatchProxy>()); } [Fact] public static void Create_Using_PrivateProxy() { Assert.NotNull(TestType_PrivateProxy.Proxy<TestType_IHelloService>()); } [Fact] public static void Create_Using_PrivateProxyAndInternalService() { Assert.NotNull(TestType_PrivateProxy.Proxy<TestType_InternalInterfaceService>()); } [Fact] public static void Create_Using_PrivateProxyAndInternalServiceWithExternalGenericArgument() { Assert.NotNull(TestType_PrivateProxy.Proxy<TestType_InternalInterfaceWithNonPublicExternalGenericArgument>()); } [Fact] public static void Create_Using_InternalProxy() { Assert.NotNull(DispatchProxy.Create<TestType_InternalInterfaceService, InternalInvokeProxy>()); } [Fact] public static void Create_Using_ExternalNonPublicService() { Assert.NotNull(DispatchProxy.Create<DispatchProxyTestDependency.TestType_IExternalNonPublicHiService, TestDispatchProxy>()); } [Fact] public static void Create_Using_InternalProxyWithExternalNonPublicBaseType() { Assert.NotNull(DispatchProxy.Create<TestType_IHelloService, TestType_InternalProxyInternalBaseType>()); } [Fact] public static void Create_Using_InternalServiceImplementingNonPublicExternalService() { Assert.NotNull(DispatchProxy.Create<TestType_InternalInterfaceImplementsNonPublicExternalType, TestDispatchProxy>()); } [Fact] public static void Create_Using_InternalServiceWithGenericArgumentBeingNonPublicExternalService() { Assert.NotNull(DispatchProxy.Create<TestType_InternalInterfaceWithNonPublicExternalGenericArgument, TestDispatchProxy>()); } [Fact] public static void Create_Using_InternalProxyWithBaseTypeImplementingServiceWithgenericArgumentBeingNonPublicExternalService() { Assert.NotNull(DispatchProxy.Create<TestType_IHelloService, TestType_InternalProxyImplementingInterfaceWithGenericArgumentBeingNonPublicExternalType>()); } [Fact] public static void Invoke_Receives_Correct_MethodInfo_And_Arguments() { bool wasInvoked = false; StringBuilder errorBuilder = new StringBuilder(); // This Func is called whenever we call a method on the proxy. // This is where we validate it received the correct arguments and methods Func<MethodInfo, object[], object> invokeCallback = (method, args) => { wasInvoked = true; if (method == null) { string error = string.Format("Proxy for {0} was called with null method", typeof(TestType_IHelloService).Name); errorBuilder.AppendLine(error); return null; } else { MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello"); if (expectedMethod != method) { string error = string.Format("Proxy for {0} was called with incorrect method. Expected = {1}, Actual = {2}", typeof(TestType_IHelloService).Name, expectedMethod, method); errorBuilder.AppendLine(error); return null; } } return "success"; }; TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); Assert.NotNull(proxy); TestDispatchProxy dispatchProxy = proxy as TestDispatchProxy; Assert.NotNull(dispatchProxy); // Redirect Invoke to our own Func above dispatchProxy.CallOnInvoke = invokeCallback; // Calling this method now will invoke the Func above which validates correct method proxy.Hello("testInput"); Assert.True(wasInvoked, "The invoke method was not called"); Assert.True(errorBuilder.Length == 0, errorBuilder.ToString()); } [Fact] public static void Invoke_Receives_Correct_MethodInfo() { MethodInfo invokedMethod = null; TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethod = method; return string.Empty; }; proxy.Hello("testInput"); MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello"); Assert.True(invokedMethod != null && expectedMethod == invokedMethod, string.Format("Invoke expected method {0} but actual was {1}", expectedMethod, invokedMethod)); } [Fact] public static void Invoke_Receives_Correct_Arguments() { object[] actualArgs = null; TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { actualArgs = args; return string.Empty; }; proxy.Hello("testInput"); object[] expectedArgs = new object[] { "testInput" }; Assert.True(actualArgs != null && actualArgs.Length == expectedArgs.Length, string.Format("Invoked expected object[] of length {0} but actual was {1}", expectedArgs.Length, (actualArgs == null ? "null" : actualArgs.Length.ToString()))); for (int i = 0; i < expectedArgs.Length; ++i) { Assert.True(expectedArgs[i].Equals(actualArgs[i]), string.Format("Expected arg[{0}] = '{1}' but actual was '{2}'", i, expectedArgs[i], actualArgs[i])); } } [Fact] public static void Invoke_Returns_Correct_Value() { TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { return "testReturn"; }; string expectedResult = "testReturn"; string actualResult = proxy.Hello(expectedResult); Assert.Equal(expectedResult, actualResult); } [Fact] public static void Invoke_Multiple_Parameters_Receives_Correct_Arguments() { object[] invokedArgs = null; object[] expectedArgs = new object[] { (int)42, "testString", (double)5.0 }; TestType_IMultipleParameterService proxy = DispatchProxy.Create<TestType_IMultipleParameterService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedArgs = args; return 0.0; }; proxy.TestMethod((int)expectedArgs[0], (string)expectedArgs[1], (double)expectedArgs[2]); Assert.True(invokedArgs != null && invokedArgs.Length == expectedArgs.Length, string.Format("Expected {0} arguments but actual was {1}", expectedArgs.Length, invokedArgs == null ? "null" : invokedArgs.Length.ToString())); for (int i = 0; i < expectedArgs.Length; ++i) { Assert.True(expectedArgs[i].Equals(invokedArgs[i]), string.Format("Expected arg[{0}] = '{1}' but actual was '{2}'", i, expectedArgs[i], invokedArgs[i])); } } [Fact] public static void Invoke_Multiple_Parameters_Via_Params_Receives_Correct_Arguments() { object[] actualArgs = null; object[] invokedArgs = null; object[] expectedArgs = new object[] { 42, "testString", 5.0 }; TestType_IMultipleParameterService proxy = DispatchProxy.Create<TestType_IMultipleParameterService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedArgs = args; return string.Empty; }; proxy.ParamsMethod((int)expectedArgs[0], (string)expectedArgs[1], (double)expectedArgs[2]); // All separate params should have become a single object[1] array Assert.True(invokedArgs != null && invokedArgs.Length == 1, string.Format("Expected single element object[] but actual was {0}", invokedArgs == null ? "null" : invokedArgs.Length.ToString())); // That object[1] should contain an object[3] containing the args actualArgs = invokedArgs[0] as object[]; Assert.True(actualArgs != null && actualArgs.Length == expectedArgs.Length, string.Format("Invoked expected object[] of length {0} but actual was {1}", expectedArgs.Length, (actualArgs == null ? "null" : actualArgs.Length.ToString()))); for (int i = 0; i < expectedArgs.Length; ++i) { Assert.True(expectedArgs[i].Equals(actualArgs[i]), string.Format("Expected arg[{0}] = '{1}' but actual was '{2}'", i, expectedArgs[i], actualArgs[i])); } } [Fact] public static void Invoke_Void_Returning_Method_Accepts_Null_Return() { MethodInfo invokedMethod = null; TestType_IOneWay proxy = DispatchProxy.Create<TestType_IOneWay, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethod = method; return null; }; proxy.OneWay(); MethodInfo expectedMethod = typeof(TestType_IOneWay).GetTypeInfo().GetDeclaredMethod("OneWay"); Assert.True(invokedMethod != null && expectedMethod == invokedMethod, string.Format("Invoke expected method {0} but actual was {1}", expectedMethod, invokedMethod)); } [Fact] public static void Invoke_Same_Method_Multiple_Interfaces_Calls_Correct_Method() { List<MethodInfo> invokedMethods = new List<MethodInfo>(); TestType_IHelloService1And2 proxy = DispatchProxy.Create<TestType_IHelloService1And2, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethods.Add(method); return null; }; ((TestType_IHelloService)proxy).Hello("calling 1"); ((TestType_IHelloService2)proxy).Hello("calling 2"); Assert.True(invokedMethods.Count == 2, string.Format("Expected 2 method invocations but received {0}", invokedMethods.Count)); MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello"); Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], string.Format("First invoke should have been TestType_IHelloService.Hello but actual was {0}", invokedMethods[0])); expectedMethod = typeof(TestType_IHelloService2).GetTypeInfo().GetDeclaredMethod("Hello"); Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], string.Format("Second invoke should have been TestType_IHelloService2.Hello but actual was {0}", invokedMethods[1])); } [Fact] public static void Invoke_Thrown_Exception_Rethrown_To_Caller() { Exception actualException = null; InvalidOperationException expectedException = new InvalidOperationException("testException"); TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { throw expectedException; }; try { proxy.Hello("testCall"); } catch (Exception e) { actualException = e; } Assert.Equal(expectedException, actualException); } [Fact] public static void Invoke_Property_Setter_And_Getter_Invokes_Correct_Methods() { List<MethodInfo> invokedMethods = new List<MethodInfo>(); TestType_IPropertyService proxy = DispatchProxy.Create<TestType_IPropertyService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethods.Add(method); return null; }; proxy.ReadWrite = "testValue"; string actualValue = proxy.ReadWrite; Assert.True(invokedMethods.Count == 2, string.Format("Expected 2 method invocations but received {0}", invokedMethods.Count)); PropertyInfo propertyInfo = typeof(TestType_IPropertyService).GetTypeInfo().GetDeclaredProperty("ReadWrite"); Assert.NotNull(propertyInfo); MethodInfo expectedMethod = propertyInfo.SetMethod; Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], string.Format("First invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[0])); expectedMethod = propertyInfo.GetMethod; Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], string.Format("Second invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[1])); Assert.Null(actualValue); } [Fact] public static void Proxy_Declares_Interface_Properties() { TestType_IPropertyService proxy = DispatchProxy.Create<TestType_IPropertyService, TestDispatchProxy>(); PropertyInfo propertyInfo = proxy.GetType().GetTypeInfo().GetDeclaredProperty("ReadWrite"); Assert.NotNull(propertyInfo); } #if NETCOREAPP [Fact] public static void Invoke_Event_Add_And_Remove_And_Raise_Invokes_Correct_Methods() { // C# cannot emit raise_Xxx method for the event, so we must use System.Reflection.Emit to generate such event. AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("EventBuilder"), AssemblyBuilderAccess.Run); ModuleBuilder modb = ab.DefineDynamicModule("mod"); TypeBuilder tb = modb.DefineType("TestType_IEventService", TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract); EventBuilder eb = tb.DefineEvent("AddRemoveRaise", EventAttributes.None, typeof(EventHandler)); eb.SetAddOnMethod(tb.DefineMethod("add_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventHandler) })); eb.SetRemoveOnMethod(tb.DefineMethod("remove_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventHandler) })); eb.SetRaiseMethod(tb.DefineMethod("raise_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventArgs) })); TypeInfo ieventServiceTypeInfo = tb.CreateTypeInfo(); List<MethodInfo> invokedMethods = new List<MethodInfo>(); object proxy = typeof(DispatchProxy) .GetRuntimeMethod("Create", Type.EmptyTypes).MakeGenericMethod(ieventServiceTypeInfo.AsType(), typeof(TestDispatchProxy)) .Invoke(null, null); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethods.Add(method); return null; }; EventHandler handler = new EventHandler((sender, e) => { }); proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "add_AddRemoveRaise").Invoke(proxy, new object[] { handler }); proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "raise_AddRemoveRaise").Invoke(proxy, new object[] { EventArgs.Empty }); proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "remove_AddRemoveRaise").Invoke(proxy, new object[] { handler }); Assert.True(invokedMethods.Count == 3, String.Format("Expected 3 method invocations but received {0}", invokedMethods.Count)); EventInfo eventInfo = ieventServiceTypeInfo.GetDeclaredEvent("AddRemoveRaise"); Assert.NotNull(eventInfo); MethodInfo expectedMethod = eventInfo.AddMethod; Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[0])); expectedMethod = eventInfo.RaiseMethod; Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[1])); expectedMethod = eventInfo.RemoveMethod; Assert.True(invokedMethods[2] != null && expectedMethod == invokedMethods[2], String.Format("Third invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[1])); } #endif [Fact] public static void Proxy_Declares_Interface_Events() { TestType_IEventService proxy = DispatchProxy.Create<TestType_IEventService, TestDispatchProxy>(); EventInfo eventInfo = proxy.GetType().GetTypeInfo().GetDeclaredEvent("AddRemove"); Assert.NotNull(eventInfo); } [Fact] public static void Invoke_Indexer_Setter_And_Getter_Invokes_Correct_Methods() { List<MethodInfo> invokedMethods = new List<MethodInfo>(); TestType_IIndexerService proxy = DispatchProxy.Create<TestType_IIndexerService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethods.Add(method); return null; }; proxy["key"] = "testValue"; string actualValue = proxy["key"]; Assert.True(invokedMethods.Count == 2, string.Format("Expected 2 method invocations but received {0}", invokedMethods.Count)); PropertyInfo propertyInfo = typeof(TestType_IIndexerService).GetTypeInfo().GetDeclaredProperty("Item"); Assert.NotNull(propertyInfo); MethodInfo expectedMethod = propertyInfo.SetMethod; Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], string.Format("First invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[0])); expectedMethod = propertyInfo.GetMethod; Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], string.Format("Second invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[1])); Assert.Null(actualValue); } [Fact] public static void Proxy_Declares_Interface_Indexers() { TestType_IIndexerService proxy = DispatchProxy.Create<TestType_IIndexerService, TestDispatchProxy>(); PropertyInfo propertyInfo = proxy.GetType().GetTypeInfo().GetDeclaredProperty("Item"); Assert.NotNull(propertyInfo); } static void testGenericMethodRoundTrip<T>(T testValue) { var proxy = DispatchProxy.Create<TypeType_GenericMethod, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (mi, a) => { Assert.True(mi.IsGenericMethod); Assert.False(mi.IsGenericMethodDefinition); Assert.Equal(1, mi.GetParameters().Length); Assert.Equal(typeof(T), mi.GetParameters()[0].ParameterType); Assert.Equal(typeof(T), mi.ReturnType); return a[0]; }; Assert.Equal(proxy.Echo(testValue), testValue); } [Fact] public static void Invoke_Generic_Method() { //string testGenericMethodRoundTrip("asdf"); //reference type testGenericMethodRoundTrip(new Version(1, 0, 0, 0)); //value type testGenericMethodRoundTrip(42); //enum type testGenericMethodRoundTrip(DayOfWeek.Monday); } [Fact] public static void Invoke_Ref_Out_In_Method() { string value = "Hello"; testRefOutInInvocation(p => p.InAttribute(value), "Hello"); testRefOutInInvocation(p => p.InAttribute_OutAttribute(value), "Hello"); testRefOutInInvocation(p => p.InAttribute_Ref(ref value), "Hello"); testRefOutInInvocation(p => p.Out(out _), null); testRefOutInInvocation(p => p.OutAttribute(value), "Hello"); testRefOutInInvocation(p => p.Ref(ref value), "Hello"); testRefOutInInvocation(p => p.In(in value), "Hello"); } private static void testRefOutInInvocation(Action<TestType_IOut_Ref> invocation, string expected) { var proxy = DispatchProxy.Create<TestType_IOut_Ref, TestDispatchProxy>(); string result = "Failed"; ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { result = args[0] as string; return null; }; invocation(proxy); Assert.Equal(expected, result); } private static TestType_IHelloService CreateTestHelloProxy() => DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); [ActiveIssue("https://github.com/dotnet/runtime/issues/62503", TestRuntimes.Mono)] [Fact] public static void Test_Unloadability() { if (typeof(DispatchProxyTests).Assembly.Location == "") return; WeakReference wr = CreateProxyInUnloadableAlc(); for (int i = 0; i < 10 && wr.IsAlive; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } Assert.False(wr.IsAlive, "The ALC could not be unloaded."); [MethodImpl(MethodImplOptions.NoInlining)] static WeakReference CreateProxyInUnloadableAlc() { var alc = new AssemblyLoadContext(nameof(Test_Unloadability), true); alc.LoadFromAssemblyPath(typeof(DispatchProxyTests).Assembly.Location) .GetType(typeof(DispatchProxyTests).FullName, true) .GetMethod(nameof(CreateTestHelloProxy), BindingFlags.Static | BindingFlags.NonPublic) .Invoke(null, null); return new WeakReference(alc); } } [Fact] public static void Test_Multiple_AssemblyLoadContexts() { if (typeof(DispatchProxyTests).Assembly.Location == "") return; object proxyDefaultAlc = CreateTestDispatchProxy(typeof(TestDispatchProxy)); Assert.True(proxyDefaultAlc.GetType().IsAssignableTo(typeof(TestDispatchProxy))); Type proxyCustomAlcType = new AssemblyLoadContext(nameof(Test_Multiple_AssemblyLoadContexts)) .LoadFromAssemblyPath(typeof(DispatchProxyTests).Assembly.Location) .GetType(typeof(TestDispatchProxy).FullName, true); object proxyCustomAlc = CreateTestDispatchProxy(proxyCustomAlcType); Assert.True(proxyCustomAlc.GetType().IsAssignableTo(proxyCustomAlcType)); static object CreateTestDispatchProxy(Type type) => typeof(DispatchProxy) .GetMethod(nameof(DispatchProxy.Create)) // It has to be a type shared in both ALCs. .MakeGenericMethod(typeof(IDisposable), type) .Invoke(null, null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Loader; using System.Text; using Xunit; namespace DispatchProxyTests { public static class DispatchProxyTests { [Fact] public static void Create_Proxy_Derives_From_DispatchProxy_BaseType() { TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); Assert.NotNull(proxy); Assert.IsAssignableFrom<TestDispatchProxy>(proxy); } [Fact] public static void Create_Proxy_Implements_All_Interfaces() { TestType_IHelloAndGoodbyeService proxy = DispatchProxy.Create<TestType_IHelloAndGoodbyeService, TestDispatchProxy>(); Assert.NotNull(proxy); Type[] implementedInterfaces = typeof(TestType_IHelloAndGoodbyeService).GetTypeInfo().ImplementedInterfaces.ToArray(); foreach (Type t in implementedInterfaces) { Assert.IsAssignableFrom(t, proxy); } } [Fact] public static void Create_Proxy_Internal_Interface() { TestType_InternalInterfaceService proxy = DispatchProxy.Create<TestType_InternalInterfaceService, TestDispatchProxy>(); Assert.NotNull(proxy); } [Fact] public static void Create_Proxy_Implements_Internal_Interfaces() { TestType_InternalInterfaceService proxy = DispatchProxy.Create<TestType_PublicInterfaceService_Implements_Internal, TestDispatchProxy>(); Assert.NotNull(proxy); // ensure we emit a valid attribute definition Type iactAttributeType = proxy.GetType().Assembly.GetType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute"); Assert.NotNull(iactAttributeType); ConstructorInfo constructor = iactAttributeType.GetConstructor(new[] { typeof(string) }); Assert.NotNull(constructor); PropertyInfo propertyInfo = iactAttributeType.GetProperty("AssemblyName"); Assert.NotNull(propertyInfo); Assert.NotNull(propertyInfo.GetMethod); string name = "anAssemblyName"; object attributeInstance = constructor.Invoke(new object[] { name }); Assert.NotNull(attributeInstance); object actualName = propertyInfo.GetMethod.Invoke(attributeInstance, null); Assert.Equal(name, actualName); } [Fact] public static void Create_Same_Proxy_Type_And_Base_Type_Reuses_Same_Generated_Type() { TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); TestType_IHelloService proxy2 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); Assert.NotNull(proxy1); Assert.NotNull(proxy2); Assert.IsType(proxy1.GetType(), proxy2); } [Fact] public static void Create_Proxy_Instances_Of_Same_Proxy_And_Base_Type_Are_Unique() { TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); TestType_IHelloService proxy2 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); Assert.NotNull(proxy1); Assert.NotNull(proxy2); Assert.False(object.ReferenceEquals(proxy1, proxy2), string.Format("First and second instance of proxy type {0} were the same instance", proxy1.GetType().ToString())); } [Fact] public static void Create_Same_Proxy_Type_With_Different_BaseType_Uses_Different_Generated_Type() { TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); TestType_IHelloService proxy2 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy2>(); Assert.NotNull(proxy1); Assert.NotNull(proxy2); Assert.False(proxy1.GetType() == proxy2.GetType(), string.Format("Proxy generated for base type {0} used same for base type {1}", typeof(TestDispatchProxy).Name, typeof(TestDispatchProxy).Name)); } [Fact] public static void Created_Proxy_With_Different_Proxy_Type_Use_Different_Generated_Type() { TestType_IHelloService proxy1 = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); TestType_IGoodbyeService proxy2 = DispatchProxy.Create<TestType_IGoodbyeService, TestDispatchProxy>(); Assert.NotNull(proxy1); Assert.NotNull(proxy2); Assert.False(proxy1.GetType() == proxy2.GetType(), string.Format("Proxy generated for type {0} used same for type {1}", typeof(TestType_IHelloService).Name, typeof(TestType_IGoodbyeService).Name)); } [Fact] public static void Create_Using_Concrete_Proxy_Type_Throws_ArgumentException() { AssertExtensions.Throws<ArgumentException>("T", () => DispatchProxy.Create<TestType_ConcreteClass, TestDispatchProxy>()); } [Fact] public static void Create_Using_Sealed_BaseType_Throws_ArgumentException() { AssertExtensions.Throws<ArgumentException>("TProxy", () => DispatchProxy.Create<TestType_IHelloService, Sealed_TestDispatchProxy>()); } [Fact] public static void Create_Using_Abstract_BaseType_Throws_ArgumentException() { AssertExtensions.Throws<ArgumentException>("TProxy", () => DispatchProxy.Create<TestType_IHelloService, Abstract_TestDispatchProxy>()); } [Fact] public static void Create_Using_BaseType_Without_Default_Ctor_Throws_ArgumentException() { AssertExtensions.Throws<ArgumentException>("TProxy", () => DispatchProxy.Create<TestType_IHelloService, NoDefaultCtor_TestDispatchProxy>()); } [Fact] public static void Create_Using_PrivateProxy() { Assert.NotNull(TestType_PrivateProxy.Proxy<TestType_IHelloService>()); } [Fact] public static void Create_Using_PrivateProxyAndInternalService() { Assert.NotNull(TestType_PrivateProxy.Proxy<TestType_InternalInterfaceService>()); } [Fact] public static void Create_Using_PrivateProxyAndInternalServiceWithExternalGenericArgument() { Assert.NotNull(TestType_PrivateProxy.Proxy<TestType_InternalInterfaceWithNonPublicExternalGenericArgument>()); } [Fact] public static void Create_Using_InternalProxy() { Assert.NotNull(DispatchProxy.Create<TestType_InternalInterfaceService, InternalInvokeProxy>()); } [Fact] public static void Create_Using_ExternalNonPublicService() { Assert.NotNull(DispatchProxy.Create<DispatchProxyTestDependency.TestType_IExternalNonPublicHiService, TestDispatchProxy>()); } [Fact] public static void Create_Using_InternalProxyWithExternalNonPublicBaseType() { Assert.NotNull(DispatchProxy.Create<TestType_IHelloService, TestType_InternalProxyInternalBaseType>()); } [Fact] public static void Create_Using_InternalServiceImplementingNonPublicExternalService() { Assert.NotNull(DispatchProxy.Create<TestType_InternalInterfaceImplementsNonPublicExternalType, TestDispatchProxy>()); } [Fact] public static void Create_Using_InternalServiceWithGenericArgumentBeingNonPublicExternalService() { Assert.NotNull(DispatchProxy.Create<TestType_InternalInterfaceWithNonPublicExternalGenericArgument, TestDispatchProxy>()); } [Fact] public static void Create_Using_InternalProxyWithBaseTypeImplementingServiceWithgenericArgumentBeingNonPublicExternalService() { Assert.NotNull(DispatchProxy.Create<TestType_IHelloService, TestType_InternalProxyImplementingInterfaceWithGenericArgumentBeingNonPublicExternalType>()); } [Fact] public static void Invoke_Receives_Correct_MethodInfo_And_Arguments() { bool wasInvoked = false; StringBuilder errorBuilder = new StringBuilder(); // This Func is called whenever we call a method on the proxy. // This is where we validate it received the correct arguments and methods Func<MethodInfo, object[], object> invokeCallback = (method, args) => { wasInvoked = true; if (method == null) { string error = string.Format("Proxy for {0} was called with null method", typeof(TestType_IHelloService).Name); errorBuilder.AppendLine(error); return null; } else { MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello"); if (expectedMethod != method) { string error = string.Format("Proxy for {0} was called with incorrect method. Expected = {1}, Actual = {2}", typeof(TestType_IHelloService).Name, expectedMethod, method); errorBuilder.AppendLine(error); return null; } } return "success"; }; TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); Assert.NotNull(proxy); TestDispatchProxy dispatchProxy = proxy as TestDispatchProxy; Assert.NotNull(dispatchProxy); // Redirect Invoke to our own Func above dispatchProxy.CallOnInvoke = invokeCallback; // Calling this method now will invoke the Func above which validates correct method proxy.Hello("testInput"); Assert.True(wasInvoked, "The invoke method was not called"); Assert.True(errorBuilder.Length == 0, errorBuilder.ToString()); } [Fact] public static void Invoke_Receives_Correct_MethodInfo() { MethodInfo invokedMethod = null; TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethod = method; return string.Empty; }; proxy.Hello("testInput"); MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello"); Assert.True(invokedMethod != null && expectedMethod == invokedMethod, string.Format("Invoke expected method {0} but actual was {1}", expectedMethod, invokedMethod)); } [Fact] public static void Invoke_Receives_Correct_Arguments() { object[] actualArgs = null; TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { actualArgs = args; return string.Empty; }; proxy.Hello("testInput"); object[] expectedArgs = new object[] { "testInput" }; Assert.True(actualArgs != null && actualArgs.Length == expectedArgs.Length, string.Format("Invoked expected object[] of length {0} but actual was {1}", expectedArgs.Length, (actualArgs == null ? "null" : actualArgs.Length.ToString()))); for (int i = 0; i < expectedArgs.Length; ++i) { Assert.True(expectedArgs[i].Equals(actualArgs[i]), string.Format("Expected arg[{0}] = '{1}' but actual was '{2}'", i, expectedArgs[i], actualArgs[i])); } } [Fact] public static void Invoke_Returns_Correct_Value() { TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { return "testReturn"; }; string expectedResult = "testReturn"; string actualResult = proxy.Hello(expectedResult); Assert.Equal(expectedResult, actualResult); } [Fact] public static void Invoke_Multiple_Parameters_Receives_Correct_Arguments() { object[] invokedArgs = null; object[] expectedArgs = new object[] { (int)42, "testString", (double)5.0 }; TestType_IMultipleParameterService proxy = DispatchProxy.Create<TestType_IMultipleParameterService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedArgs = args; return 0.0; }; proxy.TestMethod((int)expectedArgs[0], (string)expectedArgs[1], (double)expectedArgs[2]); Assert.True(invokedArgs != null && invokedArgs.Length == expectedArgs.Length, string.Format("Expected {0} arguments but actual was {1}", expectedArgs.Length, invokedArgs == null ? "null" : invokedArgs.Length.ToString())); for (int i = 0; i < expectedArgs.Length; ++i) { Assert.True(expectedArgs[i].Equals(invokedArgs[i]), string.Format("Expected arg[{0}] = '{1}' but actual was '{2}'", i, expectedArgs[i], invokedArgs[i])); } } [Fact] public static void Invoke_Multiple_Parameters_Via_Params_Receives_Correct_Arguments() { object[] actualArgs = null; object[] invokedArgs = null; object[] expectedArgs = new object[] { 42, "testString", 5.0 }; TestType_IMultipleParameterService proxy = DispatchProxy.Create<TestType_IMultipleParameterService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedArgs = args; return string.Empty; }; proxy.ParamsMethod((int)expectedArgs[0], (string)expectedArgs[1], (double)expectedArgs[2]); // All separate params should have become a single object[1] array Assert.True(invokedArgs != null && invokedArgs.Length == 1, string.Format("Expected single element object[] but actual was {0}", invokedArgs == null ? "null" : invokedArgs.Length.ToString())); // That object[1] should contain an object[3] containing the args actualArgs = invokedArgs[0] as object[]; Assert.True(actualArgs != null && actualArgs.Length == expectedArgs.Length, string.Format("Invoked expected object[] of length {0} but actual was {1}", expectedArgs.Length, (actualArgs == null ? "null" : actualArgs.Length.ToString()))); for (int i = 0; i < expectedArgs.Length; ++i) { Assert.True(expectedArgs[i].Equals(actualArgs[i]), string.Format("Expected arg[{0}] = '{1}' but actual was '{2}'", i, expectedArgs[i], actualArgs[i])); } } [Fact] public static void Invoke_Void_Returning_Method_Accepts_Null_Return() { MethodInfo invokedMethod = null; TestType_IOneWay proxy = DispatchProxy.Create<TestType_IOneWay, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethod = method; return null; }; proxy.OneWay(); MethodInfo expectedMethod = typeof(TestType_IOneWay).GetTypeInfo().GetDeclaredMethod("OneWay"); Assert.True(invokedMethod != null && expectedMethod == invokedMethod, string.Format("Invoke expected method {0} but actual was {1}", expectedMethod, invokedMethod)); } [Fact] public static void Invoke_Same_Method_Multiple_Interfaces_Calls_Correct_Method() { List<MethodInfo> invokedMethods = new List<MethodInfo>(); TestType_IHelloService1And2 proxy = DispatchProxy.Create<TestType_IHelloService1And2, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethods.Add(method); return null; }; ((TestType_IHelloService)proxy).Hello("calling 1"); ((TestType_IHelloService2)proxy).Hello("calling 2"); Assert.True(invokedMethods.Count == 2, string.Format("Expected 2 method invocations but received {0}", invokedMethods.Count)); MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello"); Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], string.Format("First invoke should have been TestType_IHelloService.Hello but actual was {0}", invokedMethods[0])); expectedMethod = typeof(TestType_IHelloService2).GetTypeInfo().GetDeclaredMethod("Hello"); Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], string.Format("Second invoke should have been TestType_IHelloService2.Hello but actual was {0}", invokedMethods[1])); } [Fact] public static void Invoke_Thrown_Exception_Rethrown_To_Caller() { Exception actualException = null; InvalidOperationException expectedException = new InvalidOperationException("testException"); TestType_IHelloService proxy = DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { throw expectedException; }; try { proxy.Hello("testCall"); } catch (Exception e) { actualException = e; } Assert.Equal(expectedException, actualException); } [Fact] public static void Invoke_Property_Setter_And_Getter_Invokes_Correct_Methods() { List<MethodInfo> invokedMethods = new List<MethodInfo>(); TestType_IPropertyService proxy = DispatchProxy.Create<TestType_IPropertyService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethods.Add(method); return null; }; proxy.ReadWrite = "testValue"; string actualValue = proxy.ReadWrite; Assert.True(invokedMethods.Count == 2, string.Format("Expected 2 method invocations but received {0}", invokedMethods.Count)); PropertyInfo propertyInfo = typeof(TestType_IPropertyService).GetTypeInfo().GetDeclaredProperty("ReadWrite"); Assert.NotNull(propertyInfo); MethodInfo expectedMethod = propertyInfo.SetMethod; Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], string.Format("First invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[0])); expectedMethod = propertyInfo.GetMethod; Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], string.Format("Second invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[1])); Assert.Null(actualValue); } [Fact] public static void Proxy_Declares_Interface_Properties() { TestType_IPropertyService proxy = DispatchProxy.Create<TestType_IPropertyService, TestDispatchProxy>(); PropertyInfo propertyInfo = proxy.GetType().GetTypeInfo().GetDeclaredProperty("ReadWrite"); Assert.NotNull(propertyInfo); } #if NETCOREAPP [Fact] public static void Invoke_Event_Add_And_Remove_And_Raise_Invokes_Correct_Methods() { // C# cannot emit raise_Xxx method for the event, so we must use System.Reflection.Emit to generate such event. AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("EventBuilder"), AssemblyBuilderAccess.Run); ModuleBuilder modb = ab.DefineDynamicModule("mod"); TypeBuilder tb = modb.DefineType("TestType_IEventService", TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract); EventBuilder eb = tb.DefineEvent("AddRemoveRaise", EventAttributes.None, typeof(EventHandler)); eb.SetAddOnMethod(tb.DefineMethod("add_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventHandler) })); eb.SetRemoveOnMethod(tb.DefineMethod("remove_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventHandler) })); eb.SetRaiseMethod(tb.DefineMethod("raise_AddRemoveRaise", MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual, typeof(void), new Type[] { typeof(EventArgs) })); TypeInfo ieventServiceTypeInfo = tb.CreateTypeInfo(); List<MethodInfo> invokedMethods = new List<MethodInfo>(); object proxy = typeof(DispatchProxy) .GetRuntimeMethod("Create", Type.EmptyTypes).MakeGenericMethod(ieventServiceTypeInfo.AsType(), typeof(TestDispatchProxy)) .Invoke(null, null); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethods.Add(method); return null; }; EventHandler handler = new EventHandler((sender, e) => { }); proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "add_AddRemoveRaise").Invoke(proxy, new object[] { handler }); proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "raise_AddRemoveRaise").Invoke(proxy, new object[] { EventArgs.Empty }); proxy.GetType().GetRuntimeMethods().Single(m => m.Name == "remove_AddRemoveRaise").Invoke(proxy, new object[] { handler }); Assert.True(invokedMethods.Count == 3, String.Format("Expected 3 method invocations but received {0}", invokedMethods.Count)); EventInfo eventInfo = ieventServiceTypeInfo.GetDeclaredEvent("AddRemoveRaise"); Assert.NotNull(eventInfo); MethodInfo expectedMethod = eventInfo.AddMethod; Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[0])); expectedMethod = eventInfo.RaiseMethod; Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[1])); expectedMethod = eventInfo.RemoveMethod; Assert.True(invokedMethods[2] != null && expectedMethod == invokedMethods[2], String.Format("Third invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[1])); } #endif [Fact] public static void Proxy_Declares_Interface_Events() { TestType_IEventService proxy = DispatchProxy.Create<TestType_IEventService, TestDispatchProxy>(); EventInfo eventInfo = proxy.GetType().GetTypeInfo().GetDeclaredEvent("AddRemove"); Assert.NotNull(eventInfo); } [Fact] public static void Invoke_Indexer_Setter_And_Getter_Invokes_Correct_Methods() { List<MethodInfo> invokedMethods = new List<MethodInfo>(); TestType_IIndexerService proxy = DispatchProxy.Create<TestType_IIndexerService, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { invokedMethods.Add(method); return null; }; proxy["key"] = "testValue"; string actualValue = proxy["key"]; Assert.True(invokedMethods.Count == 2, string.Format("Expected 2 method invocations but received {0}", invokedMethods.Count)); PropertyInfo propertyInfo = typeof(TestType_IIndexerService).GetTypeInfo().GetDeclaredProperty("Item"); Assert.NotNull(propertyInfo); MethodInfo expectedMethod = propertyInfo.SetMethod; Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], string.Format("First invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[0])); expectedMethod = propertyInfo.GetMethod; Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], string.Format("Second invoke should have been {0} but actual was {1}", expectedMethod.Name, invokedMethods[1])); Assert.Null(actualValue); } [Fact] public static void Proxy_Declares_Interface_Indexers() { TestType_IIndexerService proxy = DispatchProxy.Create<TestType_IIndexerService, TestDispatchProxy>(); PropertyInfo propertyInfo = proxy.GetType().GetTypeInfo().GetDeclaredProperty("Item"); Assert.NotNull(propertyInfo); } static void testGenericMethodRoundTrip<T>(T testValue) { var proxy = DispatchProxy.Create<TypeType_GenericMethod, TestDispatchProxy>(); ((TestDispatchProxy)proxy).CallOnInvoke = (mi, a) => { Assert.True(mi.IsGenericMethod); Assert.False(mi.IsGenericMethodDefinition); Assert.Equal(1, mi.GetParameters().Length); Assert.Equal(typeof(T), mi.GetParameters()[0].ParameterType); Assert.Equal(typeof(T), mi.ReturnType); return a[0]; }; Assert.Equal(proxy.Echo(testValue), testValue); } [Fact] public static void Invoke_Generic_Method() { //string testGenericMethodRoundTrip("asdf"); //reference type testGenericMethodRoundTrip(new Version(1, 0, 0, 0)); //value type testGenericMethodRoundTrip(42); //enum type testGenericMethodRoundTrip(DayOfWeek.Monday); } [Fact] public static void Invoke_Ref_Out_In_Method() { string value = "Hello"; testRefOutInInvocation(p => p.InAttribute(value), "Hello"); testRefOutInInvocation(p => p.InAttribute_OutAttribute(value), "Hello"); testRefOutInInvocation(p => p.InAttribute_Ref(ref value), "Hello"); testRefOutInInvocation(p => p.Out(out _), null); testRefOutInInvocation(p => p.OutAttribute(value), "Hello"); testRefOutInInvocation(p => p.Ref(ref value), "Hello"); testRefOutInInvocation(p => p.In(in value), "Hello"); } private static void testRefOutInInvocation(Action<TestType_IOut_Ref> invocation, string expected) { var proxy = DispatchProxy.Create<TestType_IOut_Ref, TestDispatchProxy>(); string result = "Failed"; ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) => { result = args[0] as string; return null; }; invocation(proxy); Assert.Equal(expected, result); } private static TestType_IHelloService CreateTestHelloProxy() => DispatchProxy.Create<TestType_IHelloService, TestDispatchProxy>(); [ActiveIssue("https://github.com/dotnet/runtime/issues/62503", TestRuntimes.Mono)] [Fact] public static void Test_Unloadability() { if (typeof(DispatchProxyTests).Assembly.Location == "") return; WeakReference wr = CreateProxyInUnloadableAlc(); for (int i = 0; i < 10 && wr.IsAlive; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } Assert.False(wr.IsAlive, "The ALC could not be unloaded."); [MethodImpl(MethodImplOptions.NoInlining)] static WeakReference CreateProxyInUnloadableAlc() { var alc = new AssemblyLoadContext(nameof(Test_Unloadability), true); alc.LoadFromAssemblyPath(typeof(DispatchProxyTests).Assembly.Location) .GetType(typeof(DispatchProxyTests).FullName, true) .GetMethod(nameof(CreateTestHelloProxy), BindingFlags.Static | BindingFlags.NonPublic) .Invoke(null, null); return new WeakReference(alc); } } [Fact] public static void Test_Multiple_AssemblyLoadContexts() { if (typeof(DispatchProxyTests).Assembly.Location == "") return; object proxyDefaultAlc = CreateTestDispatchProxy(typeof(TestDispatchProxy)); Assert.True(proxyDefaultAlc.GetType().IsAssignableTo(typeof(TestDispatchProxy))); Type proxyCustomAlcType = new AssemblyLoadContext(nameof(Test_Multiple_AssemblyLoadContexts)) .LoadFromAssemblyPath(typeof(DispatchProxyTests).Assembly.Location) .GetType(typeof(TestDispatchProxy).FullName, true); object proxyCustomAlc = CreateTestDispatchProxy(proxyCustomAlcType); Assert.True(proxyCustomAlc.GetType().IsAssignableTo(proxyCustomAlcType)); static object CreateTestDispatchProxy(Type type) => typeof(DispatchProxy) .GetMethod(nameof(DispatchProxy.Create)) // It has to be a type shared in both ALCs. .MakeGenericMethod(typeof(IDisposable), type) .Invoke(null, null); } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/Microsoft.Win32.SystemEvents/tests/SystemEvents.DisplaySettings.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; using Xunit; using static Interop; namespace Microsoft.Win32.SystemEventsTests { public class DisplaySettingsTests : SystemEventsTest { private void SendMessage() { SendMessage(User32.WM_DISPLAYCHANGE, IntPtr.Zero, IntPtr.Zero); } private void SendReflectedMessage() { SendMessage(User32.WM_REFLECT + User32.WM_DISPLAYCHANGE, IntPtr.Zero, IntPtr.Zero); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] public void SignalsDisplayEventsAsynchronouslyOnDISPLAYCHANGE() { var changing = new AutoResetEvent(false); var changed = new AutoResetEvent(false); EventHandler changedHandler = (o, e) => { Assert.NotNull(o); changed.Set(); }; EventHandler changingHandler = (o, e) => { Assert.NotNull(o); changing.Set(); }; SystemEvents.DisplaySettingsChanged += changedHandler; SystemEvents.DisplaySettingsChanging += changingHandler; try { SendMessage(); Assert.True(changing.WaitOne(PostMessageWait)); Assert.True(changed.WaitOne(PostMessageWait)); } finally { SystemEvents.DisplaySettingsChanged -= changedHandler; SystemEvents.DisplaySettingsChanging -= changingHandler; changing.Dispose(); changed.Dispose(); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] public void SignalsDisplayEventsSynchronouslyOnREFLECTDISPLAYCHANGE() { bool changing = false, changed = false; EventHandler changedHandler = (o, e) => { Assert.NotNull(o); changed = true; }; EventHandler changingHandler = (o, e) => { Assert.NotNull(o); changing = true; }; SystemEvents.DisplaySettingsChanged += changedHandler; SystemEvents.DisplaySettingsChanging += changingHandler; try { SendReflectedMessage(); Assert.True(changing); Assert.True(changed); } finally { SystemEvents.DisplaySettingsChanged -= changedHandler; SystemEvents.DisplaySettingsChanging -= changingHandler; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; using Xunit; using static Interop; namespace Microsoft.Win32.SystemEventsTests { public class DisplaySettingsTests : SystemEventsTest { private void SendMessage() { SendMessage(User32.WM_DISPLAYCHANGE, IntPtr.Zero, IntPtr.Zero); } private void SendReflectedMessage() { SendMessage(User32.WM_REFLECT + User32.WM_DISPLAYCHANGE, IntPtr.Zero, IntPtr.Zero); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] public void SignalsDisplayEventsAsynchronouslyOnDISPLAYCHANGE() { var changing = new AutoResetEvent(false); var changed = new AutoResetEvent(false); EventHandler changedHandler = (o, e) => { Assert.NotNull(o); changed.Set(); }; EventHandler changingHandler = (o, e) => { Assert.NotNull(o); changing.Set(); }; SystemEvents.DisplaySettingsChanged += changedHandler; SystemEvents.DisplaySettingsChanging += changingHandler; try { SendMessage(); Assert.True(changing.WaitOne(PostMessageWait)); Assert.True(changed.WaitOne(PostMessageWait)); } finally { SystemEvents.DisplaySettingsChanged -= changedHandler; SystemEvents.DisplaySettingsChanging -= changingHandler; changing.Dispose(); changed.Dispose(); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] public void SignalsDisplayEventsSynchronouslyOnREFLECTDISPLAYCHANGE() { bool changing = false, changed = false; EventHandler changedHandler = (o, e) => { Assert.NotNull(o); changed = true; }; EventHandler changingHandler = (o, e) => { Assert.NotNull(o); changing = true; }; SystemEvents.DisplaySettingsChanged += changedHandler; SystemEvents.DisplaySettingsChanging += changingHandler; try { SendReflectedMessage(); Assert.True(changing); Assert.True(changed); } finally { SystemEvents.DisplaySettingsChanged -= changedHandler; SystemEvents.DisplaySettingsChanging -= changingHandler; } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/SIMD/VectorDot_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="VectorDot.cs" /> <Compile Include="VectorUtil.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="VectorDot.cs" /> <Compile Include="VectorUtil.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/SIMD/StoreElement.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 Point = System.Numerics.Vector<int>; namespace VectorTests { class Program { static int Main(string[] args) { Point p = new Point(1); Point[] arr = new Point[10]; arr[0] = p; // Loadelem bytecode. arr[2] = p; if (arr[0] == arr[1] || arr[2] != p) { return 0; } return 100; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using Point = System.Numerics.Vector<int>; namespace VectorTests { class Program { static int Main(string[] args) { Point p = new Point(1); Point[] arr = new Point[10]; arr[0] = p; // Loadelem bytecode. arr[2] = p; if (arr[0] == arr[1] || arr[2] != p) { return 0; } return 100; } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Methodical/Invoke/implicit/obj_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="obj.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="obj.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Net.Security/src/System/Net/Security/SslApplicationProtocol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; namespace System.Net.Security { public readonly struct SslApplicationProtocol : IEquatable<SslApplicationProtocol> { private static readonly Encoding s_utf8 = Encoding.GetEncoding(Encoding.UTF8.CodePage, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); private static readonly byte[] s_http3Utf8 = new byte[] { 0x68, 0x33 }; // "h3" private static readonly byte[] s_http2Utf8 = new byte[] { 0x68, 0x32 }; // "h2" private static readonly byte[] s_http11Utf8 = new byte[] { 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31 }; // "http/1.1" // Refer to IANA on ApplicationProtocols: https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids /// <summary>Defines a <see cref="SslApplicationProtocol"/> instance for HTTP 3.0.</summary> public static readonly SslApplicationProtocol Http3 = new SslApplicationProtocol(s_http3Utf8, copy: false); /// <summary>Defines a <see cref="SslApplicationProtocol"/> instance for HTTP 2.0.</summary> public static readonly SslApplicationProtocol Http2 = new SslApplicationProtocol(s_http2Utf8, copy: false); /// <summary>Defines a <see cref="SslApplicationProtocol"/> instance for HTTP 1.1.</summary> public static readonly SslApplicationProtocol Http11 = new SslApplicationProtocol(s_http11Utf8, copy: false); private readonly byte[] _readOnlyProtocol; internal SslApplicationProtocol(byte[] protocol, bool copy) { Debug.Assert(protocol != null); // RFC 7301 states protocol size <= 255 bytes. if (protocol.Length == 0 || protocol.Length > 255) { throw new ArgumentException(SR.net_ssl_app_protocol_invalid, nameof(protocol)); } _readOnlyProtocol = copy ? protocol.AsSpan().ToArray() : protocol; } public SslApplicationProtocol(byte[] protocol!!) : this(protocol, copy: true) { } public SslApplicationProtocol(string protocol!!) : this(s_utf8.GetBytes(protocol), copy: false) { } public ReadOnlyMemory<byte> Protocol => _readOnlyProtocol; public bool Equals(SslApplicationProtocol other) => ((ReadOnlySpan<byte>)_readOnlyProtocol).SequenceEqual(other._readOnlyProtocol); public override bool Equals([NotNullWhen(true)] object? obj) => obj is SslApplicationProtocol protocol && Equals(protocol); public override int GetHashCode() { byte[] arr = _readOnlyProtocol; if (arr == null) { return 0; } int hash = 0; for (int i = 0; i < arr.Length; i++) { hash = ((hash << 5) + hash) ^ arr[i]; } return hash; } public override string ToString() { byte[] arr = _readOnlyProtocol; try { return arr is null ? string.Empty : ReferenceEquals(arr, s_http3Utf8) ? "h3" : ReferenceEquals(arr, s_http2Utf8) ? "h2" : ReferenceEquals(arr, s_http11Utf8) ? "http/1.1" : s_utf8.GetString(arr); } catch { // In case of decoding errors, return the byte values as hex string. char[] byteChars = new char[arr.Length * 5]; int index = 0; for (int i = 0; i < byteChars.Length; i += 5) { byte b = arr[index++]; byteChars[i] = '0'; byteChars[i + 1] = 'x'; byteChars[i + 2] = HexConverter.ToCharLower(b >> 4); byteChars[i + 3] = HexConverter.ToCharLower(b); byteChars[i + 4] = ' '; } return new string(byteChars, 0, byteChars.Length - 1); } } public static bool operator ==(SslApplicationProtocol left, SslApplicationProtocol right) => left.Equals(right); public static bool operator !=(SslApplicationProtocol left, SslApplicationProtocol right) => !(left == right); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; namespace System.Net.Security { public readonly struct SslApplicationProtocol : IEquatable<SslApplicationProtocol> { private static readonly Encoding s_utf8 = Encoding.GetEncoding(Encoding.UTF8.CodePage, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); private static readonly byte[] s_http3Utf8 = new byte[] { 0x68, 0x33 }; // "h3" private static readonly byte[] s_http2Utf8 = new byte[] { 0x68, 0x32 }; // "h2" private static readonly byte[] s_http11Utf8 = new byte[] { 0x68, 0x74, 0x74, 0x70, 0x2f, 0x31, 0x2e, 0x31 }; // "http/1.1" // Refer to IANA on ApplicationProtocols: https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids /// <summary>Defines a <see cref="SslApplicationProtocol"/> instance for HTTP 3.0.</summary> public static readonly SslApplicationProtocol Http3 = new SslApplicationProtocol(s_http3Utf8, copy: false); /// <summary>Defines a <see cref="SslApplicationProtocol"/> instance for HTTP 2.0.</summary> public static readonly SslApplicationProtocol Http2 = new SslApplicationProtocol(s_http2Utf8, copy: false); /// <summary>Defines a <see cref="SslApplicationProtocol"/> instance for HTTP 1.1.</summary> public static readonly SslApplicationProtocol Http11 = new SslApplicationProtocol(s_http11Utf8, copy: false); private readonly byte[] _readOnlyProtocol; internal SslApplicationProtocol(byte[] protocol, bool copy) { Debug.Assert(protocol != null); // RFC 7301 states protocol size <= 255 bytes. if (protocol.Length == 0 || protocol.Length > 255) { throw new ArgumentException(SR.net_ssl_app_protocol_invalid, nameof(protocol)); } _readOnlyProtocol = copy ? protocol.AsSpan().ToArray() : protocol; } public SslApplicationProtocol(byte[] protocol!!) : this(protocol, copy: true) { } public SslApplicationProtocol(string protocol!!) : this(s_utf8.GetBytes(protocol), copy: false) { } public ReadOnlyMemory<byte> Protocol => _readOnlyProtocol; public bool Equals(SslApplicationProtocol other) => ((ReadOnlySpan<byte>)_readOnlyProtocol).SequenceEqual(other._readOnlyProtocol); public override bool Equals([NotNullWhen(true)] object? obj) => obj is SslApplicationProtocol protocol && Equals(protocol); public override int GetHashCode() { byte[] arr = _readOnlyProtocol; if (arr == null) { return 0; } int hash = 0; for (int i = 0; i < arr.Length; i++) { hash = ((hash << 5) + hash) ^ arr[i]; } return hash; } public override string ToString() { byte[] arr = _readOnlyProtocol; try { return arr is null ? string.Empty : ReferenceEquals(arr, s_http3Utf8) ? "h3" : ReferenceEquals(arr, s_http2Utf8) ? "h2" : ReferenceEquals(arr, s_http11Utf8) ? "http/1.1" : s_utf8.GetString(arr); } catch { // In case of decoding errors, return the byte values as hex string. char[] byteChars = new char[arr.Length * 5]; int index = 0; for (int i = 0; i < byteChars.Length; i += 5) { byte b = arr[index++]; byteChars[i] = '0'; byteChars[i + 1] = 'x'; byteChars[i + 2] = HexConverter.ToCharLower(b >> 4); byteChars[i + 3] = HexConverter.ToCharLower(b); byteChars[i + 4] = ' '; } return new string(byteChars, 0, byteChars.Length - 1); } } public static bool operator ==(SslApplicationProtocol left, SslApplicationProtocol right) => left.Equals(right); public static bool operator !=(SslApplicationProtocol left, SslApplicationProtocol right) => !(left == right); } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseInsensitive.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; using System.Reflection; using System.Reflection.Runtime.General; using System.Reflection.Runtime.Modules; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.TypeParsing; using System.Reflection.Runtime.CustomAttributes; using System.Collections.Generic; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; using Internal.Metadata.NativeFormat; using Internal.Reflection.Tracing; namespace System.Reflection.Runtime.Assemblies.NativeFormat { internal partial class NativeFormatRuntimeAssembly { internal sealed override RuntimeTypeInfo GetTypeCoreCaseInsensitive(string fullName) { LowLevelDictionary<string, QHandle> dict = CaseInsensitiveTypeDictionary; QHandle qualifiedHandle; if (!dict.TryGetValue(fullName.ToLowerInvariant(), out qualifiedHandle)) { return null; } MetadataReader reader = qualifiedHandle.Reader; Handle typeDefOrForwarderHandle = qualifiedHandle.Handle; HandleType handleType = typeDefOrForwarderHandle.HandleType; switch (handleType) { case HandleType.TypeDefinition: { TypeDefinitionHandle typeDefinitionHandle = typeDefOrForwarderHandle.ToTypeDefinitionHandle(reader); return typeDefinitionHandle.ResolveTypeDefinition(reader); } case HandleType.TypeForwarder: { TypeForwarder typeForwarder = typeDefOrForwarderHandle.ToTypeForwarderHandle(reader).GetTypeForwarder(reader); ScopeReferenceHandle destinationScope = typeForwarder.Scope; RuntimeAssemblyName destinationAssemblyName = destinationScope.ToRuntimeAssemblyName(reader); RuntimeAssemblyInfo destinationAssembly = RuntimeAssemblyInfo.GetRuntimeAssemblyIfExists(destinationAssemblyName); if (destinationAssembly == null) return null; return destinationAssembly.GetTypeCoreCaseInsensitive(fullName); } default: throw new InvalidOperationException(); } } private LowLevelDictionary<string, QHandle> CaseInsensitiveTypeDictionary { get { return _lazyCaseInsensitiveTypeDictionary ?? (_lazyCaseInsensitiveTypeDictionary = CreateCaseInsensitiveTypeDictionary()); } } private LowLevelDictionary<string, QHandle> CreateCaseInsensitiveTypeDictionary() { // // Collect all of the *non-nested* types and type-forwards. // // The keys are full typenames in lower-cased form. // The value is a tuple containing either a TypeDefinitionHandle or TypeForwarderHandle and the associated Reader // for that handle. // // We do not store nested types here. The container type is resolved and chosen first, then the nested type chosen from // that. If we chose the wrong container type and fail the match as a result, that's too bad. (The desktop CLR has the // same issue.) // LowLevelDictionary<string, QHandle> dict = new LowLevelDictionary<string, QHandle>(); foreach (QScopeDefinition scope in AllScopes) { MetadataReader reader = scope.Reader; ScopeDefinition scopeDefinition = scope.ScopeDefinition; IEnumerable<NamespaceDefinitionHandle> topLevelNamespaceHandles = new NamespaceDefinitionHandle[] { scopeDefinition.RootNamespaceDefinition }; IEnumerable<NamespaceDefinitionHandle> allNamespaceHandles = reader.GetTransitiveNamespaces(topLevelNamespaceHandles); foreach (NamespaceDefinitionHandle namespaceHandle in allNamespaceHandles) { string ns = namespaceHandle.ToNamespaceName(reader); if (ns.Length != 0) ns = ns + "."; ns = ns.ToLowerInvariant(); NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader); foreach (TypeDefinitionHandle typeDefinitionHandle in namespaceDefinition.TypeDefinitions) { string fullName = ns + typeDefinitionHandle.GetTypeDefinition(reader).Name.GetString(reader).ToLowerInvariant(); if (!dict.TryGetValue(fullName, out _)) { dict.Add(fullName, new QHandle(reader, typeDefinitionHandle)); } } foreach (TypeForwarderHandle typeForwarderHandle in namespaceDefinition.TypeForwarders) { string fullName = ns + typeForwarderHandle.GetTypeForwarder(reader).Name.GetString(reader).ToLowerInvariant(); if (!dict.TryGetValue(fullName, out _)) { dict.Add(fullName, new QHandle(reader, typeForwarderHandle)); } } } } return dict; } private volatile LowLevelDictionary<string, QHandle> _lazyCaseInsensitiveTypeDictionary; } }
// 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; using System.Reflection; using System.Reflection.Runtime.General; using System.Reflection.Runtime.Modules; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.TypeParsing; using System.Reflection.Runtime.CustomAttributes; using System.Collections.Generic; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; using Internal.Metadata.NativeFormat; using Internal.Reflection.Tracing; namespace System.Reflection.Runtime.Assemblies.NativeFormat { internal partial class NativeFormatRuntimeAssembly { internal sealed override RuntimeTypeInfo GetTypeCoreCaseInsensitive(string fullName) { LowLevelDictionary<string, QHandle> dict = CaseInsensitiveTypeDictionary; QHandle qualifiedHandle; if (!dict.TryGetValue(fullName.ToLowerInvariant(), out qualifiedHandle)) { return null; } MetadataReader reader = qualifiedHandle.Reader; Handle typeDefOrForwarderHandle = qualifiedHandle.Handle; HandleType handleType = typeDefOrForwarderHandle.HandleType; switch (handleType) { case HandleType.TypeDefinition: { TypeDefinitionHandle typeDefinitionHandle = typeDefOrForwarderHandle.ToTypeDefinitionHandle(reader); return typeDefinitionHandle.ResolveTypeDefinition(reader); } case HandleType.TypeForwarder: { TypeForwarder typeForwarder = typeDefOrForwarderHandle.ToTypeForwarderHandle(reader).GetTypeForwarder(reader); ScopeReferenceHandle destinationScope = typeForwarder.Scope; RuntimeAssemblyName destinationAssemblyName = destinationScope.ToRuntimeAssemblyName(reader); RuntimeAssemblyInfo destinationAssembly = RuntimeAssemblyInfo.GetRuntimeAssemblyIfExists(destinationAssemblyName); if (destinationAssembly == null) return null; return destinationAssembly.GetTypeCoreCaseInsensitive(fullName); } default: throw new InvalidOperationException(); } } private LowLevelDictionary<string, QHandle> CaseInsensitiveTypeDictionary { get { return _lazyCaseInsensitiveTypeDictionary ?? (_lazyCaseInsensitiveTypeDictionary = CreateCaseInsensitiveTypeDictionary()); } } private LowLevelDictionary<string, QHandle> CreateCaseInsensitiveTypeDictionary() { // // Collect all of the *non-nested* types and type-forwards. // // The keys are full typenames in lower-cased form. // The value is a tuple containing either a TypeDefinitionHandle or TypeForwarderHandle and the associated Reader // for that handle. // // We do not store nested types here. The container type is resolved and chosen first, then the nested type chosen from // that. If we chose the wrong container type and fail the match as a result, that's too bad. (The desktop CLR has the // same issue.) // LowLevelDictionary<string, QHandle> dict = new LowLevelDictionary<string, QHandle>(); foreach (QScopeDefinition scope in AllScopes) { MetadataReader reader = scope.Reader; ScopeDefinition scopeDefinition = scope.ScopeDefinition; IEnumerable<NamespaceDefinitionHandle> topLevelNamespaceHandles = new NamespaceDefinitionHandle[] { scopeDefinition.RootNamespaceDefinition }; IEnumerable<NamespaceDefinitionHandle> allNamespaceHandles = reader.GetTransitiveNamespaces(topLevelNamespaceHandles); foreach (NamespaceDefinitionHandle namespaceHandle in allNamespaceHandles) { string ns = namespaceHandle.ToNamespaceName(reader); if (ns.Length != 0) ns = ns + "."; ns = ns.ToLowerInvariant(); NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader); foreach (TypeDefinitionHandle typeDefinitionHandle in namespaceDefinition.TypeDefinitions) { string fullName = ns + typeDefinitionHandle.GetTypeDefinition(reader).Name.GetString(reader).ToLowerInvariant(); if (!dict.TryGetValue(fullName, out _)) { dict.Add(fullName, new QHandle(reader, typeDefinitionHandle)); } } foreach (TypeForwarderHandle typeForwarderHandle in namespaceDefinition.TypeForwarders) { string fullName = ns + typeForwarderHandle.GetTypeForwarder(reader).Name.GetString(reader).ToLowerInvariant(); if (!dict.TryGetValue(fullName, out _)) { dict.Add(fullName, new QHandle(reader, typeForwarderHandle)); } } } } return dict; } private volatile LowLevelDictionary<string, QHandle> _lazyCaseInsensitiveTypeDictionary; } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Methodical/Boxing/seh/try_cs_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>Full</DebugType> <Optimize>True</Optimize> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> </PropertyGroup> <ItemGroup> <Compile Include="try.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>Full</DebugType> <Optimize>True</Optimize> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> </PropertyGroup> <ItemGroup> <Compile Include="try.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Directed/cmov/Bool_Or_Op_cs_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Bool_Or_Op.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Bool_Or_Op.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/Common/src/Interop/Unix/System.Net.Security.Native/Interop.NetSecurityNative.IsNtlmInstalled.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class NetSecurityNative { [LibraryImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_IsNtlmInstalled")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool IsNtlmInstalled(); [LibraryImport(Interop.Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_EnsureGssInitialized")] private static partial int EnsureGssInitialized(); static NetSecurityNative() { GssInitializer.Initialize(); } internal static class GssInitializer { static GssInitializer() { if (EnsureGssInitialized() != 0) { throw new InvalidOperationException(); } } internal static void Initialize() { // No-op that exists to provide a hook for other static constructors. } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class NetSecurityNative { [LibraryImport(Interop.Libraries.NetSecurityNative, EntryPoint="NetSecurityNative_IsNtlmInstalled")] [return: MarshalAs(UnmanagedType.Bool)] internal static partial bool IsNtlmInstalled(); [LibraryImport(Interop.Libraries.NetSecurityNative, EntryPoint = "NetSecurityNative_EnsureGssInitialized")] private static partial int EnsureGssInitialized(); static NetSecurityNative() { GssInitializer.Initialize(); } internal static class GssInitializer { static GssInitializer() { if (EnsureGssInitialized() != 0) { throw new InvalidOperationException(); } } internal static void Initialize() { // No-op that exists to provide a hook for other static constructors. } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/jit64/hfa/main/testC/hfa_sd0C_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="hfa_testC.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\dll\common.csproj" /> <ProjectReference Include="..\dll\hfa_simple_f64_common.csproj" /> <ProjectReference Include="..\dll\hfa_simple_f64_managed.csproj" /> <CMakeProjectReference Include="..\dll\CMakelists.txt" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="hfa_testC.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\dll\common.csproj" /> <ProjectReference Include="..\dll\hfa_simple_f64_common.csproj" /> <ProjectReference Include="..\dll\hfa_simple_f64_managed.csproj" /> <CMakeProjectReference Include="..\dll\CMakelists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationException.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.Runtime.Serialization { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SerializationException : SystemException { /// <summary> /// Creates a new SerializationException with its message /// string set to a default message. /// </summary> public SerializationException() : base(SR.SerializationException) { HResult = HResults.COR_E_SERIALIZATION; } public SerializationException(string? message) : base(message) { HResult = HResults.COR_E_SERIALIZATION; } public SerializationException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.COR_E_SERIALIZATION; } protected SerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime.Serialization { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SerializationException : SystemException { /// <summary> /// Creates a new SerializationException with its message /// string set to a default message. /// </summary> public SerializationException() : base(SR.SerializationException) { HResult = HResults.COR_E_SERIALIZATION; } public SerializationException(string? message) : base(message) { HResult = HResults.COR_E_SERIALIZATION; } public SerializationException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.COR_E_SERIALIZATION; } protected SerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/jit64/opt/cse/HugeField2.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestPriority>1</CLRTestPriority> <!-- ilasm round-trip test failure, see https://github.com/dotnet/runtime/issues/38529 --> <IlasmRoundTripIncompatible>true</IlasmRoundTripIncompatible> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="HugeField2.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestPriority>1</CLRTestPriority> <!-- ilasm round-trip test failure, see https://github.com/dotnet/runtime/issues/38529 --> <IlasmRoundTripIncompatible>true</IlasmRoundTripIncompatible> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="HugeField2.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/Common/tests/System/Xml/XPath/XmlDocument/CreateNavigatorFromXmlDocument.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests { public class CreateNavigatorFromXmlDocument : ICreateNavigator { public XPathNavigator CreateNavigatorFromFile(string fileName) { var stream = FileHelper.CreateStreamFromFile(fileName); var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.Load(stream); return xmlDocument.CreateNavigator(); } public XPathNavigator CreateNavigator(string xml) { var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.LoadXml(xml); return xmlDocument.CreateNavigator(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests { public class CreateNavigatorFromXmlDocument : ICreateNavigator { public XPathNavigator CreateNavigatorFromFile(string fileName) { var stream = FileHelper.CreateStreamFromFile(fileName); var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.Load(stream); return xmlDocument.CreateNavigator(); } public XPathNavigator CreateNavigator(string xml) { var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.LoadXml(xml); return xmlDocument.CreateNavigator(); } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/InsertSelectedScalar.Vector128.Int64.1.Vector128.Int64.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.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 InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1() { var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_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 InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray3, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = 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.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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int64, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.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(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int64> _fld1; public Vector128<Int64> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1 testClass) { var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1 testClass) { fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Int64*)pFld1), 1, AdvSimd.LoadVector128((Int64*)pFld2), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly byte ElementIndex1 = 1; private static readonly byte ElementIndex2 = 1; private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data3 = new Int64[Op3ElementCount]; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar3; private Vector128<Int64> _fld1; private Vector128<Int64> _fld3; private DataTable _dataTable; static InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data3, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.InsertSelectedScalar( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), 1, Unsafe.Read<Vector128<Int64>>(_dataTable.inArray3Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), 1, AdvSimd.LoadVector128((Int64*)(_dataTable.inArray3Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector128<Int64>), typeof(byte), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), ElementIndex1, Unsafe.Read<Vector128<Int64>>(_dataTable.inArray3Ptr), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector128<Int64>), typeof(byte), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), ElementIndex1, AdvSimd.LoadVector128((Int64*)(_dataTable.inArray3Ptr)), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar( _clsVar1, 1, _clsVar3, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int64>* pClsVar1 = &_clsVar1) fixed (Vector128<Int64>* pClsVar3 = &_clsVar3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Int64*)(pClsVar1)), 1, AdvSimd.LoadVector128((Int64*)(pClsVar3)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr); var op3 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray3Ptr); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)); var op3 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray3Ptr)); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1(); fixed (Vector128<Int64>* pFld1 = &test._fld1) fixed (Vector128<Int64>* pFld2 = &test._fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Int64*)pFld1), 1, AdvSimd.LoadVector128((Int64*)pFld2), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Int64*)pFld1), 1, AdvSimd.LoadVector128((Int64*)pFld2), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Int64*)(&test._fld1)), 1, AdvSimd.LoadVector128((Int64*)(&test._fld3)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int64> op1, Vector128<Int64> op3, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray3 = new Int64[Op3ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op3, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray3 = new Int64[Op3ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] thirdOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Insert(firstOp, ElementIndex1, thirdOp[ElementIndex2], i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.InsertSelectedScalar)}<Int64>(Vector128<Int64>, {1}, Vector128<Int64>, {1}): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1() { var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_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 InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int64[] inArray1, Int64[] inArray3, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = 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.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<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int64, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.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(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int64> _fld1; public Vector128<Int64> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1 testClass) { var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1 testClass) { fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Int64*)pFld1), 1, AdvSimd.LoadVector128((Int64*)pFld2), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly byte ElementIndex1 = 1; private static readonly byte ElementIndex2 = 1; private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data3 = new Int64[Op3ElementCount]; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar3; private Vector128<Int64> _fld1; private Vector128<Int64> _fld3; private DataTable _dataTable; static InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld3), ref Unsafe.As<Int64, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new DataTable(_data1, _data3, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.InsertSelectedScalar( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), 1, Unsafe.Read<Vector128<Int64>>(_dataTable.inArray3Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), 1, AdvSimd.LoadVector128((Int64*)(_dataTable.inArray3Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector128<Int64>), typeof(byte), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), ElementIndex1, Unsafe.Read<Vector128<Int64>>(_dataTable.inArray3Ptr), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector128<Int64>), typeof(byte), typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), ElementIndex1, AdvSimd.LoadVector128((Int64*)(_dataTable.inArray3Ptr)), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar( _clsVar1, 1, _clsVar3, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int64>* pClsVar1 = &_clsVar1) fixed (Vector128<Int64>* pClsVar3 = &_clsVar3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Int64*)(pClsVar1)), 1, AdvSimd.LoadVector128((Int64*)(pClsVar3)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr); var op3 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray3Ptr); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)); var op3 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray3Ptr)); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_Int64_1_Vector128_Int64_1(); fixed (Vector128<Int64>* pFld1 = &test._fld1) fixed (Vector128<Int64>* pFld2 = &test._fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Int64*)pFld1), 1, AdvSimd.LoadVector128((Int64*)pFld2), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int64>* pFld1 = &_fld1) fixed (Vector128<Int64>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Int64*)pFld1), 1, AdvSimd.LoadVector128((Int64*)pFld2), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((Int64*)(&test._fld1)), 1, AdvSimd.LoadVector128((Int64*)(&test._fld3)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int64> op1, Vector128<Int64> op3, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray3 = new Int64[Op3ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op3, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray3 = new Int64[Op3ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] thirdOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Insert(firstOp, ElementIndex1, thirdOp[ElementIndex2], i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.InsertSelectedScalar)}<Int64>(Vector128<Int64>, {1}, Vector128<Int64>, {1}): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); 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,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Methodical/casts/coverage/isinst_ldloc_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="isinst_ldloc.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="isinst_ldloc.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/baseservices/threading/generics/WaitCallback/thread20.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; interface IGen<T> { void Target<U>(object p); T Dummy(T t); } struct Gen<T> : IGen<T> { public T Dummy(T t) {return t;} public void Target<U>(object p) { //dummy line to avoid warnings Test_thread20.Eval(typeof(U)!=p.GetType()); ManualResetEvent evt = (ManualResetEvent) p; Interlocked.Increment(ref Test_thread20.Xcounter); evt.Set(); } public static void ThreadPoolTest<U>() { ManualResetEvent[] evts = new ManualResetEvent[Test_thread20.nThreads]; WaitHandle[] hdls = new WaitHandle[Test_thread20.nThreads]; for (int i=0; i<Test_thread20.nThreads; i++) { evts[i] = new ManualResetEvent(false); hdls[i] = (WaitHandle) evts[i]; } IGen<T> obj = new Gen<T>(); for (int i = 0; i < Test_thread20.nThreads; i++) { WaitCallback cb = new WaitCallback(obj.Target<U>); ThreadPool.QueueUserWorkItem(cb,evts[i]); } WaitHandle.WaitAll(hdls); Test_thread20.Eval(Test_thread20.Xcounter==Test_thread20.nThreads); Test_thread20.Xcounter = 0; } } public class Test_thread20 { public static int nThreads =50; public static int counter = 0; public static int Xcounter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Gen<int>.ThreadPoolTest<object>(); Gen<double>.ThreadPoolTest<string>(); Gen<string>.ThreadPoolTest<Guid>(); Gen<object>.ThreadPoolTest<int>(); Gen<Guid>.ThreadPoolTest<double>(); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; interface IGen<T> { void Target<U>(object p); T Dummy(T t); } struct Gen<T> : IGen<T> { public T Dummy(T t) {return t;} public void Target<U>(object p) { //dummy line to avoid warnings Test_thread20.Eval(typeof(U)!=p.GetType()); ManualResetEvent evt = (ManualResetEvent) p; Interlocked.Increment(ref Test_thread20.Xcounter); evt.Set(); } public static void ThreadPoolTest<U>() { ManualResetEvent[] evts = new ManualResetEvent[Test_thread20.nThreads]; WaitHandle[] hdls = new WaitHandle[Test_thread20.nThreads]; for (int i=0; i<Test_thread20.nThreads; i++) { evts[i] = new ManualResetEvent(false); hdls[i] = (WaitHandle) evts[i]; } IGen<T> obj = new Gen<T>(); for (int i = 0; i < Test_thread20.nThreads; i++) { WaitCallback cb = new WaitCallback(obj.Target<U>); ThreadPool.QueueUserWorkItem(cb,evts[i]); } WaitHandle.WaitAll(hdls); Test_thread20.Eval(Test_thread20.Xcounter==Test_thread20.nThreads); Test_thread20.Xcounter = 0; } } public class Test_thread20 { public static int nThreads =50; public static int counter = 0; public static int Xcounter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Gen<int>.ThreadPoolTest<object>(); Gen<double>.ThreadPoolTest<string>(); Gen<string>.ThreadPoolTest<Guid>(); Gen<object>.ThreadPoolTest<int>(); Gen<Guid>.ThreadPoolTest<double>(); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Private.Xml/tests/Writers/XmlWriterApi/NamespaceHandlingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using OLEDB.Test.ModuleCore; using System.IO; using System.Text; using XmlCoreTest.Common; using Xunit; namespace System.Xml.Tests { //[TestCase(Name = "XmlWriterSettings: NamespaceHandling")] public partial class TCNamespaceHandling { private static NamespaceHandling[] s_nlHandlingMembers = { NamespaceHandling.Default, NamespaceHandling.OmitDuplicates }; private StringWriter _strWriter = null; private XmlWriter CreateMemWriter(XmlWriterUtils utils, XmlWriterSettings settings) { XmlWriterSettings wSettings = settings.Clone(); wSettings.CloseOutput = false; wSettings.OmitXmlDeclaration = true; wSettings.CheckCharacters = false; XmlWriter w = null; switch (utils.WriterType) { case WriterType.UTF8Writer: wSettings.Encoding = Encoding.UTF8; if (_strWriter != null) _strWriter.Dispose(); _strWriter = new StringWriter(); w = WriterHelper.Create(_strWriter, wSettings, overrideAsync: true, async: utils.Async); break; case WriterType.UnicodeWriter: wSettings.Encoding = Encoding.Unicode; if (_strWriter != null) _strWriter.Dispose(); _strWriter = new StringWriter(); w = WriterHelper.Create(_strWriter, wSettings, overrideAsync: true, async: utils.Async); break; case WriterType.WrappedWriter: if (_strWriter != null) _strWriter.Dispose(); _strWriter = new StringWriter(); XmlWriter ww = WriterHelper.Create(_strWriter, wSettings, overrideAsync: true, async: utils.Async); w = WriterHelper.Create(ww, wSettings, overrideAsync: true, async: utils.Async); break; case WriterType.CharCheckingWriter: if (_strWriter != null) _strWriter.Dispose(); _strWriter = new StringWriter(); XmlWriter cw = WriterHelper.Create(_strWriter, wSettings, overrideAsync: true, async: utils.Async); XmlWriterSettings cws = settings.Clone(); cws.CheckCharacters = true; w = WriterHelper.Create(cw, cws, overrideAsync: true, async: utils.Async); break; default: throw new Exception("Unknown writer type"); } return w; } private void VerifyOutput(string expected) { string actual = _strWriter.ToString(); if (actual != expected) { CError.WriteLineIgnore("Expected: " + expected); CError.WriteLineIgnore("Actual: " + actual); CError.Compare(false, "Expected and actual output differ!"); } } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting)] public void NS_Handling_1(XmlWriterUtils utils) { XmlWriterSettings wSettings = new XmlWriterSettings(); CError.Compare(wSettings.NamespaceHandling, NamespaceHandling.Default, "Incorrect default value for XmlWriterSettings.NamespaceHandling"); using (XmlWriter w = CreateMemWriter(utils, wSettings)) { CError.Compare(w.Settings.NamespaceHandling, NamespaceHandling.Default, "Incorrect default value for XmlWriter.Settings.NamespaceHandling"); } return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_2(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { CError.Compare(w != null, "XmlWriter creation failed"); CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment"); } return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting)] public void NS_Handling_2a(XmlWriterUtils utils) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = NamespaceHandling.Default | NamespaceHandling.OmitDuplicates; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { CError.Compare(w.Settings.NamespaceHandling, NamespaceHandling.OmitDuplicates, "Invalid NamespaceHandling assignment"); } return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_3(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates; wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { wSettings.NamespaceHandling = NamespaceHandling.Default; CError.Compare(w != null, "XmlWriter creation failed"); CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment"); } return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_3a(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; try { wSettings.NamespaceHandling = (NamespaceHandling)(-1); CError.Compare(false, "Failed"); } catch (ArgumentOutOfRangeException) { try { wSettings.NamespaceHandling = (NamespaceHandling)(999); CError.Compare(false, "Failed2"); } catch (ArgumentOutOfRangeException) { } } using (XmlWriter w = CreateMemWriter(utils, wSettings)) { CError.Compare(w != null, "XmlWriter creation failed"); CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment"); } return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uri\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uri\" /></p:foo></root>", "<root><p:foo xmlns:p=\"uri\"><a /></p:foo></root>")] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><foo xmlns=\"uri\"><a xmlns=\"uri\" /></foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><foo xmlns=\"uri\"><a xmlns=\"uri\" /></foo></root>", "<root><foo xmlns=\"uri\"><a /></foo></root>")] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uriOther\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uriOther\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><p:foo xmlns:p=\"uri\"><a xmlns:pOther=\"uri\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><p:foo xmlns:p=\"uri\"><a xmlns:pOther=\"uri\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root xmlns:p=\"uri\"><p:foo><p:a xmlns:p=\"uri\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root xmlns:p=\"uri\"><p:foo><p:a xmlns:p=\"uri\" /></p:foo></root>", "<root xmlns:p=\"uri\"><p:foo><p:a /></p:foo></root>")] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root xmlns:p=\"uri\"><p:foo><a xmlns:p=\"uri\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root xmlns:p=\"uri\"><p:foo><a xmlns:p=\"uri\" /></p:foo></root>", "<root xmlns:p=\"uri\"><p:foo><a /></p:foo></root>")] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><p xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" /></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><p xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" /></root>", "<root><p /></root>")] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<a xmlns=\"p1\"><b xmlns=\"p2\"><c xmlns=\"p1\" /></b><d xmlns=\"\"><e xmlns=\"p1\"><f xmlns=\"\" /></e></d></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<a xmlns=\"p1\"><b xmlns=\"p2\"><c xmlns=\"p1\" /></b><d xmlns=\"\"><e xmlns=\"p1\"><f xmlns=\"\" /></e></d></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root> <elem1 xmlns=\"urn:namespace\" att1=\"foo\" /></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root> <elem1 xmlns=\"urn:namespace\" att1=\"foo\" /></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<a xmlns:p=\"p1\"><b xmlns:a=\"p1\"><c xmlns:b=\"p1\" /></b></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<a xmlns:p=\"p1\"><b xmlns:a=\"p1\"><c xmlns:b=\"p1\" /></b></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p3\" /></b></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p3\" /></b></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p1\" /></b></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p1\" /></b></a>", null)] public void NS_Handling_3b(XmlWriterUtils utils, NamespaceHandling nsHandling, string xml, string exp) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlReader r = ReaderHelper.Create(new StringReader(xml))) { using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteNode(r, false); w.Dispose(); VerifyOutput(exp == null ? xml : exp); } } return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_4a(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter ww = CreateMemWriter(utils, wSettings)) { XmlWriterSettings ws = wSettings.Clone(); ws.NamespaceHandling = NamespaceHandling.Default; ws.CheckCharacters = true; using (XmlWriter w = WriterHelper.Create(ww, ws, overrideAsync: true, async: utils.Async)) { CError.Compare(w != null, "XmlWriter creation failed"); CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment"); } } return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_4b(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter ww = CreateMemWriter(utils, wSettings)) { XmlWriterSettings ws = wSettings.Clone(); ws.NamespaceHandling = NamespaceHandling.OmitDuplicates; ws.CheckCharacters = true; using (XmlWriter w = WriterHelper.Create(ww, ws, overrideAsync: true, async: utils.Async)) { CError.Compare(w != null, "XmlWriter creation failed"); CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment"); } } return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_5(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("root", "uri"); w.WriteStartAttribute("xmlns", "p", "http://www.w3.org/2000/xmlns/"); w.WriteString("uri"); w.WriteEndElement(); } VerifyOutput("<root xmlns:p=\"uri\" xmlns=\"uri\" />"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_6(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement(null, "e", "ns"); w.WriteAttributeString(null, "attr", "ns", "val"); w.WriteElementString(null, "el", "ns", "val"); } VerifyOutput("<e p1:attr=\"val\" xmlns:p1=\"ns\" xmlns=\"ns\"><p1:el>val</p1:el></e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_7(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement(string.Empty, "e", "ns"); w.WriteAttributeString(string.Empty, "attr", "ns", "val"); w.WriteElementString(string.Empty, "el", "ns", "val"); } VerifyOutput("<e p1:attr=\"val\" xmlns:p1=\"ns\" xmlns=\"ns\"><el>val</el></e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_8(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("a", "e", "ns"); w.WriteAttributeString("a", "attr", "ns", "val"); w.WriteElementString("a", "el", "ns", "val"); } VerifyOutput("<a:e a:attr=\"val\" xmlns:a=\"ns\"><a:el>val</a:el></a:e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_9(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("e", "ns"); w.WriteAttributeString("attr", "ns", "val"); w.WriteElementString("el", "ns", "val"); } VerifyOutput("<e p1:attr=\"val\" xmlns:p1=\"ns\" xmlns=\"ns\"><p1:el>val</p1:el></e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_10(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement(null, "e", null); w.WriteAttributeString(null, "attr", null, "val"); w.WriteElementString(null, "el", null, "val"); } VerifyOutput("<e attr=\"val\"><el>val</el></e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_11(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement(string.Empty, "e", string.Empty); w.WriteAttributeString(string.Empty, "attr", string.Empty, "val"); w.WriteElementString(string.Empty, "el", string.Empty, "val"); } VerifyOutput("<e attr=\"val\"><el>val</el></e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_12(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("e"); w.WriteAttributeString("attr", "val"); w.WriteElementString("el", "val"); } VerifyOutput("<e attr=\"val\"><el>val</el></e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_16(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("a", "foo", "b"); CError.Compare(w.LookupPrefix("foo"), null, "FailedEl"); w.WriteAttributeString("a", "foo", "b"); CError.Compare(w.LookupPrefix("foo"), "p1", "FailedAttr"); w.WriteElementString("e", "foo", "b"); CError.Compare(w.LookupPrefix("foo"), "p1", "FailedEl"); } VerifyOutput("<a:foo p1:a=\"b\" xmlns:p1=\"foo\" xmlns:a=\"b\"><p1:e>b</p1:e></a:foo>"); return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_17(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteDocType("a", null, null, "<!ATTLIST Root a CDATA #IMPLIED>"); w.WriteStartElement("Root"); for (int i = 0; i < 1000; i++) { w.WriteAttributeString("a", "n" + i, "val"); } try { w.WriteAttributeString("a", "n" + 999, "val"); CError.Compare(false, "Failed"); } catch (XmlException e) { CError.WriteLine(e); return; } } Assert.True(false); } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)] public void NS_Handling_17a(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteDocType("a", null, null, "<!ATTLIST Root a CDATA #IMPLIED>"); w.WriteStartElement("Root"); for (int i = 0; i < 10; i++) { if (isAttr) w.WriteAttributeString("p", "a" + i, "n", "val"); else w.WriteElementString("p", "a" + i, "n", "val"); } } string exp = isAttr ? "<!DOCTYPE a [<!ATTLIST Root a CDATA #IMPLIED>]><Root p:a0=\"val\" p:a1=\"val\" p:a2=\"val\" p:a3=\"val\" p:a4=\"val\" p:a5=\"val\" p:a6=\"val\" p:a7=\"val\" p:a8=\"val\" p:a9=\"val\" xmlns:p=\"n\" />" : "<!DOCTYPE a [<!ATTLIST Root a CDATA #IMPLIED>]><Root><p:a0 xmlns:p=\"n\">val</p:a0><p:a1 xmlns:p=\"n\">val</p:a1><p:a2 xmlns:p=\"n\">val</p:a2><p:a3 xmlns:p=\"n\">val</p:a3><p:a4 xmlns:p=\"n\">val</p:a4><p:a5 xmlns:p=\"n\">val</p:a5><p:a6 xmlns:p=\"n\">val</p:a6><p:a7 xmlns:p=\"n\">val</p:a7><p:a8 xmlns:p=\"n\">val</p:a8><p:a9 xmlns:p=\"n\">val</p:a9></Root>"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)] public void NS_Handling_17b(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("Root"); for (int i = 0; i < 5; i++) { if (isAttr) w.WriteAttributeString("p", "a" + i, "xmlns", "val"); else w.WriteElementString("p", "a" + i, "xmlns", "val"); } } string exp = isAttr ? "<Root p:a0=\"val\" p:a1=\"val\" p:a2=\"val\" p:a3=\"val\" p:a4=\"val\" xmlns:p=\"xmlns\" />" : "<Root><p:a0 xmlns:p=\"xmlns\">val</p:a0><p:a1 xmlns:p=\"xmlns\">val</p:a1><p:a2 xmlns:p=\"xmlns\">val</p:a2><p:a3 xmlns:p=\"xmlns\">val</p:a3><p:a4 xmlns:p=\"xmlns\">val</p:a4></Root>"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)] public void NS_Handling_17c(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlWriter w = CreateMemWriter(utils, wSettings); w.WriteStartElement("Root"); for (int i = 0; i < 5; i++) { if (isAttr) w.WriteAttributeString("p" + i, "a", "n" + i, "val" + i); else w.WriteElementString("p" + i, "a", "n" + i, "val" + i); } try { if (isAttr) { w.WriteAttributeString("p", "a", "n" + 4, "val"); CError.Compare(false, "Failed"); } else w.WriteElementString("p", "a", "n" + 4, "val"); } catch (XmlException) { } finally { w.Dispose(); string exp = isAttr ? "<Root p0:a=\"val0\" p1:a=\"val1\" p2:a=\"val2\" p3:a=\"val3\" p4:a=\"val4\"" : "<Root><p0:a xmlns:p0=\"n0\">val0</p0:a><p1:a xmlns:p1=\"n1\">val1</p1:a><p2:a xmlns:p2=\"n2\">val2</p2:a><p3:a xmlns:p3=\"n3\">val3</p3:a><p4:a xmlns:p4=\"n4\">val4</p4:a><p:a xmlns:p=\"n4\">val</p:a></Root>"; VerifyOutput(exp); } return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)] public void NS_Handling_17d(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("Root"); for (int i = 0; i < 5; i++) { if (isAttr) { w.WriteAttributeString("xml", "a" + i, "http://www.w3.org/XML/1998/namespace", "val"); w.WriteAttributeString("xmlns", "a" + i, "http://www.w3.org/2000/xmlns/", "val"); } else { w.WriteElementString("xml", "a" + i, "http://www.w3.org/XML/1998/namespace", "val"); } } } string exp = isAttr ? "<Root xml:a0=\"val\" xmlns:a0=\"val\" xml:a1=\"val\" xmlns:a1=\"val\" xml:a2=\"val\" xmlns:a2=\"val\" xml:a3=\"val\" xmlns:a3=\"val\" xml:a4=\"val\" xmlns:a4=\"val\" />" : "<Root><xml:a0>val</xml:a0><xml:a1>val</xml:a1><xml:a2>val</xml:a2><xml:a3>val</xml:a3><xml:a4>val</xml:a4></Root>"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)] public void NS_Handling_17e(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("Root"); for (int i = 0; i < 5; i++) { if (isAttr) w.WriteAttributeString("a" + i, "http://www.w3.org/XML/1998/namespace", "val"); else w.WriteElementString("a" + i, "http://www.w3.org/XML/1998/namespace", "val"); } } string exp = isAttr ? "<Root xml:a0=\"val\" xml:a1=\"val\" xml:a2=\"val\" xml:a3=\"val\" xml:a4=\"val\" />" : "<Root><xml:a0>val</xml:a0><xml:a1>val</xml:a1><xml:a2>val</xml:a2><xml:a3>val</xml:a3><xml:a4>val</xml:a4></Root>"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_18(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("test"); w.WriteAttributeString("p", "a1", "ns1", "v"); w.WriteStartElement("base"); w.WriteAttributeString("a2", "ns1", "v"); w.WriteAttributeString("p", "a3", "ns2", "v"); w.WriteElementString("p", "e", "ns2", "v"); w.WriteEndElement(); w.WriteEndElement(); } string exp = "<test p:a1=\"v\" xmlns:p=\"ns1\"><base p:a2=\"v\" p4:a3=\"v\" xmlns:p4=\"ns2\"><p:e xmlns:p=\"ns2\">v</p:e></base></test>"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_19(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("Root"); w.WriteAttributeString("xmlns", "xml", null, "http://www.w3.org/XML/1998/namespace"); w.WriteAttributeString("xmlns", "space", null, "preserve"); w.WriteAttributeString("xmlns", "lang", null, "chs"); w.WriteElementString("xml", "lang", null, "jpn"); w.WriteElementString("xml", "space", null, "default"); w.WriteElementString("xml", "xml", null, "http://www.w3.org/XML/1998/namespace"); w.WriteEndElement(); } string exp = (nsHandling == NamespaceHandling.OmitDuplicates) ? "<Root xmlns:space=\"preserve\" xmlns:lang=\"chs\"><xml:lang>jpn</xml:lang><xml:space>default</xml:space><xml:xml>http://www.w3.org/XML/1998/namespace</xml:xml></Root>" : "<Root xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" xmlns:space=\"preserve\" xmlns:lang=\"chs\"><xml:lang>jpn</xml:lang><xml:space>default</xml:space><xml:xml>http://www.w3.org/XML/1998/namespace</xml:xml></Root>"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "xml", true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "xml", true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "xml", false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "xml", false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xml", "space", true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xml", "space", true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "space", false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "space", false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "lang", true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "lang", true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "lang", false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "lang", false)] public void NS_Handling_19a(XmlWriterUtils utils, NamespaceHandling nsHandling, string prefix, string name, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlWriter w = CreateMemWriter(utils, wSettings); w.WriteStartElement("Root"); try { if (isAttr) w.WriteAttributeString(prefix, name, null, null); else w.WriteElementString(prefix, name, null, null); CError.Compare(false, "error"); } catch (ArgumentException e) { CError.WriteLine(e); CError.Compare(w.WriteState, WriteState.Error, "state"); } finally { w.Dispose(); CError.Compare(w.WriteState, WriteState.Closed, "state"); } return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)] public void NS_Handling_19b(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("Root"); try { if (isAttr) w.WriteAttributeString("xmlns", "xml", null, null); else w.WriteElementString("xmlns", "xml", null, null); } catch (ArgumentException e) { CError.WriteLine(e.Message); } } string exp = isAttr ? "<Root" : "<Root><xmlns:xml"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_20(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("d", "Data", "http://example.org/data"); w.WriteStartElement("g", "GoodStuff", "http://example.org/data/good"); w.WriteAttributeString("hello", "world"); w.WriteEndElement(); w.WriteStartElement("BadStuff", "http://example.org/data/bad"); w.WriteAttributeString("hello", "world"); w.WriteEndElement(); w.WriteEndElement(); } VerifyOutput("<d:Data xmlns:d=\"http://example.org/data\"><g:GoodStuff hello=\"world\" xmlns:g=\"http://example.org/data/good\" /><BadStuff hello=\"world\" xmlns=\"http://example.org/data/bad\" /></d:Data>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_21(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; string strraw = "abc"; char[] buffer = strraw.ToCharArray(); using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("root"); w.WriteStartAttribute("xml", "lang", null); w.WriteRaw(buffer, 0, 0); w.WriteRaw(buffer, 1, 1); w.WriteRaw(buffer, 0, 2); w.WriteEndElement(); } VerifyOutput("<root xml:lang=\"bab\" />"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_22(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("root"); w.WriteStartAttribute("xml", "lang", null); w.WriteBinHex(buffer, 0, 0); w.WriteBinHex(buffer, 1, 1); w.WriteBinHex(buffer, 0, 2); w.WriteEndElement(); } VerifyOutput("<root xml:lang=\"626162\" />"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_23(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("root"); w.WriteStartAttribute("a", "b", null); w.WriteBase64(buffer, 0, 0); w.WriteBase64(buffer, 1, 1); w.WriteBase64(buffer, 0, 2); w.WriteEndElement(); } VerifyOutput("<root b=\"YmFi\" />"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_24(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlWriter w = CreateMemWriter(utils, wSettings); byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; w.WriteStartElement("A"); w.WriteAttributeString("xmlns", "p", null, "ns1"); w.WriteStartElement("B"); w.WriteAttributeString("xmlns", "p", null, "ns1"); // will be omitted try { w.WriteAttributeString("xmlns", "p", null, "ns1"); CError.Compare(false, "error"); } catch (XmlException e) { CError.WriteLine(e); } finally { w.Dispose(); VerifyOutput(nsHandling == NamespaceHandling.OmitDuplicates ? "<A xmlns:p=\"ns1\"><B" : "<A xmlns:p=\"ns1\"><B xmlns:p=\"ns1\""); } return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_25(XmlWriterUtils utils, NamespaceHandling nsHandling) { string xml = "<employees xmlns:email=\"http://www.w3c.org/some-spec-3.2\">" + "<employee><name>Bob Worker</name><address xmlns=\"http://postal.ie/spec-1.0\"><street>Nassau Street</street>" + "<city>Dublin 3</city><country>Ireland</country></address><email:address>[email protected]</email:address>" + "</employee></employees>"; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlReader r = ReaderHelper.Create(new StringReader(xml))) { using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteNode(r, false); } } VerifyOutput(xml); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_25a(XmlWriterUtils utils, NamespaceHandling nsHandling) { string xml = "<root><elem1 xmlns=\"urn:URN1\" xmlns:ns1=\"urn:URN2\"><ns1:childElem1><grandChild1 /></ns1:childElem1><childElem2><grandChild2 /></childElem2></elem1></root>"; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlReader r = ReaderHelper.Create(new StringReader(xml))) { using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteNode(r, false); } } VerifyOutput(xml); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_26(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("p", "e", "uri1"); w.WriteAttributeString("p", "e", "uri1", "val"); w.WriteAttributeString("p", "e", "uri2", "val"); w.WriteElementString("p", "e", "uri1", "val"); w.WriteElementString("p", "e", "uri2", "val"); } VerifyOutput("<p:e p:e=\"val\" p1:e=\"val\" xmlns:p1=\"uri2\" xmlns:p=\"uri1\"><p:e>val</p:e><p:e xmlns:p=\"uri2\">val</p:e></p:e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_27(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("p1", "e", "uri"); w.WriteAttributeString("p1", "e", "uri", "val"); w.WriteAttributeString("p2", "e2", "uri", "val"); w.WriteElementString("p1", "e", "uri", "val"); w.WriteElementString("p2", "e", "uri", "val"); } VerifyOutput("<p1:e p1:e=\"val\" p2:e2=\"val\" xmlns:p2=\"uri\" xmlns:p1=\"uri\"><p1:e>val</p1:e><p2:e>val</p2:e></p1:e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_29(XmlWriterUtils utils, NamespaceHandling nsHandling) { string xml = "<!DOCTYPE root [ <!ELEMENT root ANY > <!ELEMENT ns1:elem1 ANY >" + "<!ATTLIST ns1:elem1 xmlns CDATA #FIXED \"urn:URN2\"> <!ATTLIST ns1:elem1 xmlns:ns1 CDATA #FIXED \"urn:URN1\">" + "<!ELEMENT childElem1 ANY > <!ATTLIST childElem1 childElem1Att1 CDATA #FIXED \"attributeValue\">]>" + "<root> <ns1:elem1 xmlns:ns1=\"urn:URN1\" xmlns=\"urn:URN2\"> text node in elem1 <![CDATA[<doc> content </doc>]]>" + "<childElem1 childElem1Att1=\"attributeValue\"> <?PI in childElem1 ?> </childElem1> <!-- Comment in elem1 --> &amp; </ns1:elem1></root>"; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlReaderSettings rs = new XmlReaderSettings(); rs.DtdProcessing = DtdProcessing.Parse; using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs)) { using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteNode(r, false); } } VerifyOutput(xml); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_30(XmlWriterUtils utils, NamespaceHandling nsHandling) { string xml = "<!DOCTYPE doc " + "[<!ELEMENT doc ANY>" + "<!ELEMENT test1 (#PCDATA)>" + "<!ELEMENT test2 ANY>" + "<!ELEMENT test3 (#PCDATA)>" + "<!ENTITY e1 \"&e2;\">" + "<!ENTITY e2 \"xmlns:p='x'\">" + "<!ATTLIST test3 a1 CDATA #IMPLIED>" + "<!ATTLIST test3 a2 CDATA #IMPLIED>" + "]>" + "<doc xmlns:p='&e2;'>" + " &e2;" + " <test1 xmlns:p='&e2;'>AA&e2;AA</test1>" + " <test2 xmlns:p='&e1;'>BB&e1;BB</test2>" + " <test3 a1=\"&e2;\" a2=\"&e1;\">World</test3>" + "</doc>"; string exp = (nsHandling == NamespaceHandling.OmitDuplicates) ? "<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns:p='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns:p='x'\"> xmlns:p='x' <test1>AAxmlns:p='x'AA</test1> <test2>BBxmlns:p='x'BB</test2> <test3 a1=\"xmlns:p='x'\" a2=\"xmlns:p='x'\">World</test3></doc>" : "<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns:p='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns:p='x'\"> xmlns:p='x' <test1 xmlns:p=\"xmlns:p='x'\">AAxmlns:p='x'AA</test1> <test2 xmlns:p=\"xmlns:p='x'\">BBxmlns:p='x'BB</test2> <test3 a1=\"xmlns:p='x'\" a2=\"xmlns:p='x'\">World</test3></doc>"; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlReaderSettings rs = new XmlReaderSettings(); rs.DtdProcessing = DtdProcessing.Parse; using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs)) { using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteNode(r, false); } } VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_30a(XmlWriterUtils utils, NamespaceHandling nsHandling) { string xml = "<!DOCTYPE doc " + "[<!ELEMENT doc ANY>" + "<!ELEMENT test1 (#PCDATA)>" + "<!ELEMENT test2 ANY>" + "<!ELEMENT test3 (#PCDATA)>" + "<!ENTITY e1 \"&e2;\">" + "<!ENTITY e2 \"xmlns='x'\">" + "<!ATTLIST test3 a1 CDATA #IMPLIED>" + "<!ATTLIST test3 a2 CDATA #IMPLIED>" + "]>" + "<doc xmlns:p='&e2;'>" + " &e2;" + " <test1 xmlns:p='&e2;'>AA&e2;AA</test1>" + " <test2 xmlns:p='&e1;'>BB&e1;BB</test2>" + " <test3 a1=\"&e2;\" a2=\"&e1;\">World</test3>" + "</doc>"; string exp = (nsHandling == NamespaceHandling.OmitDuplicates) ? "<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns='x'\"> xmlns='x' <test1>AAxmlns='x'AA</test1> <test2>BBxmlns='x'BB</test2> <test3 a1=\"xmlns='x'\" a2=\"xmlns='x'\">World</test3></doc>" : "<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns='x'\"> xmlns='x' <test1 xmlns:p=\"xmlns='x'\">AAxmlns='x'AA</test1> <test2 xmlns:p=\"xmlns='x'\">BBxmlns='x'BB</test2> <test3 a1=\"xmlns='x'\" a2=\"xmlns='x'\">World</test3></doc>"; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlReaderSettings rs = new XmlReaderSettings(); rs.DtdProcessing = DtdProcessing.Parse; using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs)) { using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteNode(r, false); } } VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_31(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("test"); w.WriteAttributeString("p", "a1", "ns1", "v"); w.WriteStartElement("base"); w.WriteAttributeString("a2", "ns1", "v"); w.WriteAttributeString("p", "a3", "ns2", "v"); w.WriteEndElement(); w.WriteEndElement(); } VerifyOutput("<test p:a1=\"v\" xmlns:p=\"ns1\"><base p:a2=\"v\" p4:a3=\"v\" xmlns:p4=\"ns2\" /></test>"); return; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using OLEDB.Test.ModuleCore; using System.IO; using System.Text; using XmlCoreTest.Common; using Xunit; namespace System.Xml.Tests { //[TestCase(Name = "XmlWriterSettings: NamespaceHandling")] public partial class TCNamespaceHandling { private static NamespaceHandling[] s_nlHandlingMembers = { NamespaceHandling.Default, NamespaceHandling.OmitDuplicates }; private StringWriter _strWriter = null; private XmlWriter CreateMemWriter(XmlWriterUtils utils, XmlWriterSettings settings) { XmlWriterSettings wSettings = settings.Clone(); wSettings.CloseOutput = false; wSettings.OmitXmlDeclaration = true; wSettings.CheckCharacters = false; XmlWriter w = null; switch (utils.WriterType) { case WriterType.UTF8Writer: wSettings.Encoding = Encoding.UTF8; if (_strWriter != null) _strWriter.Dispose(); _strWriter = new StringWriter(); w = WriterHelper.Create(_strWriter, wSettings, overrideAsync: true, async: utils.Async); break; case WriterType.UnicodeWriter: wSettings.Encoding = Encoding.Unicode; if (_strWriter != null) _strWriter.Dispose(); _strWriter = new StringWriter(); w = WriterHelper.Create(_strWriter, wSettings, overrideAsync: true, async: utils.Async); break; case WriterType.WrappedWriter: if (_strWriter != null) _strWriter.Dispose(); _strWriter = new StringWriter(); XmlWriter ww = WriterHelper.Create(_strWriter, wSettings, overrideAsync: true, async: utils.Async); w = WriterHelper.Create(ww, wSettings, overrideAsync: true, async: utils.Async); break; case WriterType.CharCheckingWriter: if (_strWriter != null) _strWriter.Dispose(); _strWriter = new StringWriter(); XmlWriter cw = WriterHelper.Create(_strWriter, wSettings, overrideAsync: true, async: utils.Async); XmlWriterSettings cws = settings.Clone(); cws.CheckCharacters = true; w = WriterHelper.Create(cw, cws, overrideAsync: true, async: utils.Async); break; default: throw new Exception("Unknown writer type"); } return w; } private void VerifyOutput(string expected) { string actual = _strWriter.ToString(); if (actual != expected) { CError.WriteLineIgnore("Expected: " + expected); CError.WriteLineIgnore("Actual: " + actual); CError.Compare(false, "Expected and actual output differ!"); } } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting)] public void NS_Handling_1(XmlWriterUtils utils) { XmlWriterSettings wSettings = new XmlWriterSettings(); CError.Compare(wSettings.NamespaceHandling, NamespaceHandling.Default, "Incorrect default value for XmlWriterSettings.NamespaceHandling"); using (XmlWriter w = CreateMemWriter(utils, wSettings)) { CError.Compare(w.Settings.NamespaceHandling, NamespaceHandling.Default, "Incorrect default value for XmlWriter.Settings.NamespaceHandling"); } return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_2(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { CError.Compare(w != null, "XmlWriter creation failed"); CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment"); } return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting)] public void NS_Handling_2a(XmlWriterUtils utils) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = NamespaceHandling.Default | NamespaceHandling.OmitDuplicates; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { CError.Compare(w.Settings.NamespaceHandling, NamespaceHandling.OmitDuplicates, "Invalid NamespaceHandling assignment"); } return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_3(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates; wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { wSettings.NamespaceHandling = NamespaceHandling.Default; CError.Compare(w != null, "XmlWriter creation failed"); CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment"); } return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_3a(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; try { wSettings.NamespaceHandling = (NamespaceHandling)(-1); CError.Compare(false, "Failed"); } catch (ArgumentOutOfRangeException) { try { wSettings.NamespaceHandling = (NamespaceHandling)(999); CError.Compare(false, "Failed2"); } catch (ArgumentOutOfRangeException) { } } using (XmlWriter w = CreateMemWriter(utils, wSettings)) { CError.Compare(w != null, "XmlWriter creation failed"); CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment"); } return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uri\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uri\" /></p:foo></root>", "<root><p:foo xmlns:p=\"uri\"><a /></p:foo></root>")] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><foo xmlns=\"uri\"><a xmlns=\"uri\" /></foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><foo xmlns=\"uri\"><a xmlns=\"uri\" /></foo></root>", "<root><foo xmlns=\"uri\"><a /></foo></root>")] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uriOther\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><p:foo xmlns:p=\"uri\"><a xmlns:p=\"uriOther\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><p:foo xmlns:p=\"uri\"><a xmlns:pOther=\"uri\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><p:foo xmlns:p=\"uri\"><a xmlns:pOther=\"uri\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root xmlns:p=\"uri\"><p:foo><p:a xmlns:p=\"uri\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root xmlns:p=\"uri\"><p:foo><p:a xmlns:p=\"uri\" /></p:foo></root>", "<root xmlns:p=\"uri\"><p:foo><p:a /></p:foo></root>")] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root xmlns:p=\"uri\"><p:foo><a xmlns:p=\"uri\" /></p:foo></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root xmlns:p=\"uri\"><p:foo><a xmlns:p=\"uri\" /></p:foo></root>", "<root xmlns:p=\"uri\"><p:foo><a /></p:foo></root>")] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root><p xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" /></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root><p xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" /></root>", "<root><p /></root>")] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<a xmlns=\"p1\"><b xmlns=\"p2\"><c xmlns=\"p1\" /></b><d xmlns=\"\"><e xmlns=\"p1\"><f xmlns=\"\" /></e></d></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<a xmlns=\"p1\"><b xmlns=\"p2\"><c xmlns=\"p1\" /></b><d xmlns=\"\"><e xmlns=\"p1\"><f xmlns=\"\" /></e></d></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<root> <elem1 xmlns=\"urn:namespace\" att1=\"foo\" /></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<root> <elem1 xmlns=\"urn:namespace\" att1=\"foo\" /></root>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<a xmlns:p=\"p1\"><b xmlns:a=\"p1\"><c xmlns:b=\"p1\" /></b></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<a xmlns:p=\"p1\"><b xmlns:a=\"p1\"><c xmlns:b=\"p1\" /></b></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p3\" /></b></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p3\" /></b></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p1\" /></b></a>", null)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "<a xmlns:p=\"p1\"><b xmlns:p=\"p2\"><c xmlns:p=\"p1\" /></b></a>", null)] public void NS_Handling_3b(XmlWriterUtils utils, NamespaceHandling nsHandling, string xml, string exp) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlReader r = ReaderHelper.Create(new StringReader(xml))) { using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteNode(r, false); w.Dispose(); VerifyOutput(exp == null ? xml : exp); } } return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_4a(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter ww = CreateMemWriter(utils, wSettings)) { XmlWriterSettings ws = wSettings.Clone(); ws.NamespaceHandling = NamespaceHandling.Default; ws.CheckCharacters = true; using (XmlWriter w = WriterHelper.Create(ww, ws, overrideAsync: true, async: utils.Async)) { CError.Compare(w != null, "XmlWriter creation failed"); CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment"); } } return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_4b(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter ww = CreateMemWriter(utils, wSettings)) { XmlWriterSettings ws = wSettings.Clone(); ws.NamespaceHandling = NamespaceHandling.OmitDuplicates; ws.CheckCharacters = true; using (XmlWriter w = WriterHelper.Create(ww, ws, overrideAsync: true, async: utils.Async)) { CError.Compare(w != null, "XmlWriter creation failed"); CError.Compare(w.Settings.NamespaceHandling, nsHandling, "Invalid NamespaceHandling assignment"); } } return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_5(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("root", "uri"); w.WriteStartAttribute("xmlns", "p", "http://www.w3.org/2000/xmlns/"); w.WriteString("uri"); w.WriteEndElement(); } VerifyOutput("<root xmlns:p=\"uri\" xmlns=\"uri\" />"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_6(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement(null, "e", "ns"); w.WriteAttributeString(null, "attr", "ns", "val"); w.WriteElementString(null, "el", "ns", "val"); } VerifyOutput("<e p1:attr=\"val\" xmlns:p1=\"ns\" xmlns=\"ns\"><p1:el>val</p1:el></e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_7(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement(string.Empty, "e", "ns"); w.WriteAttributeString(string.Empty, "attr", "ns", "val"); w.WriteElementString(string.Empty, "el", "ns", "val"); } VerifyOutput("<e p1:attr=\"val\" xmlns:p1=\"ns\" xmlns=\"ns\"><el>val</el></e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_8(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("a", "e", "ns"); w.WriteAttributeString("a", "attr", "ns", "val"); w.WriteElementString("a", "el", "ns", "val"); } VerifyOutput("<a:e a:attr=\"val\" xmlns:a=\"ns\"><a:el>val</a:el></a:e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_9(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("e", "ns"); w.WriteAttributeString("attr", "ns", "val"); w.WriteElementString("el", "ns", "val"); } VerifyOutput("<e p1:attr=\"val\" xmlns:p1=\"ns\" xmlns=\"ns\"><p1:el>val</p1:el></e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_10(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement(null, "e", null); w.WriteAttributeString(null, "attr", null, "val"); w.WriteElementString(null, "el", null, "val"); } VerifyOutput("<e attr=\"val\"><el>val</el></e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_11(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement(string.Empty, "e", string.Empty); w.WriteAttributeString(string.Empty, "attr", string.Empty, "val"); w.WriteElementString(string.Empty, "el", string.Empty, "val"); } VerifyOutput("<e attr=\"val\"><el>val</el></e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_12(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("e"); w.WriteAttributeString("attr", "val"); w.WriteElementString("el", "val"); } VerifyOutput("<e attr=\"val\"><el>val</el></e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_16(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("a", "foo", "b"); CError.Compare(w.LookupPrefix("foo"), null, "FailedEl"); w.WriteAttributeString("a", "foo", "b"); CError.Compare(w.LookupPrefix("foo"), "p1", "FailedAttr"); w.WriteElementString("e", "foo", "b"); CError.Compare(w.LookupPrefix("foo"), "p1", "FailedEl"); } VerifyOutput("<a:foo p1:a=\"b\" xmlns:p1=\"foo\" xmlns:a=\"b\"><p1:e>b</p1:e></a:foo>"); return; } [Theory] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_17(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteDocType("a", null, null, "<!ATTLIST Root a CDATA #IMPLIED>"); w.WriteStartElement("Root"); for (int i = 0; i < 1000; i++) { w.WriteAttributeString("a", "n" + i, "val"); } try { w.WriteAttributeString("a", "n" + 999, "val"); CError.Compare(false, "Failed"); } catch (XmlException e) { CError.WriteLine(e); return; } } Assert.True(false); } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)] public void NS_Handling_17a(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteDocType("a", null, null, "<!ATTLIST Root a CDATA #IMPLIED>"); w.WriteStartElement("Root"); for (int i = 0; i < 10; i++) { if (isAttr) w.WriteAttributeString("p", "a" + i, "n", "val"); else w.WriteElementString("p", "a" + i, "n", "val"); } } string exp = isAttr ? "<!DOCTYPE a [<!ATTLIST Root a CDATA #IMPLIED>]><Root p:a0=\"val\" p:a1=\"val\" p:a2=\"val\" p:a3=\"val\" p:a4=\"val\" p:a5=\"val\" p:a6=\"val\" p:a7=\"val\" p:a8=\"val\" p:a9=\"val\" xmlns:p=\"n\" />" : "<!DOCTYPE a [<!ATTLIST Root a CDATA #IMPLIED>]><Root><p:a0 xmlns:p=\"n\">val</p:a0><p:a1 xmlns:p=\"n\">val</p:a1><p:a2 xmlns:p=\"n\">val</p:a2><p:a3 xmlns:p=\"n\">val</p:a3><p:a4 xmlns:p=\"n\">val</p:a4><p:a5 xmlns:p=\"n\">val</p:a5><p:a6 xmlns:p=\"n\">val</p:a6><p:a7 xmlns:p=\"n\">val</p:a7><p:a8 xmlns:p=\"n\">val</p:a8><p:a9 xmlns:p=\"n\">val</p:a9></Root>"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)] public void NS_Handling_17b(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("Root"); for (int i = 0; i < 5; i++) { if (isAttr) w.WriteAttributeString("p", "a" + i, "xmlns", "val"); else w.WriteElementString("p", "a" + i, "xmlns", "val"); } } string exp = isAttr ? "<Root p:a0=\"val\" p:a1=\"val\" p:a2=\"val\" p:a3=\"val\" p:a4=\"val\" xmlns:p=\"xmlns\" />" : "<Root><p:a0 xmlns:p=\"xmlns\">val</p:a0><p:a1 xmlns:p=\"xmlns\">val</p:a1><p:a2 xmlns:p=\"xmlns\">val</p:a2><p:a3 xmlns:p=\"xmlns\">val</p:a3><p:a4 xmlns:p=\"xmlns\">val</p:a4></Root>"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)] public void NS_Handling_17c(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlWriter w = CreateMemWriter(utils, wSettings); w.WriteStartElement("Root"); for (int i = 0; i < 5; i++) { if (isAttr) w.WriteAttributeString("p" + i, "a", "n" + i, "val" + i); else w.WriteElementString("p" + i, "a", "n" + i, "val" + i); } try { if (isAttr) { w.WriteAttributeString("p", "a", "n" + 4, "val"); CError.Compare(false, "Failed"); } else w.WriteElementString("p", "a", "n" + 4, "val"); } catch (XmlException) { } finally { w.Dispose(); string exp = isAttr ? "<Root p0:a=\"val0\" p1:a=\"val1\" p2:a=\"val2\" p3:a=\"val3\" p4:a=\"val4\"" : "<Root><p0:a xmlns:p0=\"n0\">val0</p0:a><p1:a xmlns:p1=\"n1\">val1</p1:a><p2:a xmlns:p2=\"n2\">val2</p2:a><p3:a xmlns:p3=\"n3\">val3</p3:a><p4:a xmlns:p4=\"n4\">val4</p4:a><p:a xmlns:p=\"n4\">val</p:a></Root>"; VerifyOutput(exp); } return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)] public void NS_Handling_17d(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("Root"); for (int i = 0; i < 5; i++) { if (isAttr) { w.WriteAttributeString("xml", "a" + i, "http://www.w3.org/XML/1998/namespace", "val"); w.WriteAttributeString("xmlns", "a" + i, "http://www.w3.org/2000/xmlns/", "val"); } else { w.WriteElementString("xml", "a" + i, "http://www.w3.org/XML/1998/namespace", "val"); } } } string exp = isAttr ? "<Root xml:a0=\"val\" xmlns:a0=\"val\" xml:a1=\"val\" xmlns:a1=\"val\" xml:a2=\"val\" xmlns:a2=\"val\" xml:a3=\"val\" xmlns:a3=\"val\" xml:a4=\"val\" xmlns:a4=\"val\" />" : "<Root><xml:a0>val</xml:a0><xml:a1>val</xml:a1><xml:a2>val</xml:a2><xml:a3>val</xml:a3><xml:a4>val</xml:a4></Root>"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)] public void NS_Handling_17e(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("Root"); for (int i = 0; i < 5; i++) { if (isAttr) w.WriteAttributeString("a" + i, "http://www.w3.org/XML/1998/namespace", "val"); else w.WriteElementString("a" + i, "http://www.w3.org/XML/1998/namespace", "val"); } } string exp = isAttr ? "<Root xml:a0=\"val\" xml:a1=\"val\" xml:a2=\"val\" xml:a3=\"val\" xml:a4=\"val\" />" : "<Root><xml:a0>val</xml:a0><xml:a1>val</xml:a1><xml:a2>val</xml:a2><xml:a3>val</xml:a3><xml:a4>val</xml:a4></Root>"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_18(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("test"); w.WriteAttributeString("p", "a1", "ns1", "v"); w.WriteStartElement("base"); w.WriteAttributeString("a2", "ns1", "v"); w.WriteAttributeString("p", "a3", "ns2", "v"); w.WriteElementString("p", "e", "ns2", "v"); w.WriteEndElement(); w.WriteEndElement(); } string exp = "<test p:a1=\"v\" xmlns:p=\"ns1\"><base p:a2=\"v\" p4:a3=\"v\" xmlns:p4=\"ns2\"><p:e xmlns:p=\"ns2\">v</p:e></base></test>"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_19(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("Root"); w.WriteAttributeString("xmlns", "xml", null, "http://www.w3.org/XML/1998/namespace"); w.WriteAttributeString("xmlns", "space", null, "preserve"); w.WriteAttributeString("xmlns", "lang", null, "chs"); w.WriteElementString("xml", "lang", null, "jpn"); w.WriteElementString("xml", "space", null, "default"); w.WriteElementString("xml", "xml", null, "http://www.w3.org/XML/1998/namespace"); w.WriteEndElement(); } string exp = (nsHandling == NamespaceHandling.OmitDuplicates) ? "<Root xmlns:space=\"preserve\" xmlns:lang=\"chs\"><xml:lang>jpn</xml:lang><xml:space>default</xml:space><xml:xml>http://www.w3.org/XML/1998/namespace</xml:xml></Root>" : "<Root xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" xmlns:space=\"preserve\" xmlns:lang=\"chs\"><xml:lang>jpn</xml:lang><xml:space>default</xml:space><xml:xml>http://www.w3.org/XML/1998/namespace</xml:xml></Root>"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "xml", true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "xml", true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "xml", false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "xml", false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xml", "space", true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xml", "space", true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "space", false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "space", false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "lang", true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "lang", true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, "xmlns", "lang", false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, "xmlns", "lang", false)] public void NS_Handling_19a(XmlWriterUtils utils, NamespaceHandling nsHandling, string prefix, string name, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlWriter w = CreateMemWriter(utils, wSettings); w.WriteStartElement("Root"); try { if (isAttr) w.WriteAttributeString(prefix, name, null, null); else w.WriteElementString(prefix, name, null, null); CError.Compare(false, "error"); } catch (ArgumentException e) { CError.WriteLine(e); CError.Compare(w.WriteState, WriteState.Error, "state"); } finally { w.Dispose(); CError.Compare(w.WriteState, WriteState.Closed, "state"); } return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, true)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default, false)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates, false)] public void NS_Handling_19b(XmlWriterUtils utils, NamespaceHandling nsHandling, bool isAttr) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("Root"); try { if (isAttr) w.WriteAttributeString("xmlns", "xml", null, null); else w.WriteElementString("xmlns", "xml", null, null); } catch (ArgumentException e) { CError.WriteLine(e.Message); } } string exp = isAttr ? "<Root" : "<Root><xmlns:xml"; VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_20(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("d", "Data", "http://example.org/data"); w.WriteStartElement("g", "GoodStuff", "http://example.org/data/good"); w.WriteAttributeString("hello", "world"); w.WriteEndElement(); w.WriteStartElement("BadStuff", "http://example.org/data/bad"); w.WriteAttributeString("hello", "world"); w.WriteEndElement(); w.WriteEndElement(); } VerifyOutput("<d:Data xmlns:d=\"http://example.org/data\"><g:GoodStuff hello=\"world\" xmlns:g=\"http://example.org/data/good\" /><BadStuff hello=\"world\" xmlns=\"http://example.org/data/bad\" /></d:Data>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_21(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; string strraw = "abc"; char[] buffer = strraw.ToCharArray(); using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("root"); w.WriteStartAttribute("xml", "lang", null); w.WriteRaw(buffer, 0, 0); w.WriteRaw(buffer, 1, 1); w.WriteRaw(buffer, 0, 2); w.WriteEndElement(); } VerifyOutput("<root xml:lang=\"bab\" />"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_22(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("root"); w.WriteStartAttribute("xml", "lang", null); w.WriteBinHex(buffer, 0, 0); w.WriteBinHex(buffer, 1, 1); w.WriteBinHex(buffer, 0, 2); w.WriteEndElement(); } VerifyOutput("<root xml:lang=\"626162\" />"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_23(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("root"); w.WriteStartAttribute("a", "b", null); w.WriteBase64(buffer, 0, 0); w.WriteBase64(buffer, 1, 1); w.WriteBase64(buffer, 0, 2); w.WriteEndElement(); } VerifyOutput("<root b=\"YmFi\" />"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_24(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlWriter w = CreateMemWriter(utils, wSettings); byte[] buffer = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; w.WriteStartElement("A"); w.WriteAttributeString("xmlns", "p", null, "ns1"); w.WriteStartElement("B"); w.WriteAttributeString("xmlns", "p", null, "ns1"); // will be omitted try { w.WriteAttributeString("xmlns", "p", null, "ns1"); CError.Compare(false, "error"); } catch (XmlException e) { CError.WriteLine(e); } finally { w.Dispose(); VerifyOutput(nsHandling == NamespaceHandling.OmitDuplicates ? "<A xmlns:p=\"ns1\"><B" : "<A xmlns:p=\"ns1\"><B xmlns:p=\"ns1\""); } return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_25(XmlWriterUtils utils, NamespaceHandling nsHandling) { string xml = "<employees xmlns:email=\"http://www.w3c.org/some-spec-3.2\">" + "<employee><name>Bob Worker</name><address xmlns=\"http://postal.ie/spec-1.0\"><street>Nassau Street</street>" + "<city>Dublin 3</city><country>Ireland</country></address><email:address>[email protected]</email:address>" + "</employee></employees>"; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlReader r = ReaderHelper.Create(new StringReader(xml))) { using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteNode(r, false); } } VerifyOutput(xml); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_25a(XmlWriterUtils utils, NamespaceHandling nsHandling) { string xml = "<root><elem1 xmlns=\"urn:URN1\" xmlns:ns1=\"urn:URN2\"><ns1:childElem1><grandChild1 /></ns1:childElem1><childElem2><grandChild2 /></childElem2></elem1></root>"; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlReader r = ReaderHelper.Create(new StringReader(xml))) { using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteNode(r, false); } } VerifyOutput(xml); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_26(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("p", "e", "uri1"); w.WriteAttributeString("p", "e", "uri1", "val"); w.WriteAttributeString("p", "e", "uri2", "val"); w.WriteElementString("p", "e", "uri1", "val"); w.WriteElementString("p", "e", "uri2", "val"); } VerifyOutput("<p:e p:e=\"val\" p1:e=\"val\" xmlns:p1=\"uri2\" xmlns:p=\"uri1\"><p:e>val</p:e><p:e xmlns:p=\"uri2\">val</p:e></p:e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_27(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("p1", "e", "uri"); w.WriteAttributeString("p1", "e", "uri", "val"); w.WriteAttributeString("p2", "e2", "uri", "val"); w.WriteElementString("p1", "e", "uri", "val"); w.WriteElementString("p2", "e", "uri", "val"); } VerifyOutput("<p1:e p1:e=\"val\" p2:e2=\"val\" xmlns:p2=\"uri\" xmlns:p1=\"uri\"><p1:e>val</p1:e><p2:e>val</p2:e></p1:e>"); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_29(XmlWriterUtils utils, NamespaceHandling nsHandling) { string xml = "<!DOCTYPE root [ <!ELEMENT root ANY > <!ELEMENT ns1:elem1 ANY >" + "<!ATTLIST ns1:elem1 xmlns CDATA #FIXED \"urn:URN2\"> <!ATTLIST ns1:elem1 xmlns:ns1 CDATA #FIXED \"urn:URN1\">" + "<!ELEMENT childElem1 ANY > <!ATTLIST childElem1 childElem1Att1 CDATA #FIXED \"attributeValue\">]>" + "<root> <ns1:elem1 xmlns:ns1=\"urn:URN1\" xmlns=\"urn:URN2\"> text node in elem1 <![CDATA[<doc> content </doc>]]>" + "<childElem1 childElem1Att1=\"attributeValue\"> <?PI in childElem1 ?> </childElem1> <!-- Comment in elem1 --> &amp; </ns1:elem1></root>"; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlReaderSettings rs = new XmlReaderSettings(); rs.DtdProcessing = DtdProcessing.Parse; using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs)) { using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteNode(r, false); } } VerifyOutput(xml); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_30(XmlWriterUtils utils, NamespaceHandling nsHandling) { string xml = "<!DOCTYPE doc " + "[<!ELEMENT doc ANY>" + "<!ELEMENT test1 (#PCDATA)>" + "<!ELEMENT test2 ANY>" + "<!ELEMENT test3 (#PCDATA)>" + "<!ENTITY e1 \"&e2;\">" + "<!ENTITY e2 \"xmlns:p='x'\">" + "<!ATTLIST test3 a1 CDATA #IMPLIED>" + "<!ATTLIST test3 a2 CDATA #IMPLIED>" + "]>" + "<doc xmlns:p='&e2;'>" + " &e2;" + " <test1 xmlns:p='&e2;'>AA&e2;AA</test1>" + " <test2 xmlns:p='&e1;'>BB&e1;BB</test2>" + " <test3 a1=\"&e2;\" a2=\"&e1;\">World</test3>" + "</doc>"; string exp = (nsHandling == NamespaceHandling.OmitDuplicates) ? "<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns:p='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns:p='x'\"> xmlns:p='x' <test1>AAxmlns:p='x'AA</test1> <test2>BBxmlns:p='x'BB</test2> <test3 a1=\"xmlns:p='x'\" a2=\"xmlns:p='x'\">World</test3></doc>" : "<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns:p='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns:p='x'\"> xmlns:p='x' <test1 xmlns:p=\"xmlns:p='x'\">AAxmlns:p='x'AA</test1> <test2 xmlns:p=\"xmlns:p='x'\">BBxmlns:p='x'BB</test2> <test3 a1=\"xmlns:p='x'\" a2=\"xmlns:p='x'\">World</test3></doc>"; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlReaderSettings rs = new XmlReaderSettings(); rs.DtdProcessing = DtdProcessing.Parse; using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs)) { using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteNode(r, false); } } VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_30a(XmlWriterUtils utils, NamespaceHandling nsHandling) { string xml = "<!DOCTYPE doc " + "[<!ELEMENT doc ANY>" + "<!ELEMENT test1 (#PCDATA)>" + "<!ELEMENT test2 ANY>" + "<!ELEMENT test3 (#PCDATA)>" + "<!ENTITY e1 \"&e2;\">" + "<!ENTITY e2 \"xmlns='x'\">" + "<!ATTLIST test3 a1 CDATA #IMPLIED>" + "<!ATTLIST test3 a2 CDATA #IMPLIED>" + "]>" + "<doc xmlns:p='&e2;'>" + " &e2;" + " <test1 xmlns:p='&e2;'>AA&e2;AA</test1>" + " <test2 xmlns:p='&e1;'>BB&e1;BB</test2>" + " <test3 a1=\"&e2;\" a2=\"&e1;\">World</test3>" + "</doc>"; string exp = (nsHandling == NamespaceHandling.OmitDuplicates) ? "<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns='x'\"> xmlns='x' <test1>AAxmlns='x'AA</test1> <test2>BBxmlns='x'BB</test2> <test3 a1=\"xmlns='x'\" a2=\"xmlns='x'\">World</test3></doc>" : "<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns='x'\"> xmlns='x' <test1 xmlns:p=\"xmlns='x'\">AAxmlns='x'AA</test1> <test2 xmlns:p=\"xmlns='x'\">BBxmlns='x'BB</test2> <test3 a1=\"xmlns='x'\" a2=\"xmlns='x'\">World</test3></doc>"; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; XmlReaderSettings rs = new XmlReaderSettings(); rs.DtdProcessing = DtdProcessing.Parse; using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs)) { using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteNode(r, false); } } VerifyOutput(exp); return; } [Theory] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.Default)] [XmlWriterInlineData(~WriterType.Async & WriterType.AllButCustom & WriterType.AllButIndenting, NamespaceHandling.OmitDuplicates)] public void NS_Handling_31(XmlWriterUtils utils, NamespaceHandling nsHandling) { XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = nsHandling; using (XmlWriter w = CreateMemWriter(utils, wSettings)) { w.WriteStartElement("test"); w.WriteAttributeString("p", "a1", "ns1", "v"); w.WriteStartElement("base"); w.WriteAttributeString("a2", "ns1", "v"); w.WriteAttributeString("p", "a3", "ns2", "v"); w.WriteEndElement(); w.WriteEndElement(); } VerifyOutput("<test p:a1=\"v\" xmlns:p=\"ns1\"><base p:a2=\"v\" p4:a3=\"v\" xmlns:p4=\"ns2\" /></test>"); return; } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Text.Json/Common/JsonCamelCaseNamingPolicy.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.Text.Json { internal sealed class JsonCamelCaseNamingPolicy : JsonNamingPolicy { public override string ConvertName(string name) { if (string.IsNullOrEmpty(name) || !char.IsUpper(name[0])) { return name; } #if BUILDING_INBOX_LIBRARY return string.Create(name.Length, name, (chars, name) => { name #if !NETCOREAPP .AsSpan() #endif .CopyTo(chars); FixCasing(chars); }); #else char[] chars = name.ToCharArray(); FixCasing(chars); return new string(chars); #endif } private static void FixCasing(Span<char> chars) { for (int i = 0; i < chars.Length; i++) { if (i == 1 && !char.IsUpper(chars[i])) { break; } bool hasNext = (i + 1 < chars.Length); // Stop when next char is already lowercase. if (i > 0 && hasNext && !char.IsUpper(chars[i + 1])) { // If the next char is a space, lowercase current char before exiting. if (chars[i + 1] == ' ') { chars[i] = char.ToLowerInvariant(chars[i]); } break; } chars[i] = char.ToLowerInvariant(chars[i]); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Text.Json { internal sealed class JsonCamelCaseNamingPolicy : JsonNamingPolicy { public override string ConvertName(string name) { if (string.IsNullOrEmpty(name) || !char.IsUpper(name[0])) { return name; } #if BUILDING_INBOX_LIBRARY return string.Create(name.Length, name, (chars, name) => { name #if !NETCOREAPP .AsSpan() #endif .CopyTo(chars); FixCasing(chars); }); #else char[] chars = name.ToCharArray(); FixCasing(chars); return new string(chars); #endif } private static void FixCasing(Span<char> chars) { for (int i = 0; i < chars.Length; i++) { if (i == 1 && !char.IsUpper(chars[i])) { break; } bool hasNext = (i + 1 < chars.Length); // Stop when next char is already lowercase. if (i > 0 && hasNext && !char.IsUpper(chars[i + 1])) { // If the next char is a space, lowercase current char before exiting. if (chars[i + 1] == ' ') { chars[i] = char.ToLowerInvariant(chars[i]); } break; } chars[i] = char.ToLowerInvariant(chars[i]); } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Linq.Expressions/tests/HelperTypes.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.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Linq.Expressions.Tests { public interface I { void M(); } public class C : IEquatable<C>, I { void I.M() { } public override bool Equals(object o) { return o is C && Equals((C)o); } public bool Equals(C c) { return c != null; } public override int GetHashCode() { return 0; } } public class D : C, IEquatable<D> { public int Val; public string S; public D() { } public D(int val) : this(val, "") { } public D(int val, string s) { Val = val; S = s; } public override bool Equals(object o) { return o is D && Equals((D)o); } public bool Equals(D d) { return d != null && d.Val == Val; } public override int GetHashCode() { return Val; } } public enum E { A = 1, B = 2, Red = 0, Green, Blue } public enum El : long { A, B, C } public enum Eu : uint { Foo, Bar, Baz } public struct S : IEquatable<S> { public override bool Equals(object o) { return (o is S) && Equals((S)o); } public bool Equals(S other) { return true; } public override int GetHashCode() { return 0; } } public struct Sp : IEquatable<Sp> { public Sp(int i, double d) { I = i; D = d; } public int I; public double D; public override bool Equals(object o) { return (o is Sp) && Equals((Sp)o); } public bool Equals(Sp other) { return other.I == I && other.D.Equals(D); } public override int GetHashCode() { return I.GetHashCode() ^ D.GetHashCode(); } } public struct Ss : IEquatable<Ss> { public Ss(S s) { Val = s; } public S Val; public override bool Equals(object o) { return (o is Ss) && Equals((Ss)o); } public bool Equals(Ss other) { return other.Val.Equals(Val); } public override int GetHashCode() { return Val.GetHashCode(); } } public struct Sc : IEquatable<Sc> { public Sc(string s) { S = s; } public string S; public override bool Equals(object o) { return (o is Sc) && Equals((Sc)o); } public bool Equals(Sc other) { return other.S == S; } public override int GetHashCode() { return S.GetHashCode(); } } public struct Scs : IEquatable<Scs> { public Scs(string s, S val) { S = s; Val = val; } public string S; public S Val; public override bool Equals(object o) { return (o is Scs) && Equals((Scs)o); } public bool Equals(Scs other) { return other.S == S && other.Val.Equals(Val); } public override int GetHashCode() { return S.GetHashCode() ^ Val.GetHashCode(); } } public class BaseClass { } public class FC { public int II; public static int SI; public const int CI = 42; public static readonly int RI = 42; } public struct FS { public int II; public static int SI; public const int CI = 42; public static readonly int RI = 42; } public class PC { public int II { get; set; } public static int SI { get; set; } public int this[int i] { get { return 1; } set { } } } public struct PS { public int II { get; set; } public static int SI { get; set; } } internal class CompilationTypes : IEnumerable<object[]> { private static IEnumerable<object[]> Booleans { get { return LambdaExpression.CanCompileToIL ? new[] { new object[] {false}, new object[] {true}, } : new[] { new object[] {true}, }; } } public IEnumerator<object[]> GetEnumerator() => Booleans.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } internal class NoOpVisitor : ExpressionVisitor { internal static readonly NoOpVisitor Instance = new NoOpVisitor(); private NoOpVisitor() { } } public static class Unreadable<T> { public static T WriteOnly { set { } } } public class GenericClass<T> { public void Method() { } public static T Field; public static T Property => Field; } public class NonGenericClass { #pragma warning disable 0067 public event EventHandler Event; #pragma warning restore 0067 public void GenericMethod<T>() { } public static void StaticMethod() { } public static readonly NonGenericClass NonGenericField = new NonGenericClass(); public static NonGenericClass NonGenericProperty => NonGenericField; } public class InvalidTypesData : IEnumerable<object[]> { private static readonly object[] GenericTypeDefinition = new object[] { typeof(GenericClass<>) }; private static readonly object[] ContainsGenericParameters = new object[] { typeof(GenericClass<>).MakeGenericType(typeof(GenericClass<>)) }; public IEnumerator<object[]> GetEnumerator() { yield return GenericTypeDefinition; yield return ContainsGenericParameters; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } public class UnreadableExpressionsData : IEnumerable<object[]> { private static readonly object[] Property = new object[] { Expression.Property(null, typeof(Unreadable<bool>), nameof(Unreadable<bool>.WriteOnly)) }; private static readonly object[] Indexer = new object[] { Expression.Property(null, typeof(Unreadable<bool>).GetProperty(nameof(Unreadable<bool>.WriteOnly)), new Expression[0]) }; public IEnumerator<object[]> GetEnumerator() { yield return Property; yield return Indexer; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class OpenGenericMethodsData : IEnumerable<object[]> { private static readonly object[] GenericClass = new object[] { typeof(GenericClass<>).GetMethod(nameof(GenericClass<string>.Method)) }; private static readonly object[] GenericMethod = new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.GenericMethod)) }; public IEnumerator<object[]> GetEnumerator() { yield return GenericClass; yield return GenericMethod; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public struct ValueTypeWithParameterlessConstructor { public readonly bool ConstructorWasRun; public ValueTypeWithParameterlessConstructor() { ConstructorWasRun = true; } } public struct ValueTypeWithParameterlessConstructorThatThrows { public readonly object Value; public ValueTypeWithParameterlessConstructorThatThrows() { throw new InvalidOperationException(); } public ValueTypeWithParameterlessConstructorThatThrows(object value) { Value = value; } } public enum ByteEnum : byte { A = byte.MaxValue } public enum SByteEnum : sbyte { A = sbyte.MaxValue } public enum Int16Enum : short { A = short.MaxValue } public enum UInt16Enum : ushort { A = ushort.MaxValue } public enum Int32Enum : int { A = int.MaxValue } public enum UInt32Enum : uint { A = uint.MaxValue } public enum Int64Enum : long { A = long.MaxValue } public enum UInt64Enum : ulong { A = ulong.MaxValue } public static class NonCSharpTypes { private static Type _charEnumType; private static Type _boolEnumType; private static ModuleBuilder GetModuleBuilder() { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly( new AssemblyName("Name"), AssemblyBuilderAccess.RunAndCollect); return assembly.DefineDynamicModule("Name"); } public static Type CharEnumType { get { if (_charEnumType == null) { EnumBuilder eb = GetModuleBuilder().DefineEnum("CharEnumType", TypeAttributes.Public, typeof(char)); eb.DefineLiteral("A", 'A'); eb.DefineLiteral("B", 'B'); eb.DefineLiteral("C", 'C'); _charEnumType = eb.CreateTypeInfo(); } return _charEnumType; } } public static Type BoolEnumType { get { if (_boolEnumType == null) { EnumBuilder eb = GetModuleBuilder().DefineEnum("BoolEnumType", TypeAttributes.Public, typeof(bool)); eb.DefineLiteral("False", false); eb.DefineLiteral("True", true); _boolEnumType = eb.CreateTypeInfo(); } return _boolEnumType; } } } public class FakeExpression : Expression { public FakeExpression(ExpressionType customNodeType, Type customType) { CustomNodeType = customNodeType; CustomType = customType; } public ExpressionType CustomNodeType { get; set; } public Type CustomType { get; set; } public override ExpressionType NodeType => CustomNodeType; public override Type Type => CustomType; } public struct Number : IEquatable<Number> { private readonly int _value; public Number(int value) { _value = value; } public static readonly Number MinValue = new Number(int.MinValue); public static readonly Number MaxValue = new Number(int.MaxValue); public static Number operator +(Number l, Number r) => new Number(unchecked(l._value + r._value)); public static Number operator -(Number l, Number r) => new Number(l._value - r._value); public static Number operator *(Number l, Number r) => new Number(unchecked(l._value * r._value)); public static Number operator /(Number l, Number r) => new Number(l._value / r._value); public static Number operator %(Number l, Number r) => new Number(l._value % r._value); public static Number operator &(Number l, Number r) => new Number(l._value & r._value); public static Number operator |(Number l, Number r) => new Number(l._value | r._value); public static Number operator ^(Number l, Number r) => new Number(l._value ^ r._value); public static bool operator >(Number l, Number r) => l._value > r._value; public static bool operator >=(Number l, Number r) => l._value >= r._value; public static bool operator <(Number l, Number r) => l._value < r._value; public static bool operator <=(Number l, Number r) => l._value <= r._value; public static bool operator ==(Number l, Number r) => l._value == r._value; public static bool operator !=(Number l, Number r) => l._value != r._value; public override bool Equals(object obj) => obj is Number && Equals((Number)obj); public bool Equals(Number other) => _value == other._value; public override int GetHashCode() => _value; } public static class ExpressionAssert { public static void Verify(this LambdaExpression expression, string il, string instructions) { if (LambdaExpression.CanCompileToIL) { expression.VerifyIL(il); } // LambdaExpression.CanCompileToIL is not directly required, // but this functionality relies on private reflection and that would not work with AOT if (LambdaExpression.CanCompileToIL && LambdaExpression.CanInterpret) { expression.VerifyInstructions(instructions); } } } public class RunOnceEnumerable<T> : IEnumerable<T> { private readonly IEnumerable<T> _source; private bool _called; public RunOnceEnumerable(IEnumerable<T> source) { _source = source; } public IEnumerator<T> GetEnumerator() { Assert.False(_called); _called = true; return _source.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } public class Truthiness { private bool Value { get; } public Truthiness(bool value) { Value = value; } public static implicit operator bool(Truthiness truth) => truth.Value; public static bool operator true(Truthiness truth) => truth.Value; public static bool operator false(Truthiness truth) => !truth.Value; public static Truthiness operator !(Truthiness truth) => new Truthiness(!truth.Value); } }
// 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.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Linq.Expressions.Tests { public interface I { void M(); } public class C : IEquatable<C>, I { void I.M() { } public override bool Equals(object o) { return o is C && Equals((C)o); } public bool Equals(C c) { return c != null; } public override int GetHashCode() { return 0; } } public class D : C, IEquatable<D> { public int Val; public string S; public D() { } public D(int val) : this(val, "") { } public D(int val, string s) { Val = val; S = s; } public override bool Equals(object o) { return o is D && Equals((D)o); } public bool Equals(D d) { return d != null && d.Val == Val; } public override int GetHashCode() { return Val; } } public enum E { A = 1, B = 2, Red = 0, Green, Blue } public enum El : long { A, B, C } public enum Eu : uint { Foo, Bar, Baz } public struct S : IEquatable<S> { public override bool Equals(object o) { return (o is S) && Equals((S)o); } public bool Equals(S other) { return true; } public override int GetHashCode() { return 0; } } public struct Sp : IEquatable<Sp> { public Sp(int i, double d) { I = i; D = d; } public int I; public double D; public override bool Equals(object o) { return (o is Sp) && Equals((Sp)o); } public bool Equals(Sp other) { return other.I == I && other.D.Equals(D); } public override int GetHashCode() { return I.GetHashCode() ^ D.GetHashCode(); } } public struct Ss : IEquatable<Ss> { public Ss(S s) { Val = s; } public S Val; public override bool Equals(object o) { return (o is Ss) && Equals((Ss)o); } public bool Equals(Ss other) { return other.Val.Equals(Val); } public override int GetHashCode() { return Val.GetHashCode(); } } public struct Sc : IEquatable<Sc> { public Sc(string s) { S = s; } public string S; public override bool Equals(object o) { return (o is Sc) && Equals((Sc)o); } public bool Equals(Sc other) { return other.S == S; } public override int GetHashCode() { return S.GetHashCode(); } } public struct Scs : IEquatable<Scs> { public Scs(string s, S val) { S = s; Val = val; } public string S; public S Val; public override bool Equals(object o) { return (o is Scs) && Equals((Scs)o); } public bool Equals(Scs other) { return other.S == S && other.Val.Equals(Val); } public override int GetHashCode() { return S.GetHashCode() ^ Val.GetHashCode(); } } public class BaseClass { } public class FC { public int II; public static int SI; public const int CI = 42; public static readonly int RI = 42; } public struct FS { public int II; public static int SI; public const int CI = 42; public static readonly int RI = 42; } public class PC { public int II { get; set; } public static int SI { get; set; } public int this[int i] { get { return 1; } set { } } } public struct PS { public int II { get; set; } public static int SI { get; set; } } internal class CompilationTypes : IEnumerable<object[]> { private static IEnumerable<object[]> Booleans { get { return LambdaExpression.CanCompileToIL ? new[] { new object[] {false}, new object[] {true}, } : new[] { new object[] {true}, }; } } public IEnumerator<object[]> GetEnumerator() => Booleans.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } internal class NoOpVisitor : ExpressionVisitor { internal static readonly NoOpVisitor Instance = new NoOpVisitor(); private NoOpVisitor() { } } public static class Unreadable<T> { public static T WriteOnly { set { } } } public class GenericClass<T> { public void Method() { } public static T Field; public static T Property => Field; } public class NonGenericClass { #pragma warning disable 0067 public event EventHandler Event; #pragma warning restore 0067 public void GenericMethod<T>() { } public static void StaticMethod() { } public static readonly NonGenericClass NonGenericField = new NonGenericClass(); public static NonGenericClass NonGenericProperty => NonGenericField; } public class InvalidTypesData : IEnumerable<object[]> { private static readonly object[] GenericTypeDefinition = new object[] { typeof(GenericClass<>) }; private static readonly object[] ContainsGenericParameters = new object[] { typeof(GenericClass<>).MakeGenericType(typeof(GenericClass<>)) }; public IEnumerator<object[]> GetEnumerator() { yield return GenericTypeDefinition; yield return ContainsGenericParameters; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } public class UnreadableExpressionsData : IEnumerable<object[]> { private static readonly object[] Property = new object[] { Expression.Property(null, typeof(Unreadable<bool>), nameof(Unreadable<bool>.WriteOnly)) }; private static readonly object[] Indexer = new object[] { Expression.Property(null, typeof(Unreadable<bool>).GetProperty(nameof(Unreadable<bool>.WriteOnly)), new Expression[0]) }; public IEnumerator<object[]> GetEnumerator() { yield return Property; yield return Indexer; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class OpenGenericMethodsData : IEnumerable<object[]> { private static readonly object[] GenericClass = new object[] { typeof(GenericClass<>).GetMethod(nameof(GenericClass<string>.Method)) }; private static readonly object[] GenericMethod = new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.GenericMethod)) }; public IEnumerator<object[]> GetEnumerator() { yield return GenericClass; yield return GenericMethod; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public struct ValueTypeWithParameterlessConstructor { public readonly bool ConstructorWasRun; public ValueTypeWithParameterlessConstructor() { ConstructorWasRun = true; } } public struct ValueTypeWithParameterlessConstructorThatThrows { public readonly object Value; public ValueTypeWithParameterlessConstructorThatThrows() { throw new InvalidOperationException(); } public ValueTypeWithParameterlessConstructorThatThrows(object value) { Value = value; } } public enum ByteEnum : byte { A = byte.MaxValue } public enum SByteEnum : sbyte { A = sbyte.MaxValue } public enum Int16Enum : short { A = short.MaxValue } public enum UInt16Enum : ushort { A = ushort.MaxValue } public enum Int32Enum : int { A = int.MaxValue } public enum UInt32Enum : uint { A = uint.MaxValue } public enum Int64Enum : long { A = long.MaxValue } public enum UInt64Enum : ulong { A = ulong.MaxValue } public static class NonCSharpTypes { private static Type _charEnumType; private static Type _boolEnumType; private static ModuleBuilder GetModuleBuilder() { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly( new AssemblyName("Name"), AssemblyBuilderAccess.RunAndCollect); return assembly.DefineDynamicModule("Name"); } public static Type CharEnumType { get { if (_charEnumType == null) { EnumBuilder eb = GetModuleBuilder().DefineEnum("CharEnumType", TypeAttributes.Public, typeof(char)); eb.DefineLiteral("A", 'A'); eb.DefineLiteral("B", 'B'); eb.DefineLiteral("C", 'C'); _charEnumType = eb.CreateTypeInfo(); } return _charEnumType; } } public static Type BoolEnumType { get { if (_boolEnumType == null) { EnumBuilder eb = GetModuleBuilder().DefineEnum("BoolEnumType", TypeAttributes.Public, typeof(bool)); eb.DefineLiteral("False", false); eb.DefineLiteral("True", true); _boolEnumType = eb.CreateTypeInfo(); } return _boolEnumType; } } } public class FakeExpression : Expression { public FakeExpression(ExpressionType customNodeType, Type customType) { CustomNodeType = customNodeType; CustomType = customType; } public ExpressionType CustomNodeType { get; set; } public Type CustomType { get; set; } public override ExpressionType NodeType => CustomNodeType; public override Type Type => CustomType; } public struct Number : IEquatable<Number> { private readonly int _value; public Number(int value) { _value = value; } public static readonly Number MinValue = new Number(int.MinValue); public static readonly Number MaxValue = new Number(int.MaxValue); public static Number operator +(Number l, Number r) => new Number(unchecked(l._value + r._value)); public static Number operator -(Number l, Number r) => new Number(l._value - r._value); public static Number operator *(Number l, Number r) => new Number(unchecked(l._value * r._value)); public static Number operator /(Number l, Number r) => new Number(l._value / r._value); public static Number operator %(Number l, Number r) => new Number(l._value % r._value); public static Number operator &(Number l, Number r) => new Number(l._value & r._value); public static Number operator |(Number l, Number r) => new Number(l._value | r._value); public static Number operator ^(Number l, Number r) => new Number(l._value ^ r._value); public static bool operator >(Number l, Number r) => l._value > r._value; public static bool operator >=(Number l, Number r) => l._value >= r._value; public static bool operator <(Number l, Number r) => l._value < r._value; public static bool operator <=(Number l, Number r) => l._value <= r._value; public static bool operator ==(Number l, Number r) => l._value == r._value; public static bool operator !=(Number l, Number r) => l._value != r._value; public override bool Equals(object obj) => obj is Number && Equals((Number)obj); public bool Equals(Number other) => _value == other._value; public override int GetHashCode() => _value; } public static class ExpressionAssert { public static void Verify(this LambdaExpression expression, string il, string instructions) { if (LambdaExpression.CanCompileToIL) { expression.VerifyIL(il); } // LambdaExpression.CanCompileToIL is not directly required, // but this functionality relies on private reflection and that would not work with AOT if (LambdaExpression.CanCompileToIL && LambdaExpression.CanInterpret) { expression.VerifyInstructions(instructions); } } } public class RunOnceEnumerable<T> : IEnumerable<T> { private readonly IEnumerable<T> _source; private bool _called; public RunOnceEnumerable(IEnumerable<T> source) { _source = source; } public IEnumerator<T> GetEnumerator() { Assert.False(_called); _called = true; return _source.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } public class Truthiness { private bool Value { get; } public Truthiness(bool value) { Value = value; } public static implicit operator bool(Truthiness truth) => truth.Value; public static bool operator true(Truthiness truth) => truth.Value; public static bool operator false(Truthiness truth) => !truth.Value; public static Truthiness operator !(Truthiness truth) => new Truthiness(!truth.Value); } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Methodical/int64/unsigned/ldc_mul_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="ldc_mul.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="ldc_mul.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/reflection/Tier1Collectible/Tier1Collectible.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/mono/mono/mini/generics.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; #if __MOBILE__ class GenericsTests #else class Tests #endif { struct TestStruct { public int i; public int j; public TestStruct (int i, int j) { this.i = i; this.j = j; } } #if !__MOBILE__ class Enumerator <T> : MyIEnumerator <T> { T MyIEnumerator<T>.Current { get { return default(T); } } bool MyIEnumerator<T>.MoveNext () { return true; } } class Comparer <T> : IComparer <T> { bool IComparer<T>.Compare (T x, T y) { return true; } } #endif #if !__MOBILE__ static int Main (string[] args) { return TestDriver.RunTests (typeof (Tests), args); } #endif public static int test_1_nullable_unbox () { return Unbox<int?> (1).Value; } public static int test_1_nullable_unbox_null () { return Unbox<int?> (null).HasValue ? 0 : 1; } public static int test_1_nullable_box () { return (int) Box<int?> (1); } public static int test_1_nullable_box_null () { return Box<int?> (null) == null ? 1 : 0; } public static int test_1_isinst_nullable () { object o = 1; return (o is int?) ? 1 : 0; } public static int test_1_nullable_unbox_vtype () { return Unbox<TestStruct?> (new TestStruct (1, 2)).Value.i; } public static int test_1_nullable_unbox_null_vtype () { return Unbox<TestStruct?> (null).HasValue ? 0 : 1; } public static int test_1_nullable_box_vtype () { return ((TestStruct)(Box<TestStruct?> (new TestStruct (1, 2)))).i; } public static int test_1_nullable_box_null_vtype () { return Box<TestStruct?> (null) == null ? 1 : 0; } public static int test_1_isinst_nullable_vtype () { object o = new TestStruct (1, 2); return (o is TestStruct?) ? 1 : 0; } public static int test_0_nullable_normal_unbox () { int? i = 5; object o = i; // This uses unbox instead of unbox_any int? j = (int?)o; if (j != 5) return 1; return 0; } public static void stelem_any<T> (T[] arr, T elem) { arr [0] = elem; } public static T ldelem_any<T> (T[] arr) { return arr [0]; } public static int test_1_ldelem_stelem_any_int () { int[] arr = new int [3]; stelem_any (arr, 1); return ldelem_any (arr); } public static int test_1_ldelem_stelem_any_single () { float[] arr = new float [3]; stelem_any (arr, 1); return (int) ldelem_any (arr); } public static int test_1_ldelem_stelem_any_double () { double[] arr = new double [3]; stelem_any (arr, 1); return (int) ldelem_any (arr); } public static T return_ref<T> (ref T t) { return t; } public static T ldelema_any<T> (T[] arr) { return return_ref<T> (ref arr [0]); } public static int test_0_ldelema () { string[] arr = new string [1]; arr [0] = "Hello"; if (ldelema_any <string> (arr) == "Hello") return 0; else return 1; } public static T[,] newarr_multi<T> () { return new T [1, 1]; } public static int test_0_newarr_multi_dim () { return newarr_multi<string> ().GetType () == typeof (string[,]) ? 0 : 1; } interface ITest { void Foo<T> (); } public static int test_0_iface_call_null_bug_77442 () { ITest test = null; try { test.Foo<int> (); } catch (NullReferenceException) { return 0; } return 1; } public static int test_18_ldobj_stobj_generics () { GenericClass<int> t = new GenericClass <int> (); int i = 5; int j = 6; return t.ldobj_stobj (ref i, ref j) + i + j; } public static int test_5_ldelem_stelem_generics () { GenericClass<TestStruct> t = new GenericClass<TestStruct> (); TestStruct s = new TestStruct (5, 5); return t.ldelem_stelem (s).i; } public static int test_0_constrained_vtype_box () { GenericClass<TestStruct> t = new GenericClass<TestStruct> (); #if __MOBILE__ return t.toString (new TestStruct ()) == "GenericsTests+TestStruct" ? 0 : 1; #else return t.toString (new TestStruct ()) == "Tests+TestStruct" ? 0 : 1; #endif } public static int test_0_constrained_vtype () { GenericClass<int> t = new GenericClass<int> (); return t.toString (1234) == "1234" ? 0 : 1; } public static int test_0_constrained_reftype () { GenericClass<String> t = new GenericClass<String> (); return t.toString ("1234") == "1234" ? 0 : 1; } public static int test_0_box_brtrue_optimizations () { if (IsNull<int>(5)) return 1; if (!IsNull<object>(null)) return 1; return 0; } [Category ("!FULLAOT")] public static int test_0_generic_get_value_optimization_int () { int[] x = new int[] {100, 200}; if (GenericClass<int>.Z (x, 0) != 100) return 2; if (GenericClass<int>.Z (x, 1) != 200) return 3; return 0; } interface NonGenericInterface { int return_field (); } interface GenericInterface<T> : NonGenericInterface { T not_used (); } struct ImplementGenericInterface<T> : GenericInterface<T> { public Object padding1; public Object padding2; public Object padding3; public T[] arr_t; public ImplementGenericInterface (T[] arr_t) { this.padding1 = null; this.padding2 = null; this.padding3 = null; this.arr_t = arr_t; } public T not_used () { return arr_t [0]; } public int return_field () { return arr_t.Length; } } public static int test_8_struct_implements_generic_interface () { int[] arr = {1, 2, 3, 4}; NonGenericInterface s = new ImplementGenericInterface<int> (arr); return s.return_field () + s.return_field (); } public static int test_0_generic_get_value_optimization_vtype () { TestStruct[] arr = new TestStruct[] { new TestStruct (100, 200), new TestStruct (300, 400) }; IEnumerator<TestStruct> enumerator = GenericClass<TestStruct>.Y (arr); TestStruct s; int sum = 0; while (enumerator.MoveNext ()) { s = enumerator.Current; sum += s.i + s.j; } if (sum != 1000) return 1; s = GenericClass<TestStruct>.Z (arr, 0); if (s.i != 100 || s.j != 200) return 2; s = GenericClass<TestStruct>.Z (arr, 1); if (s.i != 300 || s.j != 400) return 3; return 0; } public static int test_0_nullable_ldflda () { return GenericClass<string>.BIsAClazz == false ? 0 : 1; } public struct GenericStruct<T> { public T t; public GenericStruct (T t) { this.t = t; } } public class GenericClass<T> { public T t; public GenericClass (T t) { this.t = t; } public GenericClass () { } public T ldobj_stobj (ref T t1, ref T t2) { t1 = t2; T t = t1; return t; } public T ldelem_stelem (T t) { T[] arr = new T [10]; arr [0] = t; return arr [0]; } public String toString (T t) { return t.ToString (); } public static IEnumerator<T> Y (IEnumerable <T> x) { return x.GetEnumerator (); } public static T Z (IList<T> x, int index) { return x [index]; } protected static T NullB = default(T); private static Nullable<bool> _BIsA = null; public static bool BIsAClazz { get { _BIsA = false; return _BIsA.Value; } } } public class MRO : MarshalByRefObject { public GenericStruct<int> struct_field; public GenericClass<int> class_field; } public class MRO<T> : MarshalByRefObject { public T gen_field; public T stfld_ldfld (T t) { var m = this; m.gen_field = t; return m.gen_field; } } public static int test_0_ldfld_stfld_mro () { MRO m = new MRO (); GenericStruct<int> s = new GenericStruct<int> (5); // This generates stfld m.struct_field = s; // This generates ldflda if (m.struct_field.t != 5) return 1; // This generates ldfld GenericStruct<int> s2 = m.struct_field; if (s2.t != 5) return 2; if (m.struct_field.t != 5) return 3; m.class_field = new GenericClass<int> (5); if (m.class_field.t != 5) return 4; // gshared var m2 = new MRO<string> (); if (m2.stfld_ldfld ("A") != "A") return 5; return 0; } // FIXME: [Category ("!FULLAOT")] public static int test_0_generic_virtual_call_on_vtype_unbox () { object o = new Object (); IFoo h = new Handler(o); if (h.Bar<object> () != o) return 1; else return 0; } public static int test_0_box_brtrue_opt () { Foo<int> f = new Foo<int> (5); f [123] = 5; return 0; } public static int test_0_box_brtrue_opt_regress_81102 () { if (new Foo<int>(5).ToString () == "null") return 0; else return 1; } struct S { public int i; } public static int test_0_ldloca_initobj_opt () { if (new Foo<S> (new S ()).get_default ().i != 0) return 1; if (new Foo<object> (null).get_default () != null) return 2; return 0; } #if !__MOBILE__ public static int test_0_variance_reflection () { // covariance on IEnumerator if (!typeof (MyIEnumerator<object>).IsAssignableFrom (typeof (MyIEnumerator<string>))) return 1; // covariance on IEnumerator and covariance on arrays if (!typeof (MyIEnumerator<object>[]).IsAssignableFrom (typeof (MyIEnumerator<string>[]))) return 2; // covariance and implemented interfaces if (!typeof (MyIEnumerator<object>).IsAssignableFrom (typeof (Enumerator<string>))) return 3; // contravariance on IComparer if (!typeof (IComparer<string>).IsAssignableFrom (typeof (IComparer<object>))) return 4; // contravariance on IComparer, contravariance on arrays if (!typeof (IComparer<string>[]).IsAssignableFrom (typeof (IComparer<object>[]))) return 5; // contravariance and interface inheritance if (!typeof (IComparer<string>[]).IsAssignableFrom (typeof (IKeyComparer<object>[]))) return 6; return 0; } #endif public static int test_0_ldvirtftn_generic_method () { new GenericsTests ().ldvirtftn<string> (); return the_type == typeof (string) ? 0 : 1; } public static int test_0_throw_dead_this () { new Foo<string> ("").throw_dead_this (); return 0; } struct S<T> {} public static int test_0_inline_infinite_polymorphic_recursion () { f<int>(0); return 0; } private static void f<T>(int i) { if(i==42) f<S<T>>(i); } // This cannot be made to work with full-aot, since there it is impossible to // statically determine that Foo<string>.Bar <int> is needed, the code only // references IFoo.Bar<int> [Category ("!FULLAOT")] public static int test_0_generic_virtual_on_interfaces () { Foo<string>.count1 = 0; Foo<string>.count2 = 0; Foo<string>.count3 = 0; IFoo f = new Foo<string> (""); for (int i = 0; i < 1000; ++i) { f.Bar <int> (); f.Bar <string> (); f.NonGeneric (); } if (Foo<string>.count1 != 1000) return 1; if (Foo<string>.count2 != 1000) return 2; if (Foo<string>.count3 != 1000) return 3; VirtualInterfaceCallFromGenericMethod<long> (f); return 0; } public static int test_0_generic_virtual_on_interfaces_ref () { Foo<string>.count1 = 0; Foo<string>.count2 = 0; Foo<string>.count3 = 0; Foo<string>.count4 = 0; IFoo f = new Foo<string> (""); for (int i = 0; i < 1000; ++i) { f.Bar <string> (); f.Bar <object> (); f.NonGeneric (); } if (Foo<string>.count2 != 1000) return 2; if (Foo<string>.count3 != 1000) return 3; if (Foo<string>.count4 != 1000) return 4; return 0; } //repro for #505375 [Category ("!FULLAOT")] public static int test_2_cprop_bug () { int idx = 0; int a = 1; var cmp = System.Collections.Generic.Comparer<int>.Default ; if (cmp.Compare (a, 0) > 0) a = 0; do { idx++; } while (cmp.Compare (idx - 1, a) == 0); return idx; } enum MyEnumUlong : ulong { Value_2 = 2 } public static int test_0_regress_550964_constrained_enum_long () { MyEnumUlong a = MyEnumUlong.Value_2; MyEnumUlong b = MyEnumUlong.Value_2; return Pan (a, b) ? 0 : 1; } static bool Pan<T> (T a, T b) { return a.Equals (b); } public class XElement { public string Value { get; set; } } public static int test_0_fullaot_linq () { var allWords = new XElement [] { new XElement { Value = "one" } }; var filteredWords = allWords.Where(kw => kw.Value.StartsWith("T")); return filteredWords.Count (); } public static int test_0_fullaot_comparer_t () { var l = new SortedList <TimeSpan, int> (); return l.Count; } public static int test_0_fullaot_comparer_t_2 () { var l = new Dictionary <TimeSpan, int> (); return l.Count; } static void enumerate<T> (IEnumerable<T> arr) { foreach (var o in arr) ; int c = ((ICollection<T>)arr).Count; } /* Test that treating arrays as generic collections works with full-aot */ public static int test_0_fullaot_array_wrappers () { GenericsTests[] arr = new GenericsTests [10]; enumerate<GenericsTests> (arr); return 0; } static int cctor_count = 0; public abstract class Beta<TChanged> { static Beta() { cctor_count ++; } } public class Gamma<T> : Beta<T> { static Gamma() { } } // #519336 public static int test_2_generic_class_init_gshared_ctor () { new Gamma<object>(); new Gamma<string>(); return cctor_count; } static int cctor_count2 = 0; class ServiceController<T> { static ServiceController () { cctor_count2 ++; } public ServiceController () { } } static ServiceController<T> Create<T>() { return new ServiceController<T>(); } // #631409 public static int test_2_generic_class_init_gshared_ctor_from_gshared () { Create<object> (); Create<string> (); return cctor_count2; } public static Type get_type<T> () { return typeof (T); } public static int test_0_gshared_delegate_rgctx () { Func<Type> t = new Func<Type> (get_type<string>); if (t () == typeof (string)) return 0; else return 1; } // Creating a delegate from a generic method from gshared code public static int test_0_gshared_delegate_from_gshared () { if (gshared_delegate_from_gshared <object> () != 0) return 1; if (gshared_delegate_from_gshared <string> () != 0) return 2; return 0; } public static int gshared_delegate_from_gshared <T> () { Func<Type> t = new Func<Type> (get_type<T>); return t () == typeof (T) ? 0 : 1; } public static int test_0_marshalbyref_call_from_gshared_virt_elim () { /* Calling a virtual method from gshared code which is changed to a nonvirt call */ Class1<object> o = new Class1<object> (); o.Do (new Class2<object> ()); return 0; } class Pair<TKey, TValue> { public static KeyValuePair<TKey, TValue> make_pair (TKey key, TValue value) { return new KeyValuePair<TKey, TValue> (key, value); } public delegate TRet Transform<TRet> (TKey key, TValue value); } public static int test_0_bug_620864 () { var d = new Pair<string, Type>.Transform<KeyValuePair<string, Type>> (Pair<string, Type>.make_pair); var p = d ("FOO", typeof (int)); if (p.Key != "FOO" || p.Value != typeof (int)) return 1; return 0; } struct RecStruct<T> { public void foo (RecStruct<RecStruct<T>> baz) { } } public static int test_0_infinite_generic_recursion () { // Check that the AOT compile can deal with infinite generic recursion through // parameter types RecStruct<int> bla; return 0; } struct FooStruct { } bool IsNull2 <T> (object value) where T : struct { T? item = (T?) value; if (item.HasValue) return false; return true; } public static int test_0_full_aot_nullable_unbox_from_gshared_code () { if (!new GenericsTests ().IsNull2<FooStruct> (null)) return 1; if (new GenericsTests ().IsNull2<FooStruct> (new FooStruct ())) return 2; return 0; } public static int test_0_partial_sharing () { if (PartialShared1 (new List<string> (), 1) != typeof (string)) return 1; if (PartialShared1 (new List<GenericsTests> (), 1) != typeof (GenericsTests)) return 2; if (PartialShared2 (new List<string> (), 1) != typeof (int)) return 3; if (PartialShared2 (new List<GenericsTests> (), 1) != typeof (int)) return 4; return 0; } [Category ("GSHAREDVT")] public static int test_6_partial_sharing_linq () { var messages = new List<Message> (); messages.Add (new Message () { MessageID = 5 }); messages.Add (new Message () { MessageID = 6 }); return messages.Max(i => i.MessageID); } public static int test_0_partial_shared_method_in_nonshared_class () { var c = new Class1<double> (); return (c.Foo<string> (5).GetType () == typeof (Class1<string>)) ? 0 : 1; } class Message { public int MessageID { get; set; } } public static Type PartialShared1<T, K> (List<T> list, K k) { return typeof (T); } public static Type PartialShared2<T, K> (List<T> list, K k) { return typeof (K); } public class Class1<T> { public virtual void Do (Class2<T> t) { t.Foo (); } public virtual object Foo<U> (T t) { return new Class1<U> (); } } public interface IFace1<T> { void Foo (); } public class Class2<T> : MarshalByRefObject, IFace1<T> { public void Foo () { } } public static void VirtualInterfaceCallFromGenericMethod <T> (IFoo f) { f.Bar <T> (); } public static Type the_type; public void ldvirtftn<T> () { Foo <T> binding = new Foo <T> (default (T)); binding.GenericEvent += event_handler; binding.fire (); } public virtual void event_handler<T> (Foo<T> sender) { the_type = typeof (T); } public interface IFoo { void NonGeneric (); object Bar<T>(); } public class Foo<T1> : IFoo { public Foo(T1 t1) { m_t1 = t1; } public override string ToString() { return Bar(m_t1 == null ? "null" : "null"); } public String Bar (String s) { return s; } public int this [T1 key] { set { if (key == null) throw new ArgumentNullException ("key"); } } public void throw_dead_this () { try { new SomeClass().ThrowAnException(); } catch { } } public T1 get_default () { return default (T1); } readonly T1 m_t1; public delegate void GenericEventHandler (Foo<T1> sender); public event GenericEventHandler GenericEvent; public void fire () { GenericEvent (this); } public static int count1, count2, count3, count4; public void NonGeneric () { count3 ++; } public object Bar <T> () { if (typeof (T) == typeof (int)) count1 ++; else if (typeof (T) == typeof (string)) count2 ++; else if (typeof (T) == typeof (object)) count4 ++; return null; } } public class SomeClass { public void ThrowAnException() { throw new Exception ("Something went wrong"); } } struct Handler : IFoo { object o; public Handler(object o) { this.o = o; } public void NonGeneric () { } public object Bar<T>() { return o; } } static bool IsNull<T> (T t) { if (t == null) return true; else return false; } static object Box<T> (T t) { return t; } static T Unbox <T> (object o) { return (T) o; } interface IDefaultRetriever { T GetDefault<T>(); } class DefaultRetriever : IDefaultRetriever { [MethodImpl(MethodImplOptions.Synchronized)] public T GetDefault<T>() { return default(T); } } [Category ("!FULLAOT")] [Category ("!BITCODE")] public static int test_0_regress_668095_synchronized_gshared () { return DoSomething (new DefaultRetriever ()); } static int DoSomething(IDefaultRetriever foo) { int result = foo.GetDefault<int>(); return result; } class SyncClass<T> { [MethodImpl(MethodImplOptions.Synchronized)] public Type getInstance() { return typeof (T); } } [Category ("GSHAREDVT")] static int test_0_synchronized_gshared () { var c = new SyncClass<string> (); if (c.getInstance () != typeof (string)) return 1; return 0; } class Response { } public static int test_0_687865_isinst_with_cache_wrapper () { object o = new object (); if (o is Action<IEnumerable<Response>>) return 1; else return 0; } enum DocType { One, Two, Three } class Doc { public string Name { get; set; } public DocType Type { get; set; } } // #2155 [Category ("GSHAREDVT")] public static int test_0_fullaot_sflda_cctor () { List<Doc> documents = new List<Doc>(); documents.Add(new Doc { Name = "Doc1", Type = DocType.One } ); documents.Add(new Doc { Name = "Doc2", Type = DocType.Two } ); documents.Add(new Doc { Name = "Doc3", Type = DocType.Three } ); documents.Add(new Doc { Name = "Doc4", Type = DocType.One } ); documents.Add(new Doc { Name = "Doc5", Type = DocType.Two } ); documents.Add(new Doc { Name = "Doc6", Type = DocType.Three } ); documents.Add(new Doc { Name = "Doc7", Type = DocType.One } ); documents.Add(new Doc { Name = "Doc8", Type = DocType.Two } ); documents.Add(new Doc { Name = "Doc9", Type = DocType.Three } ); List<DocType> categories = documents.Select(d=>d.Type).Distinct().ToList<DocType>().OrderBy(d => d).ToList(); foreach(DocType cat in categories) { List<Doc> catDocs = documents.Where(d => d.Type == cat).OrderBy(d => d.Name).ToList<Doc>(); } return 0; } class A { } static List<A> sources = new List<A>(); // #6112 public static int test_0_fullaot_imt () { sources.Add(null); sources.Add(null); int a = sources.Count; var enumerator = sources.GetEnumerator() as IEnumerator<object>; while (enumerator.MoveNext()) { object o = enumerator.Current; } return 0; } class AClass { } class BClass : AClass { } public static int test_0_fullaot_variant_iface () { var arr = new BClass [10]; var enumerable = (IEnumerable<AClass>)arr; enumerable.GetEnumerator (); return 0; } struct Record : Foo2<Record>.IRecord { int counter; int Foo2<Record>.IRecord.DoSomething () { return counter++; } } class Foo2<T> where T : Foo2<T>.IRecord { public interface IRecord { int DoSomething (); } public static int Extract (T[] t) { return t[0].DoSomething (); } } class Foo3<T> where T : IComparable { public static int CompareTo (T[] t) { // This is a constrained call to Enum.CompareTo () return t[0].CompareTo (t [0]); } } public static int test_1_regress_constrained_iface_call_7571 () { var r = new Record [10]; Foo2<Record>.Extract (r); return Foo2<Record>.Extract (r); } enum ConstrainedEnum { Val = 1 } public static int test_0_regress_constrained_iface_call_enum () { var r = new ConstrainedEnum [10]; return Foo3<ConstrainedEnum>.CompareTo (r); } public interface IFoo2 { void MoveNext (); } public struct Foo2 : IFoo2 { public void MoveNext () { } } public static Action Dingus (ref Foo2 f) { return new Action (f.MoveNext); } public static int test_0_delegate_unbox_full_aot () { Foo2 foo = new Foo2 (); Dingus (ref foo) (); return 0; } public static int test_0_arrays_ireadonly () { int[] arr = new int [10]; for (int i = 0; i < 10; ++i) arr [i] = i; IReadOnlyList<int> a = (IReadOnlyList<int>)(object)arr; if (a.Count != 10) return 1; if (a [0] != 0) return 2; if (a [1] != 1) return 3; return 0; } public static int test_0_volatile_read_write () { string foo = "ABC"; Volatile.Write (ref foo, "DEF"); return Volatile.Read (ref foo) == "DEF" ? 0 : 1; } // FIXME: Doesn't work with --regression as Interlocked.Add(ref long) is only implemented as an intrinsic #if FALSE public static async Task<T> FooAsync<T> (int i, int j) { Task<int> t = new Task<int> (delegate () { Console.WriteLine ("HIT!"); return 0; }); var response = await t; return default(T); } public static int test_0_fullaot_generic_async () { Task<string> t = FooAsync<string> (1, 2); t.RunSynchronously (); return 0; } #endif public static int test_0_delegate_callvirt_fullaot () { Func<string> f = delegate () { return "A"; }; var f2 = (Func<Func<string>, string>)Delegate.CreateDelegate (typeof (Func<Func<string>, string>), null, f.GetType ().GetMethod ("Invoke")); var s = f2 (f); return s == "A" ? 0 : 1; } public interface ICovariant<out R> { } // Deleting the `out` modifier from this line stop the problem public interface IExtCovariant<out R> : ICovariant<R> { } public class Sample<R> : ICovariant<R> { } public interface IMyInterface { } public static int test_0_variant_cast_cache () { object covariant = new Sample<IMyInterface>(); var foo = (ICovariant<IMyInterface>)(covariant); try { var extCovariant = (IExtCovariant<IMyInterface>)covariant; return 1; } catch { return 0; } } struct FooStruct2 { public int a1, a2, a3; } class MyClass<T> where T: struct { [MethodImplAttribute (MethodImplOptions.NoInlining)] public MyClass(int a1, int a2, int a3, int a4, int a5, int a6, Nullable<T> a) { } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static MyClass<T> foo () { Nullable<T> a = new Nullable<T> (); return new MyClass<T> (0, 0, 0, 0, 0, 0, a); } } public static int test_0_newobj_generic_context () { MyClass<FooStruct2>.foo (); return 0; } enum AnEnum { A, B } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static string constrained_tostring<T> (T t) { return t.ToString (); } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static bool constrained_equals<T> (T t1, T t2) { var c = EqualityComparer<T>.Default; return c.Equals (t1, t2); } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static int constrained_gethashcode<T> (T t) { return t.GetHashCode (); } public static int test_0_constrained_partial_sharing () { string s; s = constrained_tostring<int> (5); if (s != "5") return 1; s = constrained_tostring<AnEnum> (AnEnum.B); if (s != "B") return 2; if (!constrained_equals<int> (1, 1)) return 3; if (constrained_equals<int> (1, 2)) return 4; if (!constrained_equals<AnEnum> (AnEnum.A, AnEnum.A)) return 5; if (constrained_equals<AnEnum> (AnEnum.A, AnEnum.B)) return 6; int i = constrained_gethashcode<int> (5); if (i != 5) return 7; i = constrained_gethashcode<AnEnum> (AnEnum.B); if (i != 1) return 8; return 0; } enum Enum1 { A, B } enum Enum2 { A, B } public static int test_0_partial_sharing_ginst () { var l1 = new List<KeyValuePair<int, Enum1>> (); l1.Add (new KeyValuePair<int, Enum1>(5, Enum1.A)); if (l1 [0].Key != 5) return 1; if (l1 [0].Value != Enum1.A) return 2; var l2 = new List<KeyValuePair<int, Enum2>> (); l2.Add (new KeyValuePair<int, Enum2>(5, Enum2.B)); if (l2 [0].Key != 5) return 3; if (l2 [0].Value != Enum2.B) return 4; return 0; } static object delegate_8_args_res; public static int test_0_delegate_8_args () { delegate_8_args_res = null; Action<string, string, string, string, string, string, string, string> test = (a, b, c, d, e, f, g, h) => { delegate_8_args_res = h; }; test("a", "b", "c", "d", "e", "f", "g", "h"); return delegate_8_args_res == "h" ? 0 : 1; } static void throw_catch_t<T> () where T: Exception { try { throw new NotSupportedException (); } catch (T) { } } public static int test_0_gshared_catch_open_type () { throw_catch_t<NotSupportedException> (); return 0; } class ThrowClass<T> where T: Exception { public void throw_catch_t () { try { throw new NotSupportedException (); } catch (T) { } } } public static int test_0_gshared_catch_open_type_instance () { var c = new ThrowClass<NotSupportedException> (); c.throw_catch_t (); return 0; } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static bool is_ref_or_contains_refs<T> () { return RuntimeHelpers.IsReferenceOrContainsReferences<T> (); } class IsRefClass<T> { [MethodImplAttribute (MethodImplOptions.NoInlining)] public bool is_ref () { return RuntimeHelpers.IsReferenceOrContainsReferences<T> (); } } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static bool is_ref_or_contains_refs_gen_ref<T> () { return RuntimeHelpers.IsReferenceOrContainsReferences<GenStruct<T>> (); } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static bool is_ref_or_contains_refs_gen_noref<T> () { return RuntimeHelpers.IsReferenceOrContainsReferences<NoRefGenStruct<T>> (); } struct GenStruct<T> { T t; } struct NoRefGenStruct<T> { } struct RefStruct { string s; } struct NestedRefStruct { RefStruct r; } struct NoRefStruct { int i; } struct AStruct3<T1, T2, T3> { T1 t1; T2 t2; T3 t3; } public static int test_0_isreference_intrins () { if (RuntimeHelpers.IsReferenceOrContainsReferences<int> ()) return 1; if (!RuntimeHelpers.IsReferenceOrContainsReferences<string> ()) return 2; if (!RuntimeHelpers.IsReferenceOrContainsReferences<RefStruct> ()) return 3; if (!RuntimeHelpers.IsReferenceOrContainsReferences<NestedRefStruct> ()) return 4; if (RuntimeHelpers.IsReferenceOrContainsReferences<NoRefStruct> ()) return 5; // Generic code if (is_ref_or_contains_refs<int> ()) return 6; // Shared code if (!is_ref_or_contains_refs<string> ()) return 7; // Complex type from shared code if (!is_ref_or_contains_refs_gen_ref<string> ()) return 8; if (is_ref_or_contains_refs_gen_ref<int> ()) return 9; if (is_ref_or_contains_refs_gen_noref<string> ()) return 10; // Complex type from shared class method var c1 = new IsRefClass<AStruct3<int, int, int>> (); if (c1.is_ref ()) return 11; var c2 = new IsRefClass<AStruct3<string, int, int>> (); if (!c2.is_ref ()) return 12; return 0; } class LdobjStobj { public int counter; public LdobjStobj buffer1; public LdobjStobj buffer2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void swap<T>(ref T first, ref T second) { second = first; } public static int test_42_ldobj_stobj_ref () { var obj = new LdobjStobj (); obj.counter = 42; swap (ref obj.buffer1, ref obj.buffer2); return obj.counter; } public interface ICompletion { Type UnsafeOnCompleted (); } public struct TaskAwaiter<T> : ICompletion { public Type UnsafeOnCompleted () { typeof(T).GetHashCode (); return typeof(T); } } public struct AStruct { public Type Caller<TAwaiter>(ref TAwaiter awaiter) where TAwaiter : ICompletion { return awaiter.UnsafeOnCompleted(); } } public static int test_0_partial_constrained_call_llvmonly () { var builder = new AStruct (); var awaiter = new TaskAwaiter<bool> (); var res = builder.Caller (ref awaiter); return res == typeof (bool) ? 0 : 1; } struct OneThing<T1> { public T1 Item1; } [MethodImpl (MethodImplOptions.NoInlining)] static T FromResult<T> (T result) { return result; } public static int test_42_llvm_gsharedvt_small_vtype_in_regs () { var t = FromResult<OneThing<int>>(new OneThing<int> {Item1 = 42}); return t.Item1; } class ThreadLocalClass<T> { [ThreadStatic] static T v; public T Value { [MethodImpl (MethodImplOptions.NoInlining)] get { return v; } [MethodImpl (MethodImplOptions.NoInlining)] set { v = value; } } } public static int test_0_tls_gshared () { var c = new ThreadLocalClass<string> (); c.Value = "FOO"; return c.Value == "FOO" ? 0 : 1; } } #if !__MOBILE__ class GenericsTests : Tests { } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; #if __MOBILE__ class GenericsTests #else class Tests #endif { struct TestStruct { public int i; public int j; public TestStruct (int i, int j) { this.i = i; this.j = j; } } #if !__MOBILE__ class Enumerator <T> : MyIEnumerator <T> { T MyIEnumerator<T>.Current { get { return default(T); } } bool MyIEnumerator<T>.MoveNext () { return true; } } class Comparer <T> : IComparer <T> { bool IComparer<T>.Compare (T x, T y) { return true; } } #endif #if !__MOBILE__ static int Main (string[] args) { return TestDriver.RunTests (typeof (Tests), args); } #endif public static int test_1_nullable_unbox () { return Unbox<int?> (1).Value; } public static int test_1_nullable_unbox_null () { return Unbox<int?> (null).HasValue ? 0 : 1; } public static int test_1_nullable_box () { return (int) Box<int?> (1); } public static int test_1_nullable_box_null () { return Box<int?> (null) == null ? 1 : 0; } public static int test_1_isinst_nullable () { object o = 1; return (o is int?) ? 1 : 0; } public static int test_1_nullable_unbox_vtype () { return Unbox<TestStruct?> (new TestStruct (1, 2)).Value.i; } public static int test_1_nullable_unbox_null_vtype () { return Unbox<TestStruct?> (null).HasValue ? 0 : 1; } public static int test_1_nullable_box_vtype () { return ((TestStruct)(Box<TestStruct?> (new TestStruct (1, 2)))).i; } public static int test_1_nullable_box_null_vtype () { return Box<TestStruct?> (null) == null ? 1 : 0; } public static int test_1_isinst_nullable_vtype () { object o = new TestStruct (1, 2); return (o is TestStruct?) ? 1 : 0; } public static int test_0_nullable_normal_unbox () { int? i = 5; object o = i; // This uses unbox instead of unbox_any int? j = (int?)o; if (j != 5) return 1; return 0; } public static void stelem_any<T> (T[] arr, T elem) { arr [0] = elem; } public static T ldelem_any<T> (T[] arr) { return arr [0]; } public static int test_1_ldelem_stelem_any_int () { int[] arr = new int [3]; stelem_any (arr, 1); return ldelem_any (arr); } public static int test_1_ldelem_stelem_any_single () { float[] arr = new float [3]; stelem_any (arr, 1); return (int) ldelem_any (arr); } public static int test_1_ldelem_stelem_any_double () { double[] arr = new double [3]; stelem_any (arr, 1); return (int) ldelem_any (arr); } public static T return_ref<T> (ref T t) { return t; } public static T ldelema_any<T> (T[] arr) { return return_ref<T> (ref arr [0]); } public static int test_0_ldelema () { string[] arr = new string [1]; arr [0] = "Hello"; if (ldelema_any <string> (arr) == "Hello") return 0; else return 1; } public static T[,] newarr_multi<T> () { return new T [1, 1]; } public static int test_0_newarr_multi_dim () { return newarr_multi<string> ().GetType () == typeof (string[,]) ? 0 : 1; } interface ITest { void Foo<T> (); } public static int test_0_iface_call_null_bug_77442 () { ITest test = null; try { test.Foo<int> (); } catch (NullReferenceException) { return 0; } return 1; } public static int test_18_ldobj_stobj_generics () { GenericClass<int> t = new GenericClass <int> (); int i = 5; int j = 6; return t.ldobj_stobj (ref i, ref j) + i + j; } public static int test_5_ldelem_stelem_generics () { GenericClass<TestStruct> t = new GenericClass<TestStruct> (); TestStruct s = new TestStruct (5, 5); return t.ldelem_stelem (s).i; } public static int test_0_constrained_vtype_box () { GenericClass<TestStruct> t = new GenericClass<TestStruct> (); #if __MOBILE__ return t.toString (new TestStruct ()) == "GenericsTests+TestStruct" ? 0 : 1; #else return t.toString (new TestStruct ()) == "Tests+TestStruct" ? 0 : 1; #endif } public static int test_0_constrained_vtype () { GenericClass<int> t = new GenericClass<int> (); return t.toString (1234) == "1234" ? 0 : 1; } public static int test_0_constrained_reftype () { GenericClass<String> t = new GenericClass<String> (); return t.toString ("1234") == "1234" ? 0 : 1; } public static int test_0_box_brtrue_optimizations () { if (IsNull<int>(5)) return 1; if (!IsNull<object>(null)) return 1; return 0; } [Category ("!FULLAOT")] public static int test_0_generic_get_value_optimization_int () { int[] x = new int[] {100, 200}; if (GenericClass<int>.Z (x, 0) != 100) return 2; if (GenericClass<int>.Z (x, 1) != 200) return 3; return 0; } interface NonGenericInterface { int return_field (); } interface GenericInterface<T> : NonGenericInterface { T not_used (); } struct ImplementGenericInterface<T> : GenericInterface<T> { public Object padding1; public Object padding2; public Object padding3; public T[] arr_t; public ImplementGenericInterface (T[] arr_t) { this.padding1 = null; this.padding2 = null; this.padding3 = null; this.arr_t = arr_t; } public T not_used () { return arr_t [0]; } public int return_field () { return arr_t.Length; } } public static int test_8_struct_implements_generic_interface () { int[] arr = {1, 2, 3, 4}; NonGenericInterface s = new ImplementGenericInterface<int> (arr); return s.return_field () + s.return_field (); } public static int test_0_generic_get_value_optimization_vtype () { TestStruct[] arr = new TestStruct[] { new TestStruct (100, 200), new TestStruct (300, 400) }; IEnumerator<TestStruct> enumerator = GenericClass<TestStruct>.Y (arr); TestStruct s; int sum = 0; while (enumerator.MoveNext ()) { s = enumerator.Current; sum += s.i + s.j; } if (sum != 1000) return 1; s = GenericClass<TestStruct>.Z (arr, 0); if (s.i != 100 || s.j != 200) return 2; s = GenericClass<TestStruct>.Z (arr, 1); if (s.i != 300 || s.j != 400) return 3; return 0; } public static int test_0_nullable_ldflda () { return GenericClass<string>.BIsAClazz == false ? 0 : 1; } public struct GenericStruct<T> { public T t; public GenericStruct (T t) { this.t = t; } } public class GenericClass<T> { public T t; public GenericClass (T t) { this.t = t; } public GenericClass () { } public T ldobj_stobj (ref T t1, ref T t2) { t1 = t2; T t = t1; return t; } public T ldelem_stelem (T t) { T[] arr = new T [10]; arr [0] = t; return arr [0]; } public String toString (T t) { return t.ToString (); } public static IEnumerator<T> Y (IEnumerable <T> x) { return x.GetEnumerator (); } public static T Z (IList<T> x, int index) { return x [index]; } protected static T NullB = default(T); private static Nullable<bool> _BIsA = null; public static bool BIsAClazz { get { _BIsA = false; return _BIsA.Value; } } } public class MRO : MarshalByRefObject { public GenericStruct<int> struct_field; public GenericClass<int> class_field; } public class MRO<T> : MarshalByRefObject { public T gen_field; public T stfld_ldfld (T t) { var m = this; m.gen_field = t; return m.gen_field; } } public static int test_0_ldfld_stfld_mro () { MRO m = new MRO (); GenericStruct<int> s = new GenericStruct<int> (5); // This generates stfld m.struct_field = s; // This generates ldflda if (m.struct_field.t != 5) return 1; // This generates ldfld GenericStruct<int> s2 = m.struct_field; if (s2.t != 5) return 2; if (m.struct_field.t != 5) return 3; m.class_field = new GenericClass<int> (5); if (m.class_field.t != 5) return 4; // gshared var m2 = new MRO<string> (); if (m2.stfld_ldfld ("A") != "A") return 5; return 0; } // FIXME: [Category ("!FULLAOT")] public static int test_0_generic_virtual_call_on_vtype_unbox () { object o = new Object (); IFoo h = new Handler(o); if (h.Bar<object> () != o) return 1; else return 0; } public static int test_0_box_brtrue_opt () { Foo<int> f = new Foo<int> (5); f [123] = 5; return 0; } public static int test_0_box_brtrue_opt_regress_81102 () { if (new Foo<int>(5).ToString () == "null") return 0; else return 1; } struct S { public int i; } public static int test_0_ldloca_initobj_opt () { if (new Foo<S> (new S ()).get_default ().i != 0) return 1; if (new Foo<object> (null).get_default () != null) return 2; return 0; } #if !__MOBILE__ public static int test_0_variance_reflection () { // covariance on IEnumerator if (!typeof (MyIEnumerator<object>).IsAssignableFrom (typeof (MyIEnumerator<string>))) return 1; // covariance on IEnumerator and covariance on arrays if (!typeof (MyIEnumerator<object>[]).IsAssignableFrom (typeof (MyIEnumerator<string>[]))) return 2; // covariance and implemented interfaces if (!typeof (MyIEnumerator<object>).IsAssignableFrom (typeof (Enumerator<string>))) return 3; // contravariance on IComparer if (!typeof (IComparer<string>).IsAssignableFrom (typeof (IComparer<object>))) return 4; // contravariance on IComparer, contravariance on arrays if (!typeof (IComparer<string>[]).IsAssignableFrom (typeof (IComparer<object>[]))) return 5; // contravariance and interface inheritance if (!typeof (IComparer<string>[]).IsAssignableFrom (typeof (IKeyComparer<object>[]))) return 6; return 0; } #endif public static int test_0_ldvirtftn_generic_method () { new GenericsTests ().ldvirtftn<string> (); return the_type == typeof (string) ? 0 : 1; } public static int test_0_throw_dead_this () { new Foo<string> ("").throw_dead_this (); return 0; } struct S<T> {} public static int test_0_inline_infinite_polymorphic_recursion () { f<int>(0); return 0; } private static void f<T>(int i) { if(i==42) f<S<T>>(i); } // This cannot be made to work with full-aot, since there it is impossible to // statically determine that Foo<string>.Bar <int> is needed, the code only // references IFoo.Bar<int> [Category ("!FULLAOT")] public static int test_0_generic_virtual_on_interfaces () { Foo<string>.count1 = 0; Foo<string>.count2 = 0; Foo<string>.count3 = 0; IFoo f = new Foo<string> (""); for (int i = 0; i < 1000; ++i) { f.Bar <int> (); f.Bar <string> (); f.NonGeneric (); } if (Foo<string>.count1 != 1000) return 1; if (Foo<string>.count2 != 1000) return 2; if (Foo<string>.count3 != 1000) return 3; VirtualInterfaceCallFromGenericMethod<long> (f); return 0; } public static int test_0_generic_virtual_on_interfaces_ref () { Foo<string>.count1 = 0; Foo<string>.count2 = 0; Foo<string>.count3 = 0; Foo<string>.count4 = 0; IFoo f = new Foo<string> (""); for (int i = 0; i < 1000; ++i) { f.Bar <string> (); f.Bar <object> (); f.NonGeneric (); } if (Foo<string>.count2 != 1000) return 2; if (Foo<string>.count3 != 1000) return 3; if (Foo<string>.count4 != 1000) return 4; return 0; } //repro for #505375 [Category ("!FULLAOT")] public static int test_2_cprop_bug () { int idx = 0; int a = 1; var cmp = System.Collections.Generic.Comparer<int>.Default ; if (cmp.Compare (a, 0) > 0) a = 0; do { idx++; } while (cmp.Compare (idx - 1, a) == 0); return idx; } enum MyEnumUlong : ulong { Value_2 = 2 } public static int test_0_regress_550964_constrained_enum_long () { MyEnumUlong a = MyEnumUlong.Value_2; MyEnumUlong b = MyEnumUlong.Value_2; return Pan (a, b) ? 0 : 1; } static bool Pan<T> (T a, T b) { return a.Equals (b); } public class XElement { public string Value { get; set; } } public static int test_0_fullaot_linq () { var allWords = new XElement [] { new XElement { Value = "one" } }; var filteredWords = allWords.Where(kw => kw.Value.StartsWith("T")); return filteredWords.Count (); } public static int test_0_fullaot_comparer_t () { var l = new SortedList <TimeSpan, int> (); return l.Count; } public static int test_0_fullaot_comparer_t_2 () { var l = new Dictionary <TimeSpan, int> (); return l.Count; } static void enumerate<T> (IEnumerable<T> arr) { foreach (var o in arr) ; int c = ((ICollection<T>)arr).Count; } /* Test that treating arrays as generic collections works with full-aot */ public static int test_0_fullaot_array_wrappers () { GenericsTests[] arr = new GenericsTests [10]; enumerate<GenericsTests> (arr); return 0; } static int cctor_count = 0; public abstract class Beta<TChanged> { static Beta() { cctor_count ++; } } public class Gamma<T> : Beta<T> { static Gamma() { } } // #519336 public static int test_2_generic_class_init_gshared_ctor () { new Gamma<object>(); new Gamma<string>(); return cctor_count; } static int cctor_count2 = 0; class ServiceController<T> { static ServiceController () { cctor_count2 ++; } public ServiceController () { } } static ServiceController<T> Create<T>() { return new ServiceController<T>(); } // #631409 public static int test_2_generic_class_init_gshared_ctor_from_gshared () { Create<object> (); Create<string> (); return cctor_count2; } public static Type get_type<T> () { return typeof (T); } public static int test_0_gshared_delegate_rgctx () { Func<Type> t = new Func<Type> (get_type<string>); if (t () == typeof (string)) return 0; else return 1; } // Creating a delegate from a generic method from gshared code public static int test_0_gshared_delegate_from_gshared () { if (gshared_delegate_from_gshared <object> () != 0) return 1; if (gshared_delegate_from_gshared <string> () != 0) return 2; return 0; } public static int gshared_delegate_from_gshared <T> () { Func<Type> t = new Func<Type> (get_type<T>); return t () == typeof (T) ? 0 : 1; } public static int test_0_marshalbyref_call_from_gshared_virt_elim () { /* Calling a virtual method from gshared code which is changed to a nonvirt call */ Class1<object> o = new Class1<object> (); o.Do (new Class2<object> ()); return 0; } class Pair<TKey, TValue> { public static KeyValuePair<TKey, TValue> make_pair (TKey key, TValue value) { return new KeyValuePair<TKey, TValue> (key, value); } public delegate TRet Transform<TRet> (TKey key, TValue value); } public static int test_0_bug_620864 () { var d = new Pair<string, Type>.Transform<KeyValuePair<string, Type>> (Pair<string, Type>.make_pair); var p = d ("FOO", typeof (int)); if (p.Key != "FOO" || p.Value != typeof (int)) return 1; return 0; } struct RecStruct<T> { public void foo (RecStruct<RecStruct<T>> baz) { } } public static int test_0_infinite_generic_recursion () { // Check that the AOT compile can deal with infinite generic recursion through // parameter types RecStruct<int> bla; return 0; } struct FooStruct { } bool IsNull2 <T> (object value) where T : struct { T? item = (T?) value; if (item.HasValue) return false; return true; } public static int test_0_full_aot_nullable_unbox_from_gshared_code () { if (!new GenericsTests ().IsNull2<FooStruct> (null)) return 1; if (new GenericsTests ().IsNull2<FooStruct> (new FooStruct ())) return 2; return 0; } public static int test_0_partial_sharing () { if (PartialShared1 (new List<string> (), 1) != typeof (string)) return 1; if (PartialShared1 (new List<GenericsTests> (), 1) != typeof (GenericsTests)) return 2; if (PartialShared2 (new List<string> (), 1) != typeof (int)) return 3; if (PartialShared2 (new List<GenericsTests> (), 1) != typeof (int)) return 4; return 0; } [Category ("GSHAREDVT")] public static int test_6_partial_sharing_linq () { var messages = new List<Message> (); messages.Add (new Message () { MessageID = 5 }); messages.Add (new Message () { MessageID = 6 }); return messages.Max(i => i.MessageID); } public static int test_0_partial_shared_method_in_nonshared_class () { var c = new Class1<double> (); return (c.Foo<string> (5).GetType () == typeof (Class1<string>)) ? 0 : 1; } class Message { public int MessageID { get; set; } } public static Type PartialShared1<T, K> (List<T> list, K k) { return typeof (T); } public static Type PartialShared2<T, K> (List<T> list, K k) { return typeof (K); } public class Class1<T> { public virtual void Do (Class2<T> t) { t.Foo (); } public virtual object Foo<U> (T t) { return new Class1<U> (); } } public interface IFace1<T> { void Foo (); } public class Class2<T> : MarshalByRefObject, IFace1<T> { public void Foo () { } } public static void VirtualInterfaceCallFromGenericMethod <T> (IFoo f) { f.Bar <T> (); } public static Type the_type; public void ldvirtftn<T> () { Foo <T> binding = new Foo <T> (default (T)); binding.GenericEvent += event_handler; binding.fire (); } public virtual void event_handler<T> (Foo<T> sender) { the_type = typeof (T); } public interface IFoo { void NonGeneric (); object Bar<T>(); } public class Foo<T1> : IFoo { public Foo(T1 t1) { m_t1 = t1; } public override string ToString() { return Bar(m_t1 == null ? "null" : "null"); } public String Bar (String s) { return s; } public int this [T1 key] { set { if (key == null) throw new ArgumentNullException ("key"); } } public void throw_dead_this () { try { new SomeClass().ThrowAnException(); } catch { } } public T1 get_default () { return default (T1); } readonly T1 m_t1; public delegate void GenericEventHandler (Foo<T1> sender); public event GenericEventHandler GenericEvent; public void fire () { GenericEvent (this); } public static int count1, count2, count3, count4; public void NonGeneric () { count3 ++; } public object Bar <T> () { if (typeof (T) == typeof (int)) count1 ++; else if (typeof (T) == typeof (string)) count2 ++; else if (typeof (T) == typeof (object)) count4 ++; return null; } } public class SomeClass { public void ThrowAnException() { throw new Exception ("Something went wrong"); } } struct Handler : IFoo { object o; public Handler(object o) { this.o = o; } public void NonGeneric () { } public object Bar<T>() { return o; } } static bool IsNull<T> (T t) { if (t == null) return true; else return false; } static object Box<T> (T t) { return t; } static T Unbox <T> (object o) { return (T) o; } interface IDefaultRetriever { T GetDefault<T>(); } class DefaultRetriever : IDefaultRetriever { [MethodImpl(MethodImplOptions.Synchronized)] public T GetDefault<T>() { return default(T); } } [Category ("!FULLAOT")] [Category ("!BITCODE")] public static int test_0_regress_668095_synchronized_gshared () { return DoSomething (new DefaultRetriever ()); } static int DoSomething(IDefaultRetriever foo) { int result = foo.GetDefault<int>(); return result; } class SyncClass<T> { [MethodImpl(MethodImplOptions.Synchronized)] public Type getInstance() { return typeof (T); } } [Category ("GSHAREDVT")] static int test_0_synchronized_gshared () { var c = new SyncClass<string> (); if (c.getInstance () != typeof (string)) return 1; return 0; } class Response { } public static int test_0_687865_isinst_with_cache_wrapper () { object o = new object (); if (o is Action<IEnumerable<Response>>) return 1; else return 0; } enum DocType { One, Two, Three } class Doc { public string Name { get; set; } public DocType Type { get; set; } } // #2155 [Category ("GSHAREDVT")] public static int test_0_fullaot_sflda_cctor () { List<Doc> documents = new List<Doc>(); documents.Add(new Doc { Name = "Doc1", Type = DocType.One } ); documents.Add(new Doc { Name = "Doc2", Type = DocType.Two } ); documents.Add(new Doc { Name = "Doc3", Type = DocType.Three } ); documents.Add(new Doc { Name = "Doc4", Type = DocType.One } ); documents.Add(new Doc { Name = "Doc5", Type = DocType.Two } ); documents.Add(new Doc { Name = "Doc6", Type = DocType.Three } ); documents.Add(new Doc { Name = "Doc7", Type = DocType.One } ); documents.Add(new Doc { Name = "Doc8", Type = DocType.Two } ); documents.Add(new Doc { Name = "Doc9", Type = DocType.Three } ); List<DocType> categories = documents.Select(d=>d.Type).Distinct().ToList<DocType>().OrderBy(d => d).ToList(); foreach(DocType cat in categories) { List<Doc> catDocs = documents.Where(d => d.Type == cat).OrderBy(d => d.Name).ToList<Doc>(); } return 0; } class A { } static List<A> sources = new List<A>(); // #6112 public static int test_0_fullaot_imt () { sources.Add(null); sources.Add(null); int a = sources.Count; var enumerator = sources.GetEnumerator() as IEnumerator<object>; while (enumerator.MoveNext()) { object o = enumerator.Current; } return 0; } class AClass { } class BClass : AClass { } public static int test_0_fullaot_variant_iface () { var arr = new BClass [10]; var enumerable = (IEnumerable<AClass>)arr; enumerable.GetEnumerator (); return 0; } struct Record : Foo2<Record>.IRecord { int counter; int Foo2<Record>.IRecord.DoSomething () { return counter++; } } class Foo2<T> where T : Foo2<T>.IRecord { public interface IRecord { int DoSomething (); } public static int Extract (T[] t) { return t[0].DoSomething (); } } class Foo3<T> where T : IComparable { public static int CompareTo (T[] t) { // This is a constrained call to Enum.CompareTo () return t[0].CompareTo (t [0]); } } public static int test_1_regress_constrained_iface_call_7571 () { var r = new Record [10]; Foo2<Record>.Extract (r); return Foo2<Record>.Extract (r); } enum ConstrainedEnum { Val = 1 } public static int test_0_regress_constrained_iface_call_enum () { var r = new ConstrainedEnum [10]; return Foo3<ConstrainedEnum>.CompareTo (r); } public interface IFoo2 { void MoveNext (); } public struct Foo2 : IFoo2 { public void MoveNext () { } } public static Action Dingus (ref Foo2 f) { return new Action (f.MoveNext); } public static int test_0_delegate_unbox_full_aot () { Foo2 foo = new Foo2 (); Dingus (ref foo) (); return 0; } public static int test_0_arrays_ireadonly () { int[] arr = new int [10]; for (int i = 0; i < 10; ++i) arr [i] = i; IReadOnlyList<int> a = (IReadOnlyList<int>)(object)arr; if (a.Count != 10) return 1; if (a [0] != 0) return 2; if (a [1] != 1) return 3; return 0; } public static int test_0_volatile_read_write () { string foo = "ABC"; Volatile.Write (ref foo, "DEF"); return Volatile.Read (ref foo) == "DEF" ? 0 : 1; } // FIXME: Doesn't work with --regression as Interlocked.Add(ref long) is only implemented as an intrinsic #if FALSE public static async Task<T> FooAsync<T> (int i, int j) { Task<int> t = new Task<int> (delegate () { Console.WriteLine ("HIT!"); return 0; }); var response = await t; return default(T); } public static int test_0_fullaot_generic_async () { Task<string> t = FooAsync<string> (1, 2); t.RunSynchronously (); return 0; } #endif public static int test_0_delegate_callvirt_fullaot () { Func<string> f = delegate () { return "A"; }; var f2 = (Func<Func<string>, string>)Delegate.CreateDelegate (typeof (Func<Func<string>, string>), null, f.GetType ().GetMethod ("Invoke")); var s = f2 (f); return s == "A" ? 0 : 1; } public interface ICovariant<out R> { } // Deleting the `out` modifier from this line stop the problem public interface IExtCovariant<out R> : ICovariant<R> { } public class Sample<R> : ICovariant<R> { } public interface IMyInterface { } public static int test_0_variant_cast_cache () { object covariant = new Sample<IMyInterface>(); var foo = (ICovariant<IMyInterface>)(covariant); try { var extCovariant = (IExtCovariant<IMyInterface>)covariant; return 1; } catch { return 0; } } struct FooStruct2 { public int a1, a2, a3; } class MyClass<T> where T: struct { [MethodImplAttribute (MethodImplOptions.NoInlining)] public MyClass(int a1, int a2, int a3, int a4, int a5, int a6, Nullable<T> a) { } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static MyClass<T> foo () { Nullable<T> a = new Nullable<T> (); return new MyClass<T> (0, 0, 0, 0, 0, 0, a); } } public static int test_0_newobj_generic_context () { MyClass<FooStruct2>.foo (); return 0; } enum AnEnum { A, B } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static string constrained_tostring<T> (T t) { return t.ToString (); } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static bool constrained_equals<T> (T t1, T t2) { var c = EqualityComparer<T>.Default; return c.Equals (t1, t2); } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static int constrained_gethashcode<T> (T t) { return t.GetHashCode (); } public static int test_0_constrained_partial_sharing () { string s; s = constrained_tostring<int> (5); if (s != "5") return 1; s = constrained_tostring<AnEnum> (AnEnum.B); if (s != "B") return 2; if (!constrained_equals<int> (1, 1)) return 3; if (constrained_equals<int> (1, 2)) return 4; if (!constrained_equals<AnEnum> (AnEnum.A, AnEnum.A)) return 5; if (constrained_equals<AnEnum> (AnEnum.A, AnEnum.B)) return 6; int i = constrained_gethashcode<int> (5); if (i != 5) return 7; i = constrained_gethashcode<AnEnum> (AnEnum.B); if (i != 1) return 8; return 0; } enum Enum1 { A, B } enum Enum2 { A, B } public static int test_0_partial_sharing_ginst () { var l1 = new List<KeyValuePair<int, Enum1>> (); l1.Add (new KeyValuePair<int, Enum1>(5, Enum1.A)); if (l1 [0].Key != 5) return 1; if (l1 [0].Value != Enum1.A) return 2; var l2 = new List<KeyValuePair<int, Enum2>> (); l2.Add (new KeyValuePair<int, Enum2>(5, Enum2.B)); if (l2 [0].Key != 5) return 3; if (l2 [0].Value != Enum2.B) return 4; return 0; } static object delegate_8_args_res; public static int test_0_delegate_8_args () { delegate_8_args_res = null; Action<string, string, string, string, string, string, string, string> test = (a, b, c, d, e, f, g, h) => { delegate_8_args_res = h; }; test("a", "b", "c", "d", "e", "f", "g", "h"); return delegate_8_args_res == "h" ? 0 : 1; } static void throw_catch_t<T> () where T: Exception { try { throw new NotSupportedException (); } catch (T) { } } public static int test_0_gshared_catch_open_type () { throw_catch_t<NotSupportedException> (); return 0; } class ThrowClass<T> where T: Exception { public void throw_catch_t () { try { throw new NotSupportedException (); } catch (T) { } } } public static int test_0_gshared_catch_open_type_instance () { var c = new ThrowClass<NotSupportedException> (); c.throw_catch_t (); return 0; } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static bool is_ref_or_contains_refs<T> () { return RuntimeHelpers.IsReferenceOrContainsReferences<T> (); } class IsRefClass<T> { [MethodImplAttribute (MethodImplOptions.NoInlining)] public bool is_ref () { return RuntimeHelpers.IsReferenceOrContainsReferences<T> (); } } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static bool is_ref_or_contains_refs_gen_ref<T> () { return RuntimeHelpers.IsReferenceOrContainsReferences<GenStruct<T>> (); } [MethodImplAttribute (MethodImplOptions.NoInlining)] public static bool is_ref_or_contains_refs_gen_noref<T> () { return RuntimeHelpers.IsReferenceOrContainsReferences<NoRefGenStruct<T>> (); } struct GenStruct<T> { T t; } struct NoRefGenStruct<T> { } struct RefStruct { string s; } struct NestedRefStruct { RefStruct r; } struct NoRefStruct { int i; } struct AStruct3<T1, T2, T3> { T1 t1; T2 t2; T3 t3; } public static int test_0_isreference_intrins () { if (RuntimeHelpers.IsReferenceOrContainsReferences<int> ()) return 1; if (!RuntimeHelpers.IsReferenceOrContainsReferences<string> ()) return 2; if (!RuntimeHelpers.IsReferenceOrContainsReferences<RefStruct> ()) return 3; if (!RuntimeHelpers.IsReferenceOrContainsReferences<NestedRefStruct> ()) return 4; if (RuntimeHelpers.IsReferenceOrContainsReferences<NoRefStruct> ()) return 5; // Generic code if (is_ref_or_contains_refs<int> ()) return 6; // Shared code if (!is_ref_or_contains_refs<string> ()) return 7; // Complex type from shared code if (!is_ref_or_contains_refs_gen_ref<string> ()) return 8; if (is_ref_or_contains_refs_gen_ref<int> ()) return 9; if (is_ref_or_contains_refs_gen_noref<string> ()) return 10; // Complex type from shared class method var c1 = new IsRefClass<AStruct3<int, int, int>> (); if (c1.is_ref ()) return 11; var c2 = new IsRefClass<AStruct3<string, int, int>> (); if (!c2.is_ref ()) return 12; return 0; } class LdobjStobj { public int counter; public LdobjStobj buffer1; public LdobjStobj buffer2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void swap<T>(ref T first, ref T second) { second = first; } public static int test_42_ldobj_stobj_ref () { var obj = new LdobjStobj (); obj.counter = 42; swap (ref obj.buffer1, ref obj.buffer2); return obj.counter; } public interface ICompletion { Type UnsafeOnCompleted (); } public struct TaskAwaiter<T> : ICompletion { public Type UnsafeOnCompleted () { typeof(T).GetHashCode (); return typeof(T); } } public struct AStruct { public Type Caller<TAwaiter>(ref TAwaiter awaiter) where TAwaiter : ICompletion { return awaiter.UnsafeOnCompleted(); } } public static int test_0_partial_constrained_call_llvmonly () { var builder = new AStruct (); var awaiter = new TaskAwaiter<bool> (); var res = builder.Caller (ref awaiter); return res == typeof (bool) ? 0 : 1; } struct OneThing<T1> { public T1 Item1; } [MethodImpl (MethodImplOptions.NoInlining)] static T FromResult<T> (T result) { return result; } public static int test_42_llvm_gsharedvt_small_vtype_in_regs () { var t = FromResult<OneThing<int>>(new OneThing<int> {Item1 = 42}); return t.Item1; } class ThreadLocalClass<T> { [ThreadStatic] static T v; public T Value { [MethodImpl (MethodImplOptions.NoInlining)] get { return v; } [MethodImpl (MethodImplOptions.NoInlining)] set { v = value; } } } public static int test_0_tls_gshared () { var c = new ThreadLocalClass<string> (); c.Value = "FOO"; return c.Value == "FOO" ? 0 : 1; } } #if !__MOBILE__ class GenericsTests : Tests { } #endif
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.CompilerServices; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Converters; using System.Text.Json.Serialization.Metadata; using System.Threading; using System.Threading.Tasks; namespace System.Text.Json { public static partial class JsonSerializer { /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>. /// The Stream will be read to completion. /// </summary> /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="options">Options to control the behavior during reading.</param> /// <param name="cancellationToken"> /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation. /// </param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// <typeparamref name="TValue"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <typeparamref name="TValue"/> or its serializable members. /// </exception> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static ValueTask<TValue?> DeserializeAsync<TValue>( Stream utf8Json!!, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, typeof(TValue)); return ReadAllAsync<TValue>(utf8Json, jsonTypeInfo, cancellationToken); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>. /// The Stream will be read to completion. /// </summary> /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="options">Options to control the behavior during reading.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// <typeparamref name="TValue"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <typeparamref name="TValue"/> or its serializable members. /// </exception> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static TValue? Deserialize<TValue>( Stream utf8Json!!, JsonSerializerOptions? options = null) { return ReadAllUsingOptions<TValue>(utf8Json, typeof(TValue), options); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>. /// The Stream will be read to completion. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="options">Options to control the behavior during reading.</param> /// <param name="cancellationToken"> /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation. /// </param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> or <paramref name="returnType"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// the <paramref name="returnType"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <paramref name="returnType"/> or its serializable members. /// </exception> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static ValueTask<object?> DeserializeAsync( Stream utf8Json!!, Type returnType!!, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadAllAsync<object?>(utf8Json, jsonTypeInfo, cancellationToken); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>. /// The Stream will be read to completion. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="options">Options to control the behavior during reading.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> or <paramref name="returnType"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// the <paramref name="returnType"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <paramref name="returnType"/> or its serializable members. /// </exception> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static object? Deserialize( Stream utf8Json!!, Type returnType!!, JsonSerializerOptions? options = null) { return ReadAllUsingOptions<object>(utf8Json, returnType, options); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>. /// The Stream will be read to completion. /// </summary> /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="jsonTypeInfo">Metadata about the type to convert.</param> /// <param name="cancellationToken"> /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation. /// </param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// <typeparamref name="TValue"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <typeparamref name="TValue"/> or its serializable members. /// </exception> public static ValueTask<TValue?> DeserializeAsync<TValue>( Stream utf8Json!!, JsonTypeInfo<TValue> jsonTypeInfo!!, CancellationToken cancellationToken = default) { return ReadAllAsync<TValue>(utf8Json, jsonTypeInfo, cancellationToken); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>. /// The Stream will be read to completion. /// </summary> /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="jsonTypeInfo">Metadata about the type to convert.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// <typeparamref name="TValue"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <typeparamref name="TValue"/> or its serializable members. /// </exception> public static TValue? Deserialize<TValue>( Stream utf8Json!!, JsonTypeInfo<TValue> jsonTypeInfo!!) { return ReadAll<TValue>(utf8Json, jsonTypeInfo); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>. /// The Stream will be read to completion. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="context">A metadata provider for serializable types.</param> /// <param name="cancellationToken"> /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation. /// </param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/>, <paramref name="returnType"/>, or <paramref name="context"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// the <paramref name="returnType"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <paramref name="returnType"/> or its serializable members. /// </exception> /// <exception cref="InvalidOperationException"> /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/> /// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>. /// </exception> public static ValueTask<object?> DeserializeAsync( Stream utf8Json!!, Type returnType!!, JsonSerializerContext context!!, CancellationToken cancellationToken = default) { return ReadAllAsync<object>(utf8Json, GetTypeInfo(context, returnType), cancellationToken); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>. /// The Stream will be read to completion. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="context">A metadata provider for serializable types.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/>, <paramref name="returnType"/>, or <paramref name="context"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// the <paramref name="returnType"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <paramref name="returnType"/> or its serializable members. /// </exception> /// <exception cref="InvalidOperationException"> /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/> /// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>. /// </exception> public static object? Deserialize( Stream utf8Json!!, Type returnType!!, JsonSerializerContext context!!) { return ReadAll<object>(utf8Json, GetTypeInfo(context, returnType)); } /// <summary> /// Wraps the UTF-8 encoded text into an <see cref="IAsyncEnumerable{TValue}" /> /// that can be used to deserialize root-level JSON arrays in a streaming manner. /// </summary> /// <typeparam name="TValue">The element type to deserialize asynchronously.</typeparam> /// <returns>An <see cref="IAsyncEnumerable{TValue}" /> representation of the provided JSON array.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="options">Options to control the behavior during reading.</param> /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.</param> /// <returns>An <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> is <see langword="null"/>. /// </exception> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<TValue>( Stream utf8Json!!, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { options ??= JsonSerializerOptions.Default; if (!options.IsInitializedForReflectionSerializer) { options.InitializeForReflectionSerializer(); } return CreateAsyncEnumerableDeserializer(utf8Json, options, cancellationToken); [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] static async IAsyncEnumerable<TValue> CreateAsyncEnumerableDeserializer( Stream utf8Json, JsonSerializerOptions options, [EnumeratorCancellation] CancellationToken cancellationToken) { var bufferState = new ReadBufferState(options.DefaultBufferSize); // Hardcode the queue converter to avoid accidental use of custom converters JsonConverter converter = QueueOfTConverter<Queue<TValue>, TValue>.Instance; JsonTypeInfo jsonTypeInfo = CreateQueueJsonTypeInfo<TValue>(converter, options); ReadStack readStack = default; readStack.Initialize(jsonTypeInfo, supportContinuation: true); var jsonReaderState = new JsonReaderState(options.GetReaderOptions()); try { do { bufferState = await ReadFromStreamAsync(utf8Json, bufferState, cancellationToken).ConfigureAwait(false); ContinueDeserialize<Queue<TValue>>(ref bufferState, ref jsonReaderState, ref readStack, converter, options); if (readStack.Current.ReturnValue is Queue<TValue> queue) { while (queue.Count > 0) { yield return queue.Dequeue(); } } } while (!bufferState.IsFinalBlock); } finally { bufferState.Dispose(); } } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Workaround for https://github.com/mono/linker/issues/1416. All usages are marked as unsafe.")] private static JsonTypeInfo CreateQueueJsonTypeInfo<TValue>(JsonConverter queueConverter, JsonSerializerOptions queueOptions) => new JsonTypeInfo(typeof(Queue<TValue>), queueConverter, queueOptions); internal static async ValueTask<TValue?> ReadAllAsync<TValue>( Stream utf8Json, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken) { JsonSerializerOptions options = jsonTypeInfo.Options; var bufferState = new ReadBufferState(options.DefaultBufferSize); ReadStack readStack = default; readStack.Initialize(jsonTypeInfo, supportContinuation: true); JsonConverter converter = readStack.Current.JsonPropertyInfo!.ConverterBase; var jsonReaderState = new JsonReaderState(options.GetReaderOptions()); try { while (true) { bufferState = await ReadFromStreamAsync(utf8Json, bufferState, cancellationToken).ConfigureAwait(false); TValue value = ContinueDeserialize<TValue>(ref bufferState, ref jsonReaderState, ref readStack, converter, options); if (bufferState.IsFinalBlock) { return value!; } } } finally { bufferState.Dispose(); } } internal static TValue? ReadAll<TValue>( Stream utf8Json, JsonTypeInfo jsonTypeInfo) { JsonSerializerOptions options = jsonTypeInfo.Options; var bufferState = new ReadBufferState(options.DefaultBufferSize); ReadStack readStack = default; readStack.Initialize(jsonTypeInfo, supportContinuation: true); JsonConverter converter = readStack.Current.JsonPropertyInfo!.ConverterBase; var jsonReaderState = new JsonReaderState(options.GetReaderOptions()); try { while (true) { bufferState = ReadFromStream(utf8Json, bufferState); TValue value = ContinueDeserialize<TValue>(ref bufferState, ref jsonReaderState, ref readStack, converter, options); if (bufferState.IsFinalBlock) { return value!; } } } finally { bufferState.Dispose(); } } /// <summary> /// Read from the stream until either our buffer is filled or we hit EOF. /// Calling ReadCore is relatively expensive, so we minimize the number of times /// we need to call it. /// </summary> internal static async ValueTask<ReadBufferState> ReadFromStreamAsync( Stream utf8Json, ReadBufferState bufferState, CancellationToken cancellationToken) { while (true) { int bytesRead = await utf8Json.ReadAsync( #if BUILDING_INBOX_LIBRARY bufferState.Buffer.AsMemory(bufferState.BytesInBuffer), #else bufferState.Buffer, bufferState.BytesInBuffer, bufferState.Buffer.Length - bufferState.BytesInBuffer, #endif cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { bufferState.IsFinalBlock = true; break; } bufferState.BytesInBuffer += bytesRead; if (bufferState.BytesInBuffer == bufferState.Buffer.Length) { break; } } return bufferState; } /// <summary> /// Read from the stream until either our buffer is filled or we hit EOF. /// Calling ReadCore is relatively expensive, so we minimize the number of times /// we need to call it. /// </summary> internal static ReadBufferState ReadFromStream( Stream utf8Json, ReadBufferState bufferState) { while (true) { int bytesRead = utf8Json.Read( #if BUILDING_INBOX_LIBRARY bufferState.Buffer.AsSpan(bufferState.BytesInBuffer)); #else bufferState.Buffer, bufferState.BytesInBuffer, bufferState.Buffer.Length - bufferState.BytesInBuffer); #endif if (bytesRead == 0) { bufferState.IsFinalBlock = true; break; } bufferState.BytesInBuffer += bytesRead; if (bufferState.BytesInBuffer == bufferState.Buffer.Length) { break; } } return bufferState; } internal static TValue ContinueDeserialize<TValue>( ref ReadBufferState bufferState, ref JsonReaderState jsonReaderState, ref ReadStack readStack, JsonConverter converter, JsonSerializerOptions options) { if (bufferState.BytesInBuffer > bufferState.ClearMax) { bufferState.ClearMax = bufferState.BytesInBuffer; } int start = 0; if (bufferState.IsFirstIteration) { bufferState.IsFirstIteration = false; // Handle the UTF-8 BOM if present Debug.Assert(bufferState.Buffer.Length >= JsonConstants.Utf8Bom.Length); if (bufferState.Buffer.AsSpan().StartsWith(JsonConstants.Utf8Bom)) { start += JsonConstants.Utf8Bom.Length; bufferState.BytesInBuffer -= JsonConstants.Utf8Bom.Length; } } // Process the data available TValue value = ReadCore<TValue>( ref jsonReaderState, bufferState.IsFinalBlock, new ReadOnlySpan<byte>(bufferState.Buffer, start, bufferState.BytesInBuffer), options, ref readStack, converter); Debug.Assert(readStack.BytesConsumed <= bufferState.BytesInBuffer); int bytesConsumed = checked((int)readStack.BytesConsumed); bufferState.BytesInBuffer -= bytesConsumed; // The reader should have thrown if we have remaining bytes. Debug.Assert(!bufferState.IsFinalBlock || bufferState.BytesInBuffer == 0); if (!bufferState.IsFinalBlock) { // Check if we need to shift or expand the buffer because there wasn't enough data to complete deserialization. if ((uint)bufferState.BytesInBuffer > ((uint)bufferState.Buffer.Length / 2)) { // We have less than half the buffer available, double the buffer size. byte[] oldBuffer = bufferState.Buffer; int oldClearMax = bufferState.ClearMax; byte[] newBuffer = ArrayPool<byte>.Shared.Rent((bufferState.Buffer.Length < (int.MaxValue / 2)) ? bufferState.Buffer.Length * 2 : int.MaxValue); // Copy the unprocessed data to the new buffer while shifting the processed bytes. Buffer.BlockCopy(oldBuffer, bytesConsumed + start, newBuffer, 0, bufferState.BytesInBuffer); bufferState.Buffer = newBuffer; bufferState.ClearMax = bufferState.BytesInBuffer; // Clear and return the old buffer new Span<byte>(oldBuffer, 0, oldClearMax).Clear(); ArrayPool<byte>.Shared.Return(oldBuffer); } else if (bufferState.BytesInBuffer != 0) { // Shift the processed bytes to the beginning of buffer to make more room. Buffer.BlockCopy(bufferState.Buffer, bytesConsumed + start, bufferState.Buffer, 0, bufferState.BytesInBuffer); } } return value; } [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] private static TValue? ReadAllUsingOptions<TValue>( Stream utf8Json, Type returnType, JsonSerializerOptions? options) { JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadAll<TValue>(utf8Json, jsonTypeInfo); } private static TValue ReadCore<TValue>( ref JsonReaderState readerState, bool isFinalBlock, ReadOnlySpan<byte> buffer, JsonSerializerOptions options, ref ReadStack state, JsonConverter converterBase) { var reader = new Utf8JsonReader(buffer, isFinalBlock, readerState); // If we haven't read in the entire stream's payload we'll need to signify that we want // to enable read ahead behaviors to ensure we have complete json objects and arrays // ({}, []) when needed. (Notably to successfully parse JsonElement via JsonDocument // to assign to object and JsonElement properties in the constructed .NET object.) state.ReadAhead = !isFinalBlock; state.BytesConsumed = 0; TValue? value = ReadCore<TValue>(converterBase, ref reader, options, ref state); readerState = reader.CurrentState; return value!; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.CompilerServices; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Converters; using System.Text.Json.Serialization.Metadata; using System.Threading; using System.Threading.Tasks; namespace System.Text.Json { public static partial class JsonSerializer { /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>. /// The Stream will be read to completion. /// </summary> /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="options">Options to control the behavior during reading.</param> /// <param name="cancellationToken"> /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation. /// </param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// <typeparamref name="TValue"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <typeparamref name="TValue"/> or its serializable members. /// </exception> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static ValueTask<TValue?> DeserializeAsync<TValue>( Stream utf8Json!!, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, typeof(TValue)); return ReadAllAsync<TValue>(utf8Json, jsonTypeInfo, cancellationToken); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>. /// The Stream will be read to completion. /// </summary> /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="options">Options to control the behavior during reading.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// <typeparamref name="TValue"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <typeparamref name="TValue"/> or its serializable members. /// </exception> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static TValue? Deserialize<TValue>( Stream utf8Json!!, JsonSerializerOptions? options = null) { return ReadAllUsingOptions<TValue>(utf8Json, typeof(TValue), options); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>. /// The Stream will be read to completion. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="options">Options to control the behavior during reading.</param> /// <param name="cancellationToken"> /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation. /// </param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> or <paramref name="returnType"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// the <paramref name="returnType"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <paramref name="returnType"/> or its serializable members. /// </exception> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static ValueTask<object?> DeserializeAsync( Stream utf8Json!!, Type returnType!!, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadAllAsync<object?>(utf8Json, jsonTypeInfo, cancellationToken); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>. /// The Stream will be read to completion. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="options">Options to control the behavior during reading.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> or <paramref name="returnType"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// the <paramref name="returnType"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <paramref name="returnType"/> or its serializable members. /// </exception> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static object? Deserialize( Stream utf8Json!!, Type returnType!!, JsonSerializerOptions? options = null) { return ReadAllUsingOptions<object>(utf8Json, returnType, options); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>. /// The Stream will be read to completion. /// </summary> /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="jsonTypeInfo">Metadata about the type to convert.</param> /// <param name="cancellationToken"> /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation. /// </param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// <typeparamref name="TValue"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <typeparamref name="TValue"/> or its serializable members. /// </exception> public static ValueTask<TValue?> DeserializeAsync<TValue>( Stream utf8Json!!, JsonTypeInfo<TValue> jsonTypeInfo!!, CancellationToken cancellationToken = default) { return ReadAllAsync<TValue>(utf8Json, jsonTypeInfo, cancellationToken); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>. /// The Stream will be read to completion. /// </summary> /// <typeparam name="TValue">The type to deserialize the JSON value into.</typeparam> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="jsonTypeInfo">Metadata about the type to convert.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> or <paramref name="jsonTypeInfo"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// <typeparamref name="TValue"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <typeparamref name="TValue"/> or its serializable members. /// </exception> public static TValue? Deserialize<TValue>( Stream utf8Json!!, JsonTypeInfo<TValue> jsonTypeInfo!!) { return ReadAll<TValue>(utf8Json, jsonTypeInfo); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>. /// The Stream will be read to completion. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="context">A metadata provider for serializable types.</param> /// <param name="cancellationToken"> /// The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation. /// </param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/>, <paramref name="returnType"/>, or <paramref name="context"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// the <paramref name="returnType"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <paramref name="returnType"/> or its serializable members. /// </exception> /// <exception cref="InvalidOperationException"> /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/> /// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>. /// </exception> public static ValueTask<object?> DeserializeAsync( Stream utf8Json!!, Type returnType!!, JsonSerializerContext context!!, CancellationToken cancellationToken = default) { return ReadAllAsync<object>(utf8Json, GetTypeInfo(context, returnType), cancellationToken); } /// <summary> /// Reads the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>. /// The Stream will be read to completion. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="context">A metadata provider for serializable types.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/>, <paramref name="returnType"/>, or <paramref name="context"/> is <see langword="null"/>. /// </exception> /// <exception cref="JsonException"> /// The JSON is invalid, /// the <paramref name="returnType"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> /// <exception cref="NotSupportedException"> /// There is no compatible <see cref="System.Text.Json.Serialization.JsonConverter"/> /// for <paramref name="returnType"/> or its serializable members. /// </exception> /// <exception cref="InvalidOperationException"> /// The <see cref="JsonSerializerContext.GetTypeInfo(Type)"/> method on the provided <paramref name="context"/> /// did not return a compatible <see cref="JsonTypeInfo"/> for <paramref name="returnType"/>. /// </exception> public static object? Deserialize( Stream utf8Json!!, Type returnType!!, JsonSerializerContext context!!) { return ReadAll<object>(utf8Json, GetTypeInfo(context, returnType)); } /// <summary> /// Wraps the UTF-8 encoded text into an <see cref="IAsyncEnumerable{TValue}" /> /// that can be used to deserialize root-level JSON arrays in a streaming manner. /// </summary> /// <typeparam name="TValue">The element type to deserialize asynchronously.</typeparam> /// <returns>An <see cref="IAsyncEnumerable{TValue}" /> representation of the provided JSON array.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="options">Options to control the behavior during reading.</param> /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the read operation.</param> /// <returns>An <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <exception cref="System.ArgumentNullException"> /// <paramref name="utf8Json"/> is <see langword="null"/>. /// </exception> [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] public static IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<TValue>( Stream utf8Json!!, JsonSerializerOptions? options = null, CancellationToken cancellationToken = default) { options ??= JsonSerializerOptions.Default; if (!options.IsInitializedForReflectionSerializer) { options.InitializeForReflectionSerializer(); } return CreateAsyncEnumerableDeserializer(utf8Json, options, cancellationToken); [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] static async IAsyncEnumerable<TValue> CreateAsyncEnumerableDeserializer( Stream utf8Json, JsonSerializerOptions options, [EnumeratorCancellation] CancellationToken cancellationToken) { var bufferState = new ReadBufferState(options.DefaultBufferSize); // Hardcode the queue converter to avoid accidental use of custom converters JsonConverter converter = QueueOfTConverter<Queue<TValue>, TValue>.Instance; JsonTypeInfo jsonTypeInfo = CreateQueueJsonTypeInfo<TValue>(converter, options); ReadStack readStack = default; readStack.Initialize(jsonTypeInfo, supportContinuation: true); var jsonReaderState = new JsonReaderState(options.GetReaderOptions()); try { do { bufferState = await ReadFromStreamAsync(utf8Json, bufferState, cancellationToken).ConfigureAwait(false); ContinueDeserialize<Queue<TValue>>(ref bufferState, ref jsonReaderState, ref readStack, converter, options); if (readStack.Current.ReturnValue is Queue<TValue> queue) { while (queue.Count > 0) { yield return queue.Dequeue(); } } } while (!bufferState.IsFinalBlock); } finally { bufferState.Dispose(); } } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Workaround for https://github.com/mono/linker/issues/1416. All usages are marked as unsafe.")] private static JsonTypeInfo CreateQueueJsonTypeInfo<TValue>(JsonConverter queueConverter, JsonSerializerOptions queueOptions) => new JsonTypeInfo(typeof(Queue<TValue>), queueConverter, queueOptions); internal static async ValueTask<TValue?> ReadAllAsync<TValue>( Stream utf8Json, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken) { JsonSerializerOptions options = jsonTypeInfo.Options; var bufferState = new ReadBufferState(options.DefaultBufferSize); ReadStack readStack = default; readStack.Initialize(jsonTypeInfo, supportContinuation: true); JsonConverter converter = readStack.Current.JsonPropertyInfo!.ConverterBase; var jsonReaderState = new JsonReaderState(options.GetReaderOptions()); try { while (true) { bufferState = await ReadFromStreamAsync(utf8Json, bufferState, cancellationToken).ConfigureAwait(false); TValue value = ContinueDeserialize<TValue>(ref bufferState, ref jsonReaderState, ref readStack, converter, options); if (bufferState.IsFinalBlock) { return value!; } } } finally { bufferState.Dispose(); } } internal static TValue? ReadAll<TValue>( Stream utf8Json, JsonTypeInfo jsonTypeInfo) { JsonSerializerOptions options = jsonTypeInfo.Options; var bufferState = new ReadBufferState(options.DefaultBufferSize); ReadStack readStack = default; readStack.Initialize(jsonTypeInfo, supportContinuation: true); JsonConverter converter = readStack.Current.JsonPropertyInfo!.ConverterBase; var jsonReaderState = new JsonReaderState(options.GetReaderOptions()); try { while (true) { bufferState = ReadFromStream(utf8Json, bufferState); TValue value = ContinueDeserialize<TValue>(ref bufferState, ref jsonReaderState, ref readStack, converter, options); if (bufferState.IsFinalBlock) { return value!; } } } finally { bufferState.Dispose(); } } /// <summary> /// Read from the stream until either our buffer is filled or we hit EOF. /// Calling ReadCore is relatively expensive, so we minimize the number of times /// we need to call it. /// </summary> internal static async ValueTask<ReadBufferState> ReadFromStreamAsync( Stream utf8Json, ReadBufferState bufferState, CancellationToken cancellationToken) { while (true) { int bytesRead = await utf8Json.ReadAsync( #if BUILDING_INBOX_LIBRARY bufferState.Buffer.AsMemory(bufferState.BytesInBuffer), #else bufferState.Buffer, bufferState.BytesInBuffer, bufferState.Buffer.Length - bufferState.BytesInBuffer, #endif cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { bufferState.IsFinalBlock = true; break; } bufferState.BytesInBuffer += bytesRead; if (bufferState.BytesInBuffer == bufferState.Buffer.Length) { break; } } return bufferState; } /// <summary> /// Read from the stream until either our buffer is filled or we hit EOF. /// Calling ReadCore is relatively expensive, so we minimize the number of times /// we need to call it. /// </summary> internal static ReadBufferState ReadFromStream( Stream utf8Json, ReadBufferState bufferState) { while (true) { int bytesRead = utf8Json.Read( #if BUILDING_INBOX_LIBRARY bufferState.Buffer.AsSpan(bufferState.BytesInBuffer)); #else bufferState.Buffer, bufferState.BytesInBuffer, bufferState.Buffer.Length - bufferState.BytesInBuffer); #endif if (bytesRead == 0) { bufferState.IsFinalBlock = true; break; } bufferState.BytesInBuffer += bytesRead; if (bufferState.BytesInBuffer == bufferState.Buffer.Length) { break; } } return bufferState; } internal static TValue ContinueDeserialize<TValue>( ref ReadBufferState bufferState, ref JsonReaderState jsonReaderState, ref ReadStack readStack, JsonConverter converter, JsonSerializerOptions options) { if (bufferState.BytesInBuffer > bufferState.ClearMax) { bufferState.ClearMax = bufferState.BytesInBuffer; } int start = 0; if (bufferState.IsFirstIteration) { bufferState.IsFirstIteration = false; // Handle the UTF-8 BOM if present Debug.Assert(bufferState.Buffer.Length >= JsonConstants.Utf8Bom.Length); if (bufferState.Buffer.AsSpan().StartsWith(JsonConstants.Utf8Bom)) { start += JsonConstants.Utf8Bom.Length; bufferState.BytesInBuffer -= JsonConstants.Utf8Bom.Length; } } // Process the data available TValue value = ReadCore<TValue>( ref jsonReaderState, bufferState.IsFinalBlock, new ReadOnlySpan<byte>(bufferState.Buffer, start, bufferState.BytesInBuffer), options, ref readStack, converter); Debug.Assert(readStack.BytesConsumed <= bufferState.BytesInBuffer); int bytesConsumed = checked((int)readStack.BytesConsumed); bufferState.BytesInBuffer -= bytesConsumed; // The reader should have thrown if we have remaining bytes. Debug.Assert(!bufferState.IsFinalBlock || bufferState.BytesInBuffer == 0); if (!bufferState.IsFinalBlock) { // Check if we need to shift or expand the buffer because there wasn't enough data to complete deserialization. if ((uint)bufferState.BytesInBuffer > ((uint)bufferState.Buffer.Length / 2)) { // We have less than half the buffer available, double the buffer size. byte[] oldBuffer = bufferState.Buffer; int oldClearMax = bufferState.ClearMax; byte[] newBuffer = ArrayPool<byte>.Shared.Rent((bufferState.Buffer.Length < (int.MaxValue / 2)) ? bufferState.Buffer.Length * 2 : int.MaxValue); // Copy the unprocessed data to the new buffer while shifting the processed bytes. Buffer.BlockCopy(oldBuffer, bytesConsumed + start, newBuffer, 0, bufferState.BytesInBuffer); bufferState.Buffer = newBuffer; bufferState.ClearMax = bufferState.BytesInBuffer; // Clear and return the old buffer new Span<byte>(oldBuffer, 0, oldClearMax).Clear(); ArrayPool<byte>.Shared.Return(oldBuffer); } else if (bufferState.BytesInBuffer != 0) { // Shift the processed bytes to the beginning of buffer to make more room. Buffer.BlockCopy(bufferState.Buffer, bytesConsumed + start, bufferState.Buffer, 0, bufferState.BytesInBuffer); } } return value; } [RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)] private static TValue? ReadAllUsingOptions<TValue>( Stream utf8Json, Type returnType, JsonSerializerOptions? options) { JsonTypeInfo jsonTypeInfo = GetTypeInfo(options, returnType); return ReadAll<TValue>(utf8Json, jsonTypeInfo); } private static TValue ReadCore<TValue>( ref JsonReaderState readerState, bool isFinalBlock, ReadOnlySpan<byte> buffer, JsonSerializerOptions options, ref ReadStack state, JsonConverter converterBase) { var reader = new Utf8JsonReader(buffer, isFinalBlock, readerState); // If we haven't read in the entire stream's payload we'll need to signify that we want // to enable read ahead behaviors to ensure we have complete json objects and arrays // ({}, []) when needed. (Notably to successfully parse JsonElement via JsonDocument // to assign to object and JsonElement properties in the constructed .NET object.) state.ReadAhead = !isFinalBlock; state.BytesConsumed = 0; TValue? value = ReadCore<TValue>(converterBase, ref reader, options, ref state); readerState = reader.CurrentState; return value!; } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Regression/JitBlue/GitHub_8231/GitHub_8231.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/readytorun/r2rdump/FrameworkTests/R2RDumpTester.cs
using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using Xunit; namespace R2RDumpTests { public class R2RDumpTester { private const string CoreRoot = "CORE_ROOT"; private const string R2RDumpRelativePath = "R2RDump"; private const string R2RDumpFile = "R2RDump.dll"; private const string CoreRunFileName = "corerun"; public static string FindExePath(string exe) { if (OperatingSystem.IsWindows()) { exe = exe + ".exe"; } exe = Environment.ExpandEnvironmentVariables(exe); if (!File.Exists(exe)) { if (Path.GetDirectoryName(exe) == String.Empty) { foreach (string test in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator)) { string path = test.Trim(); if (!String.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, exe))) return Path.GetFullPath(path); } } throw new FileNotFoundException(new FileNotFoundException().Message, exe); } return Path.GetFullPath(exe); } [Fact] [SkipOnMono("Ready-To-Run is a CoreCLR-only feature", TestPlatforms.Any)] public static void DumpCoreLib() { string CoreRootVar = Environment.GetEnvironmentVariable(CoreRoot); bool IsUnix = !OperatingSystem.IsWindows(); string R2RDumpAbsolutePath = Path.Combine(CoreRootVar, R2RDumpRelativePath, R2RDumpFile); string CoreLibFile = "System.Private.CoreLib.dll"; string CoreLibAbsolutePath = Path.Combine(CoreRootVar, CoreLibFile); string OutputFile = Path.GetTempFileName(); string TestDotNetCmdVar = Environment.GetEnvironmentVariable("__TestDotNetCmd"); // Unset COMPlus_GCName since standalone GC doesnt exist in official "dotnet" deployment Environment.SetEnvironmentVariable("COMPlus_GCName", String.Empty); string DotNetAbsolutePath = string.IsNullOrEmpty(TestDotNetCmdVar) ? FindExePath("dotnet") : TestDotNetCmdVar; ProcessStartInfo processStartInfo = new ProcessStartInfo { UseShellExecute = false, FileName = DotNetAbsolutePath, // TODO, what flags do we like to test? Arguments = string.Join(" ", new string[]{"exec", R2RDumpAbsolutePath, "--in", CoreLibAbsolutePath, "--out", OutputFile}) }; Process process = Process.Start(processStartInfo); process.WaitForExit(); int exitCode = process.ExitCode; string outputContent = File.ReadAllText(OutputFile); File.Delete(OutputFile); // TODO, here is a point where we can add more validation to outputs // An uncaught exception (such as signature decoding error, would be caught by the error code) bool failed = exitCode != 0; if (failed) { Console.WriteLine("The process terminated with exit code {0}", exitCode); Console.WriteLine(outputContent); Assert.True(!failed); } } } }
using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using Xunit; namespace R2RDumpTests { public class R2RDumpTester { private const string CoreRoot = "CORE_ROOT"; private const string R2RDumpRelativePath = "R2RDump"; private const string R2RDumpFile = "R2RDump.dll"; private const string CoreRunFileName = "corerun"; public static string FindExePath(string exe) { if (OperatingSystem.IsWindows()) { exe = exe + ".exe"; } exe = Environment.ExpandEnvironmentVariables(exe); if (!File.Exists(exe)) { if (Path.GetDirectoryName(exe) == String.Empty) { foreach (string test in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator)) { string path = test.Trim(); if (!String.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, exe))) return Path.GetFullPath(path); } } throw new FileNotFoundException(new FileNotFoundException().Message, exe); } return Path.GetFullPath(exe); } [Fact] [SkipOnMono("Ready-To-Run is a CoreCLR-only feature", TestPlatforms.Any)] public static void DumpCoreLib() { string CoreRootVar = Environment.GetEnvironmentVariable(CoreRoot); bool IsUnix = !OperatingSystem.IsWindows(); string R2RDumpAbsolutePath = Path.Combine(CoreRootVar, R2RDumpRelativePath, R2RDumpFile); string CoreLibFile = "System.Private.CoreLib.dll"; string CoreLibAbsolutePath = Path.Combine(CoreRootVar, CoreLibFile); string OutputFile = Path.GetTempFileName(); string TestDotNetCmdVar = Environment.GetEnvironmentVariable("__TestDotNetCmd"); // Unset COMPlus_GCName since standalone GC doesnt exist in official "dotnet" deployment Environment.SetEnvironmentVariable("COMPlus_GCName", String.Empty); string DotNetAbsolutePath = string.IsNullOrEmpty(TestDotNetCmdVar) ? FindExePath("dotnet") : TestDotNetCmdVar; ProcessStartInfo processStartInfo = new ProcessStartInfo { UseShellExecute = false, FileName = DotNetAbsolutePath, // TODO, what flags do we like to test? Arguments = string.Join(" ", new string[]{"exec", R2RDumpAbsolutePath, "--in", CoreLibAbsolutePath, "--out", OutputFile}) }; Process process = Process.Start(processStartInfo); process.WaitForExit(); int exitCode = process.ExitCode; string outputContent = File.ReadAllText(OutputFile); File.Delete(OutputFile); // TODO, here is a point where we can add more validation to outputs // An uncaught exception (such as signature decoding error, would be caught by the error code) bool failed = exitCode != 0; if (failed) { Console.WriteLine("The process terminated with exit code {0}", exitCode); Console.WriteLine(outputContent); Assert.True(!failed); } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/HardwareIntrinsics/General/Vector256/Create.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\General\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 CreateDouble() { var test = new VectorCreate__CreateDouble(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorCreate__CreateDouble { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Double value = TestLibrary.Generator.GetDouble(); Vector256<Double> result = Vector256.Create(value); ValidateResult(result, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Double value = TestLibrary.Generator.GetDouble(); object result = typeof(Vector256) .GetMethod(nameof(Vector256.Create), new Type[] { typeof(Double) }) .Invoke(null, new object[] { value }); ValidateResult((Vector256<Double>)(result), value); } private void ValidateResult(Vector256<Double> result, Double expectedValue, [CallerMemberName] string method = "") { Double[] resultElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref resultElements[0]), result); ValidateResult(resultElements, expectedValue, method); } private void ValidateResult(Double[] resultElements, Double expectedValue, [CallerMemberName] string method = "") { bool succeeded = true; if (resultElements[0] != expectedValue) { succeeded = false; } else { for (var i = 1; i < ElementCount; i++) { if (resultElements[i] != expectedValue) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256.Create(Double): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: {expectedValue}"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); 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\General\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 CreateDouble() { var test = new VectorCreate__CreateDouble(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorCreate__CreateDouble { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Double value = TestLibrary.Generator.GetDouble(); Vector256<Double> result = Vector256.Create(value); ValidateResult(result, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Double value = TestLibrary.Generator.GetDouble(); object result = typeof(Vector256) .GetMethod(nameof(Vector256.Create), new Type[] { typeof(Double) }) .Invoke(null, new object[] { value }); ValidateResult((Vector256<Double>)(result), value); } private void ValidateResult(Vector256<Double> result, Double expectedValue, [CallerMemberName] string method = "") { Double[] resultElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref resultElements[0]), result); ValidateResult(resultElements, expectedValue, method); } private void ValidateResult(Double[] resultElements, Double expectedValue, [CallerMemberName] string method = "") { bool succeeded = true; if (resultElements[0] != expectedValue) { succeeded = false; } else { for (var i = 1; i < ElementCount; i++) { if (resultElements[i] != expectedValue) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256.Create(Double): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: {expectedValue}"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/VariableAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Xml.XPath; namespace System.Xml.Xsl.XsltOld { internal enum VariableType { GlobalVariable, GlobalParameter, LocalVariable, LocalParameter, WithParameter, } internal class VariableAction : ContainerAction, IXsltContextVariable { public static object BeingComputedMark = new object(); private const int ValueCalculated = 2; protected XmlQualifiedName? name; protected string? nameStr; protected string? baseUri; protected int selectKey = Compiler.InvalidQueryKey; protected int stylesheetid; protected VariableType varType; private int _varKey; internal int Stylesheetid { get { return this.stylesheetid; } } internal XmlQualifiedName? Name { get { return this.name; } } internal string? NameStr { get { return this.nameStr; } } internal VariableType VarType { get { return this.varType; } } internal int VarKey { get { return _varKey; } } internal bool IsGlobal { get { return this.varType == VariableType.GlobalVariable || this.varType == VariableType.GlobalParameter; } } internal VariableAction(VariableType type) { this.varType = type; } internal override void Compile(Compiler compiler) { this.stylesheetid = compiler.Stylesheetid; this.baseUri = compiler.Input.BaseURI; CompileAttributes(compiler); CheckRequiredAttribute(compiler, this.name, "name"); if (compiler.Recurse()) { CompileTemplate(compiler); compiler.ToParent(); if (this.selectKey != Compiler.InvalidQueryKey && this.containedActions != null) { throw XsltException.Create(SR.Xslt_VariableCntSel2, this.nameStr); } } if (this.containedActions != null) { baseUri = $"{baseUri}#{compiler.GetUnicRtfId()}"; } else { baseUri = null; } _varKey = compiler.InsertVariable(this); } internal override bool CompileAttribute(Compiler compiler) { string name = compiler.Input.LocalName; string value = compiler.Input.Value; if (Ref.Equal(name, compiler.Atoms.Name)) { Debug.Assert(this.name == null && this.nameStr == null); this.nameStr = value; this.name = compiler.CreateXPathQName(this.nameStr); } else if (Ref.Equal(name, compiler.Atoms.Select)) { this.selectKey = compiler.AddQuery(value); } else { return false; } return true; } internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null && frame.State != ValueCalculated); object? value = null; switch (frame.State) { case Initialized: if (IsGlobal) { if (frame.GetVariable(_varKey) != null) { // This var was calculated already frame.Finished(); break; } // Mark that the variable is being computed to check for circular references frame.SetVariable(_varKey, BeingComputedMark); } // If this is a parameter, check whether the caller has passed the value if (this.varType == VariableType.GlobalParameter) { value = processor.GetGlobalParameter(this.name!); } else if (this.varType == VariableType.LocalParameter) { value = processor.GetParameter(this.name!); } if (value != null) { goto case ValueCalculated; } // If value was not passed, check the 'select' attribute if (this.selectKey != Compiler.InvalidQueryKey) { value = processor.RunQuery(frame, this.selectKey); goto case ValueCalculated; } // If there is no 'select' attribute and the content is empty, use the empty string if (this.containedActions == null) { value = string.Empty; goto case ValueCalculated; } // RTF case NavigatorOutput output = new NavigatorOutput(this.baseUri!); processor.PushOutput(output); processor.PushActionFrame(frame); frame.State = ProcessingChildren; break; case ProcessingChildren: IRecordOutput recOutput = processor.PopOutput(); Debug.Assert(recOutput is NavigatorOutput); value = ((NavigatorOutput)recOutput).Navigator; goto case ValueCalculated; case ValueCalculated: Debug.Assert(value != null); frame.SetVariable(_varKey, value); frame.Finished(); break; default: Debug.Fail("Invalid execution state inside VariableAction.Execute"); break; } } // ---------------------- IXsltContextVariable -------------------- XPathResultType IXsltContextVariable.VariableType { get { return XPathResultType.Any; } } object IXsltContextVariable.Evaluate(XsltContext xsltContext) { return ((XsltCompileContext)xsltContext).EvaluateVariable(this); } bool IXsltContextVariable.IsLocal { get { return this.varType == VariableType.LocalVariable || this.varType == VariableType.LocalParameter; } } bool IXsltContextVariable.IsParam { get { return this.varType == VariableType.LocalParameter || this.varType == VariableType.GlobalParameter; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Xml.XPath; namespace System.Xml.Xsl.XsltOld { internal enum VariableType { GlobalVariable, GlobalParameter, LocalVariable, LocalParameter, WithParameter, } internal class VariableAction : ContainerAction, IXsltContextVariable { public static object BeingComputedMark = new object(); private const int ValueCalculated = 2; protected XmlQualifiedName? name; protected string? nameStr; protected string? baseUri; protected int selectKey = Compiler.InvalidQueryKey; protected int stylesheetid; protected VariableType varType; private int _varKey; internal int Stylesheetid { get { return this.stylesheetid; } } internal XmlQualifiedName? Name { get { return this.name; } } internal string? NameStr { get { return this.nameStr; } } internal VariableType VarType { get { return this.varType; } } internal int VarKey { get { return _varKey; } } internal bool IsGlobal { get { return this.varType == VariableType.GlobalVariable || this.varType == VariableType.GlobalParameter; } } internal VariableAction(VariableType type) { this.varType = type; } internal override void Compile(Compiler compiler) { this.stylesheetid = compiler.Stylesheetid; this.baseUri = compiler.Input.BaseURI; CompileAttributes(compiler); CheckRequiredAttribute(compiler, this.name, "name"); if (compiler.Recurse()) { CompileTemplate(compiler); compiler.ToParent(); if (this.selectKey != Compiler.InvalidQueryKey && this.containedActions != null) { throw XsltException.Create(SR.Xslt_VariableCntSel2, this.nameStr); } } if (this.containedActions != null) { baseUri = $"{baseUri}#{compiler.GetUnicRtfId()}"; } else { baseUri = null; } _varKey = compiler.InsertVariable(this); } internal override bool CompileAttribute(Compiler compiler) { string name = compiler.Input.LocalName; string value = compiler.Input.Value; if (Ref.Equal(name, compiler.Atoms.Name)) { Debug.Assert(this.name == null && this.nameStr == null); this.nameStr = value; this.name = compiler.CreateXPathQName(this.nameStr); } else if (Ref.Equal(name, compiler.Atoms.Select)) { this.selectKey = compiler.AddQuery(value); } else { return false; } return true; } internal override void Execute(Processor processor, ActionFrame frame) { Debug.Assert(processor != null && frame != null && frame.State != ValueCalculated); object? value = null; switch (frame.State) { case Initialized: if (IsGlobal) { if (frame.GetVariable(_varKey) != null) { // This var was calculated already frame.Finished(); break; } // Mark that the variable is being computed to check for circular references frame.SetVariable(_varKey, BeingComputedMark); } // If this is a parameter, check whether the caller has passed the value if (this.varType == VariableType.GlobalParameter) { value = processor.GetGlobalParameter(this.name!); } else if (this.varType == VariableType.LocalParameter) { value = processor.GetParameter(this.name!); } if (value != null) { goto case ValueCalculated; } // If value was not passed, check the 'select' attribute if (this.selectKey != Compiler.InvalidQueryKey) { value = processor.RunQuery(frame, this.selectKey); goto case ValueCalculated; } // If there is no 'select' attribute and the content is empty, use the empty string if (this.containedActions == null) { value = string.Empty; goto case ValueCalculated; } // RTF case NavigatorOutput output = new NavigatorOutput(this.baseUri!); processor.PushOutput(output); processor.PushActionFrame(frame); frame.State = ProcessingChildren; break; case ProcessingChildren: IRecordOutput recOutput = processor.PopOutput(); Debug.Assert(recOutput is NavigatorOutput); value = ((NavigatorOutput)recOutput).Navigator; goto case ValueCalculated; case ValueCalculated: Debug.Assert(value != null); frame.SetVariable(_varKey, value); frame.Finished(); break; default: Debug.Fail("Invalid execution state inside VariableAction.Execute"); break; } } // ---------------------- IXsltContextVariable -------------------- XPathResultType IXsltContextVariable.VariableType { get { return XPathResultType.Any; } } object IXsltContextVariable.Evaluate(XsltContext xsltContext) { return ((XsltCompileContext)xsltContext).EvaluateVariable(this); } bool IXsltContextVariable.IsLocal { get { return this.varType == VariableType.LocalVariable || this.varType == VariableType.LocalParameter; } } bool IXsltContextVariable.IsParam { get { return this.varType == VariableType.LocalParameter || this.varType == VariableType.GlobalParameter; } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.String.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // --------------------------------------------------------------------------- // Native Format Reader // // UTF8 string reading methods // --------------------------------------------------------------------------- using System; using System.Text; namespace Internal.NativeFormat { internal partial struct NativeParser { public string GetString() { string value; _offset = _reader.DecodeString(_offset, out value); return value; } public void SkipString() { _offset = _reader.SkipString(_offset); } } internal partial class NativeReader { public string ReadString(uint offset) { string value; DecodeString(offset, out value); return value; } public unsafe uint DecodeString(uint offset, out string value) { uint numBytes; offset = DecodeUnsigned(offset, out numBytes); if (numBytes == 0) { value = string.Empty; return offset; } uint endOffset = offset + numBytes; if (endOffset < numBytes || endOffset > _size) ThrowBadImageFormatException(); #if NETFX_45 byte[] bytes = new byte[numBytes]; for (int i = 0; i < bytes.Length; i++) bytes[i] = *(_base + offset + i); value = Encoding.UTF8.GetString(bytes, 0, bytes.Length); #else value = Encoding.UTF8.GetString(_base + offset, (int)numBytes); #endif return endOffset; } // Decode a string, but just skip it instead of returning it public uint SkipString(uint offset) { uint numBytes; offset = DecodeUnsigned(offset, out numBytes); if (numBytes == 0) { return offset; } uint endOffset = offset + numBytes; if (endOffset < numBytes || endOffset > _size) ThrowBadImageFormatException(); return endOffset; } public unsafe bool StringEquals(uint offset, string value) { uint originalOffset = offset; uint numBytes; offset = DecodeUnsigned(offset, out numBytes); uint endOffset = offset + numBytes; if (endOffset < numBytes || offset > _size) ThrowBadImageFormatException(); if (numBytes < value.Length) return false; for (int i = 0; i < value.Length; i++) { int ch = *(_base + offset + i); if (ch > 0x7F) return ReadString(originalOffset) == value; // We are assuming here that valid UTF8 encoded byte > 0x7F cannot map to a character with code point <= 0x7F if (ch != value[i]) return false; } return numBytes == value.Length; // All char ANSI, all matching } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // --------------------------------------------------------------------------- // Native Format Reader // // UTF8 string reading methods // --------------------------------------------------------------------------- using System; using System.Text; namespace Internal.NativeFormat { internal partial struct NativeParser { public string GetString() { string value; _offset = _reader.DecodeString(_offset, out value); return value; } public void SkipString() { _offset = _reader.SkipString(_offset); } } internal partial class NativeReader { public string ReadString(uint offset) { string value; DecodeString(offset, out value); return value; } public unsafe uint DecodeString(uint offset, out string value) { uint numBytes; offset = DecodeUnsigned(offset, out numBytes); if (numBytes == 0) { value = string.Empty; return offset; } uint endOffset = offset + numBytes; if (endOffset < numBytes || endOffset > _size) ThrowBadImageFormatException(); #if NETFX_45 byte[] bytes = new byte[numBytes]; for (int i = 0; i < bytes.Length; i++) bytes[i] = *(_base + offset + i); value = Encoding.UTF8.GetString(bytes, 0, bytes.Length); #else value = Encoding.UTF8.GetString(_base + offset, (int)numBytes); #endif return endOffset; } // Decode a string, but just skip it instead of returning it public uint SkipString(uint offset) { uint numBytes; offset = DecodeUnsigned(offset, out numBytes); if (numBytes == 0) { return offset; } uint endOffset = offset + numBytes; if (endOffset < numBytes || endOffset > _size) ThrowBadImageFormatException(); return endOffset; } public unsafe bool StringEquals(uint offset, string value) { uint originalOffset = offset; uint numBytes; offset = DecodeUnsigned(offset, out numBytes); uint endOffset = offset + numBytes; if (endOffset < numBytes || offset > _size) ThrowBadImageFormatException(); if (numBytes < value.Length) return false; for (int i = 0; i < value.Length; i++) { int ch = *(_base + offset + i); if (ch > 0x7F) return ReadString(originalOffset) == value; // We are assuming here that valid UTF8 encoded byte > 0x7F cannot map to a character with code point <= 0x7F if (ch != value[i]) return false; } return numBytes == value.Length; // All char ANSI, all matching } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Runtime.InteropServices/src/System/Runtime/InteropServices/ComTypes/DVASPECT.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; namespace System.Runtime.InteropServices.ComTypes { [EditorBrowsable(EditorBrowsableState.Never)] [Flags] public enum DVASPECT { DVASPECT_CONTENT = 1, DVASPECT_THUMBNAIL = 2, DVASPECT_ICON = 4, DVASPECT_DOCPRINT = 8 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; namespace System.Runtime.InteropServices.ComTypes { [EditorBrowsable(EditorBrowsableState.Never)] [Flags] public enum DVASPECT { DVASPECT_CONTENT = 1, DVASPECT_THUMBNAIL = 2, DVASPECT_ICON = 4, DVASPECT_DOCPRINT = 8 } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Performance/CodeQuality/Benchstones/MDBenchF/MDLLoops/MDLLoops.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // C# adaptation of C implementation of Livermore Loops Fortran benchmark. /* Livermore Loops coded in C Latest File Modification 20 Oct 92, * by Tim Peters, Kendall Square Res. Corp. [email protected], [email protected] * SUBROUTINE KERNEL( TK) replaces the Fortran routine in LFK Test program. ************************************************************************ * * * KERNEL executes 24 samples of "C" computation * * * * TK(1) - total cpu time to execute only the 24 kernels.* * TK(2) - total Flops executed by the 24 Kernels * * * ************************************************************************ * * * L. L. N. L. " C " K E R N E L S: M F L O P S * * * * These kernels measure " C " numerical computation * * rates for a spectrum of cpu-limited computational * * structures or benchmarks. Mathematical through-put * * is measured in units of millions of floating-point * * operations executed per second, called Megaflops/sec. * * * * Fonzi's Law: There is not now and there never will be a language * * in which it is the least bit difficult to write * * bad programs. * * F.H.MCMAHON 1972 * ************************************************************************ *Originally from Greg Astfalk, AT&T, P.O.Box 900, Princeton, NJ. 08540* * by way of Frank McMahon (LLNL). * * * * REFERENCE * * * * F.H.McMahon, The Livermore Fortran Kernels: * * A Computer Test Of The Numerical Performance Range, * * Lawrence Livermore National Laboratory, * * Livermore, California, UCRL-53745, December 1986. * * * * from: National Technical Information Service * * U.S. Department of Commerce * * 5285 Port Royal Road * * Springfield, VA. 22161 * * * * Changes made to correct many array subscripting problems, * * make more readable (added #define's), include the original * * FORTRAN versions of the runs as comments, and make more * * portable by Kelly O'Hair (LLNL) and Chuck Rasbold (LLNL). * * * ************************************************************************ */ using System; using System.Runtime.CompilerServices; namespace Benchstone.MDBenchF { public class MDLLoops { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 4000; #endif private const double MaxErr = 1.0e-6; private double[] _x = new double[1002]; private double[] _y = new double[1002]; private double[] _z = new double[1002]; private double[] _u = new double[501]; private double[,] _px; private double[,] _cx; private double[,,] _u1; private double[,,] _u2; private double[,,] _u3; private double[,] _b; private double[] _bnk1 = new double[6]; private double[,] _c; private double[] _bnk2 = new double[6]; private double[,] _p; private double[] _bnk3 = new double[6]; private double[,] _h; private double[] _bnk4 = new double[6]; private double[] _bnk5 = new double[6]; private double[] _ex = new double[68]; private double[] _rh = new double[68]; private double[] _dex = new double[68]; private double[] _vx = new double[151]; private double[] _xx = new double[151]; private double[] _grd = new double[151]; private int[] _e = new int[193]; private int[] _f = new int[193]; private int[] _nrops = { 0, 5, 10, 2, 2, 2, 2, 16, 36, 17, 9, 1, 1, 7, 11 }; private int[] _loops = { 0, 400, 200, 1000, 510, 1000, 1000, 120, 40, 100, 100, 1000, 1000, 128, 150 }; private double[] _checks = { 0, 0.811986948148e+07, 0.356310000000e+03, 0.356310000000e+03, -0.402412007078e+05, 0.136579037764e+06, 0.419716278716e+06, 0.429449847526e+07, 0.314064400000e+06, 0.182709000000e+07, -0.140415250000e+09, 0.374895020500e+09, 0.000000000000e+00, 0.171449024000e+06, -0.510829560800e+07 }; public static volatile object VolatileObject; [MethodImpl(MethodImplOptions.NoInlining)] private static void Escape(object obj) { VolatileObject = obj; } [MethodImpl(MethodImplOptions.NoInlining)] private bool Bench() { _px = new double[16, 101]; _cx = new double[16, 101]; _u1 = new double[6, 23, 3]; _u2 = new double[6, 23, 3]; _u3 = new double[6, 23, 3]; _b = new double[65, 9]; _c = new double[65, 9]; _h = new double[65, 9]; _p = new double[5, 513]; for (int i = 0; i < Iterations; i++) { Main1(i < Iterations - 1 ? 0 : 1); } return true; } private static int Clock() { return 0; } private void Main1(int output) { int nt, lw, nl1, nl2; int i, i1, i2, ip, ir, ix, j, j1, j2, k, kx, ky, l, m; double[] ts = new double[21]; double[] rt = new double[21]; double[] rpm = new double[21]; double[] cksum = new double[21]; double r, t, a11, a12, a13, sig, a21, a22, a23, a31, a32, a33; double b28, b27, b26, b25, b24, b23, b22, c0, flx, rx1; double q, s, scale, uu, du1, du2, du3, ar, br, cr, xi, ri; int[] mops = new int[20]; for (i = 1; i <= 20; i++) { cksum[i] = 0.0; } r = 4.86; t = 276.0; a11 = 0.5; a12 = 0.33; a13 = 0.25; sig = 0.8; a21 = 0.20; a22 = 0.167; a23 = 0.141; a31 = 0.125; a32 = 0.111; a33 = 0.10; b28 = 0.1; b27 = 0.2; b26 = 0.3; b25 = 0.4; b24 = 0.5; b23 = 0.6; b22 = 0.7; c0 = 0.8; flx = 4.689; rx1 = 64.0; /* * end of initialization -- begin timing */ /* loop 1 hydro excerpt */ Init(); ts[1] = (double)Clock(); q = 0.0; for (k = 1; k <= 400; k++) { _x[k] = q + _y[k] * (r * _z[k + 10] + t * _z[k + 11]); } ts[1] = (double)Clock() - ts[1]; for (k = 1; k <= 400; k++) { cksum[1] += (double)k * _x[k]; } /* loop 2 mlr, inner product */ Init(); ts[2] = (double)Clock(); q = 0.0; for (k = 1; k <= 996; k += 5) { q += _z[k] * _x[k] + _z[k + 1] * _x[k + 1] + _z[k + 2] * _x[k + 2] + _z[k + 3] * _x[k + 3] + _z[k + 4] * _x[k + 4]; } ts[2] = (double)Clock() - ts[2]; cksum[2] = q; /* loop 3 inner prod */ Init(); ts[3] = (double)Clock(); q = 0.0; for (k = 1; k <= 1000; k++) { q += _z[k] * _x[k]; } ts[3] = (double)Clock() - ts[3]; cksum[3] = q; /* loop 4 banded linear equarions */ Init(); ts[4] = (double)Clock(); for (l = 7; l <= 107; l += 50) { lw = l; for (j = 30; j <= 870; j += 5) { _x[l - 1] -= _x[lw++] * _y[j]; } _x[l - 1] = _y[5] * _x[l - 1]; } ts[4] = (double)Clock() - ts[4]; for (l = 7; l <= 107; l += 50) { cksum[4] += (double)l * _x[l - 1]; } /* loop 5 tri-diagonal elimination, below diagonal */ Init(); ts[5] = (double)Clock(); for (i = 2; i <= 998; i += 3) { _x[i] = _z[i] * (_y[i] - _x[i - 1]); _x[i + 1] = _z[i + 1] * (_y[i + 1] - _x[i]); _x[i + 2] = _z[i + 2] * (_y[i + 2] - _x[i + 1]); } ts[5] = (double)Clock() - ts[5]; for (i = 2; i <= 1000; i++) { cksum[5] += (double)i * _x[i]; } /* loop 6 tri-diagonal elimination, above diagonal */ Init(); ts[6] = (double)Clock(); for (j = 3; j <= 999; j += 3) { i = 1003 - j; _x[i] = _x[i] - _z[i] * _x[i + 1]; _x[i - 1] = _x[i - 1] - _z[i - 1] * _x[i]; _x[i - 2] = _x[i - 2] - _z[i - 2] * _x[i - 1]; } ts[6] = (double)Clock() - ts[6]; for (j = 1; j <= 999; j++) { l = 1001 - j; cksum[6] += (double)j * _x[l]; } /* loop 7 equation of state excerpt */ Init(); ts[7] = (double)Clock(); for (m = 1; m <= 120; m++) { _x[m] = _u[m] + r * (_z[m] + r * _y[m]) + t * (_u[m + 3] + r * (_u[m + 2] + r * _u[m + 1]) + t * (_u[m + 6] + r * (_u[m + 5] + r * _u[m + 4]))); } ts[7] = (double)Clock() - ts[7]; for (m = 1; m <= 120; m++) { cksum[7] += (double)m * _x[m]; } /* loop 8 p.d.e. integration */ Init(); ts[8] = (double)Clock(); nl1 = 1; nl2 = 2; for (kx = 2; kx <= 3; kx++) { for (ky = 2; ky <= 21; ky++) { du1 = _u1[kx,ky + 1,nl1] - _u1[kx,ky - 1,nl1]; du2 = _u2[kx,ky + 1,nl1] - _u2[kx,ky - 1,nl1]; du3 = _u3[kx,ky + 1,nl1] - _u3[kx,ky - 1,nl1]; _u1[kx,ky,nl2] = _u1[kx,ky,nl1] + a11 * du1 + a12 * du2 + a13 * du3 + sig * (_u1[kx + 1,ky,nl1] - 2.0 * _u1[kx,ky,nl1] + _u1[kx - 1,ky,nl1]); _u2[kx,ky,nl2] = _u2[kx,ky,nl1] + a21 * du1 + a22 * du2 + a23 * du3 + sig * (_u2[kx + 1,ky,nl1] - 2.0 * _u2[kx,ky,nl1] + _u2[kx - 1,ky,nl1]); _u3[kx,ky,nl2] = _u3[kx,ky,nl1] + a31 * du1 + a32 * du2 + a33 * du3 + sig * (_u3[kx + 1,ky,nl1] - 2.0 * _u3[kx,ky,nl1] + _u3[kx - 1,ky,nl1]); } } ts[8] = (double)Clock() - ts[8]; for (i = 1; i <= 2; i++) { for (kx = 2; kx <= 3; kx++) { for (ky = 2; ky <= 21; ky++) { cksum[8] += (double)kx * (double)ky * (double)i * (_u1[kx,ky,i] + _u2[kx,ky,i] + _u3[kx,ky,i]); } } } /* loop 9 integrate predictors */ Init(); ts[9] = (double)Clock(); for (i = 1; i <= 100; i++) { _px[1,i] = b28 * _px[13,i] + b27 * _px[12,i] + b26 * _px[11,i] + b25 * _px[10,i] + b24 * _px[9,i] + b23 * _px[8,i] + b22 * _px[7,i] + c0 * (_px[5,i] + _px[6,i]) + _px[3,i]; } ts[9] = (double)Clock() - ts[9]; for (i = 1; i <= 100; i++) { cksum[9] += (double)i * _px[1,i]; } /* loop 10 difference predictors */ Init(); ts[10] = (double)Clock(); for (i = 1; i <= 100; i++) { ar = _cx[5,i]; br = ar - _px[5,i]; _px[5,i] = ar; cr = br - _px[6,i]; _px[6,i] = br; ar = cr - _px[7,i]; _px[7,i] = cr; br = ar - _px[8,i]; _px[8,i] = ar; cr = br - _px[9,i]; _px[9,i] = br; ar = cr - _px[10,i]; _px[10,i] = cr; br = ar - _px[11,i]; _px[11,i] = ar; cr = br - _px[12,i]; _px[12,i] = br; _px[14,i] = cr - _px[13,i]; _px[13,i] = cr; } ts[10] = (double)Clock() - ts[10]; for (i = 1; i <= 100; i++) { for (k = 5; k <= 14; k++) { cksum[10] += (double)k * (double)i * _px[k,i]; } } /* loop 11 first sum. */ Init(); ts[11] = (double)Clock(); _x[1] = _y[1]; for (k = 2; k <= 1000; k++) { _x[k] = _x[k - 1] + _y[k]; } ts[11] = (double)Clock() - ts[11]; for (k = 1; k <= 1000; k++) { cksum[11] += (double)k * _x[k]; } /* loop 12 first diff. */ Init(); ts[12] = (double)Clock(); for (k = 1; k <= 999; k++) { _x[k] = _y[k + 1] - _y[k]; } ts[12] = (double)Clock() - ts[12]; for (k = 1; k <= 999; k++) { cksum[12] += (double)k * _x[k]; } /* loop 13 2-d particle pusher */ Init(); ts[13] = (double)Clock(); for (ip = 1; ip <= 128; ip++) { i1 = (int)_p[1,ip]; j1 = (int)_p[2,ip]; _p[3,ip] += _b[i1,j1]; _p[4,ip] += _c[i1,j1]; _p[1,ip] += _p[3,ip]; _p[2,ip] += _p[4,ip]; // Each element of m_p, m_b and m_c is initialized to 1.00025 in Init(). // From the assignments above, // i2 = m_p[1,ip] = m_p[1,ip] + m_p[3,ip] = m_p[1,ip] + m_p[3,ip] + m_b[i1,j1] = 1 + 1 + 1 = 3 // j2 = m_p[2,ip] = m_p[2,ip] + m_p[4,ip] = m_p[2,ip] + m_p[4,ip] + m_c[i1,j1] = 1 + 1 + 1 = 3 i2 = (int)_p[1,ip]; j2 = (int)_p[2,ip]; // Accessing m_y, m_z upto 35 _p[1,ip] += _y[i2 + 32]; _p[2,ip] += _z[j2 + 32]; i2 += _e[i2 + 32]; j2 += _f[j2 + 32]; _h[i2,j2] += 1.0; } ts[13] = (double)Clock() - ts[13]; for (ip = 1; ip <= 128; ip++) { cksum[13] += (double)ip * (_p[3,ip] + _p[4,ip] + _p[1,ip] + _p[2,ip]); } for (k = 1; k <= 64; k++) { for (ix = 1; ix <= 8; ix++) { cksum[13] += (double)k * (double)ix * _h[k,ix]; } } /* loop 14 1-d particle pusher */ Init(); ts[14] = (double)Clock(); for (k = 1; k <= 150; k++) { // m_grd[150] = 13.636 // Therefore ix <= 13 ix = (int)_grd[k]; xi = (double)ix; _vx[k] += _ex[ix] + (_xx[k] - xi) * _dex[ix]; _xx[k] += _vx[k] + flx; ir = (int)_xx[k]; ri = (double)ir; rx1 = _xx[k] - ri; ir = System.Math.Abs(ir % 64); _xx[k] = ri + rx1; // ir < 64 since ir = ir % 64 // So m_rh is accessed upto 64 _rh[ir] += 1.0 - rx1; _rh[ir + 1] += rx1; } ts[14] = (double)Clock() - ts[14]; for (k = 1; k <= 150; k++) { cksum[14] += (double)k * (_vx[k] + _xx[k]); } for (k = 1; k <= 67; k++) { cksum[14] += (double)k * _rh[k]; } /* time the clock call */ ts[15] = (double)Clock(); ts[15] = (double)Clock() - ts[15]; /* scale= set to convert time to micro-seconds */ scale = 1.0; rt[15] = ts[15] * scale; nt = 14; t = s = uu = 0.0; for (k = 1; k <= nt; k++) { rt[k] = (ts[k] - ts[15]) * scale; t += rt[k]; mops[k] = _nrops[k] * _loops[k]; s += (double)mops[k]; rpm[k] = 0.0; if (rt[k] != 0.0) { rpm[k] = (double)mops[k] / rt[k]; } uu += rpm[k]; } uu /= (double)nt; s /= t; // Ensure that the array elements are live-out Escape(ts); Escape(rt); Escape(rpm); Escape(cksum); Escape(mops); } private void Init() { int j, k, l; for (k = 1; k <= 1000; k++) { _x[k] = 1.11; _y[k] = 1.123; _z[k] = 0.321; } for (k = 1; k <= 500; k++) { _u[k] = 0.00025; } for (k = 1; k <= 15; k++) { for (l = 1; l <= 100; l++) { _px[k,l] = l; _cx[k,l] = l; } } for (j = 1; j < 6; j++) { for (k = 1; k < 23; k++) { for (l = 1; l < 3; l++) { _u1[j,k,l] = k; _u2[j,k,l] = k + k; _u3[j,k,l] = k + k + k; } } } for (j = 1; j < 65; j++) { for (k = 1; k < 9; k++) { _b[j,k] = 1.00025; _c[j,k] = 1.00025; _h[j,k] = 1.00025; } } for (j = 1; j < 6; j++) { _bnk1[j] = j * 100; _bnk2[j] = j * 110; _bnk3[j] = j * 120; _bnk4[j] = j * 130; _bnk5[j] = j * 140; } for (j = 1; j < 5; j++) { for (k = 1; k < 513; k++) { _p[j,k] = 1.00025; } } for (j = 1; j < 193; j++) { _e[j] = _f[j] = 1; } for (j = 1; j < 68; j++) { _ex[j] = _rh[j] = _dex[j] = (double)j; } for (j = 1; j < 151; j++) { _vx[j] = 0.001; _xx[j] = 0.001; _grd[j] = (double)(j / 8 + 3); } } private bool TestBase() { bool result = Bench(); return result; } public static int Main() { var lloops = new MDLLoops(); bool result = lloops.TestBase(); return (result ? 100 : -1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // C# adaptation of C implementation of Livermore Loops Fortran benchmark. /* Livermore Loops coded in C Latest File Modification 20 Oct 92, * by Tim Peters, Kendall Square Res. Corp. [email protected], [email protected] * SUBROUTINE KERNEL( TK) replaces the Fortran routine in LFK Test program. ************************************************************************ * * * KERNEL executes 24 samples of "C" computation * * * * TK(1) - total cpu time to execute only the 24 kernels.* * TK(2) - total Flops executed by the 24 Kernels * * * ************************************************************************ * * * L. L. N. L. " C " K E R N E L S: M F L O P S * * * * These kernels measure " C " numerical computation * * rates for a spectrum of cpu-limited computational * * structures or benchmarks. Mathematical through-put * * is measured in units of millions of floating-point * * operations executed per second, called Megaflops/sec. * * * * Fonzi's Law: There is not now and there never will be a language * * in which it is the least bit difficult to write * * bad programs. * * F.H.MCMAHON 1972 * ************************************************************************ *Originally from Greg Astfalk, AT&T, P.O.Box 900, Princeton, NJ. 08540* * by way of Frank McMahon (LLNL). * * * * REFERENCE * * * * F.H.McMahon, The Livermore Fortran Kernels: * * A Computer Test Of The Numerical Performance Range, * * Lawrence Livermore National Laboratory, * * Livermore, California, UCRL-53745, December 1986. * * * * from: National Technical Information Service * * U.S. Department of Commerce * * 5285 Port Royal Road * * Springfield, VA. 22161 * * * * Changes made to correct many array subscripting problems, * * make more readable (added #define's), include the original * * FORTRAN versions of the runs as comments, and make more * * portable by Kelly O'Hair (LLNL) and Chuck Rasbold (LLNL). * * * ************************************************************************ */ using System; using System.Runtime.CompilerServices; namespace Benchstone.MDBenchF { public class MDLLoops { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 4000; #endif private const double MaxErr = 1.0e-6; private double[] _x = new double[1002]; private double[] _y = new double[1002]; private double[] _z = new double[1002]; private double[] _u = new double[501]; private double[,] _px; private double[,] _cx; private double[,,] _u1; private double[,,] _u2; private double[,,] _u3; private double[,] _b; private double[] _bnk1 = new double[6]; private double[,] _c; private double[] _bnk2 = new double[6]; private double[,] _p; private double[] _bnk3 = new double[6]; private double[,] _h; private double[] _bnk4 = new double[6]; private double[] _bnk5 = new double[6]; private double[] _ex = new double[68]; private double[] _rh = new double[68]; private double[] _dex = new double[68]; private double[] _vx = new double[151]; private double[] _xx = new double[151]; private double[] _grd = new double[151]; private int[] _e = new int[193]; private int[] _f = new int[193]; private int[] _nrops = { 0, 5, 10, 2, 2, 2, 2, 16, 36, 17, 9, 1, 1, 7, 11 }; private int[] _loops = { 0, 400, 200, 1000, 510, 1000, 1000, 120, 40, 100, 100, 1000, 1000, 128, 150 }; private double[] _checks = { 0, 0.811986948148e+07, 0.356310000000e+03, 0.356310000000e+03, -0.402412007078e+05, 0.136579037764e+06, 0.419716278716e+06, 0.429449847526e+07, 0.314064400000e+06, 0.182709000000e+07, -0.140415250000e+09, 0.374895020500e+09, 0.000000000000e+00, 0.171449024000e+06, -0.510829560800e+07 }; public static volatile object VolatileObject; [MethodImpl(MethodImplOptions.NoInlining)] private static void Escape(object obj) { VolatileObject = obj; } [MethodImpl(MethodImplOptions.NoInlining)] private bool Bench() { _px = new double[16, 101]; _cx = new double[16, 101]; _u1 = new double[6, 23, 3]; _u2 = new double[6, 23, 3]; _u3 = new double[6, 23, 3]; _b = new double[65, 9]; _c = new double[65, 9]; _h = new double[65, 9]; _p = new double[5, 513]; for (int i = 0; i < Iterations; i++) { Main1(i < Iterations - 1 ? 0 : 1); } return true; } private static int Clock() { return 0; } private void Main1(int output) { int nt, lw, nl1, nl2; int i, i1, i2, ip, ir, ix, j, j1, j2, k, kx, ky, l, m; double[] ts = new double[21]; double[] rt = new double[21]; double[] rpm = new double[21]; double[] cksum = new double[21]; double r, t, a11, a12, a13, sig, a21, a22, a23, a31, a32, a33; double b28, b27, b26, b25, b24, b23, b22, c0, flx, rx1; double q, s, scale, uu, du1, du2, du3, ar, br, cr, xi, ri; int[] mops = new int[20]; for (i = 1; i <= 20; i++) { cksum[i] = 0.0; } r = 4.86; t = 276.0; a11 = 0.5; a12 = 0.33; a13 = 0.25; sig = 0.8; a21 = 0.20; a22 = 0.167; a23 = 0.141; a31 = 0.125; a32 = 0.111; a33 = 0.10; b28 = 0.1; b27 = 0.2; b26 = 0.3; b25 = 0.4; b24 = 0.5; b23 = 0.6; b22 = 0.7; c0 = 0.8; flx = 4.689; rx1 = 64.0; /* * end of initialization -- begin timing */ /* loop 1 hydro excerpt */ Init(); ts[1] = (double)Clock(); q = 0.0; for (k = 1; k <= 400; k++) { _x[k] = q + _y[k] * (r * _z[k + 10] + t * _z[k + 11]); } ts[1] = (double)Clock() - ts[1]; for (k = 1; k <= 400; k++) { cksum[1] += (double)k * _x[k]; } /* loop 2 mlr, inner product */ Init(); ts[2] = (double)Clock(); q = 0.0; for (k = 1; k <= 996; k += 5) { q += _z[k] * _x[k] + _z[k + 1] * _x[k + 1] + _z[k + 2] * _x[k + 2] + _z[k + 3] * _x[k + 3] + _z[k + 4] * _x[k + 4]; } ts[2] = (double)Clock() - ts[2]; cksum[2] = q; /* loop 3 inner prod */ Init(); ts[3] = (double)Clock(); q = 0.0; for (k = 1; k <= 1000; k++) { q += _z[k] * _x[k]; } ts[3] = (double)Clock() - ts[3]; cksum[3] = q; /* loop 4 banded linear equarions */ Init(); ts[4] = (double)Clock(); for (l = 7; l <= 107; l += 50) { lw = l; for (j = 30; j <= 870; j += 5) { _x[l - 1] -= _x[lw++] * _y[j]; } _x[l - 1] = _y[5] * _x[l - 1]; } ts[4] = (double)Clock() - ts[4]; for (l = 7; l <= 107; l += 50) { cksum[4] += (double)l * _x[l - 1]; } /* loop 5 tri-diagonal elimination, below diagonal */ Init(); ts[5] = (double)Clock(); for (i = 2; i <= 998; i += 3) { _x[i] = _z[i] * (_y[i] - _x[i - 1]); _x[i + 1] = _z[i + 1] * (_y[i + 1] - _x[i]); _x[i + 2] = _z[i + 2] * (_y[i + 2] - _x[i + 1]); } ts[5] = (double)Clock() - ts[5]; for (i = 2; i <= 1000; i++) { cksum[5] += (double)i * _x[i]; } /* loop 6 tri-diagonal elimination, above diagonal */ Init(); ts[6] = (double)Clock(); for (j = 3; j <= 999; j += 3) { i = 1003 - j; _x[i] = _x[i] - _z[i] * _x[i + 1]; _x[i - 1] = _x[i - 1] - _z[i - 1] * _x[i]; _x[i - 2] = _x[i - 2] - _z[i - 2] * _x[i - 1]; } ts[6] = (double)Clock() - ts[6]; for (j = 1; j <= 999; j++) { l = 1001 - j; cksum[6] += (double)j * _x[l]; } /* loop 7 equation of state excerpt */ Init(); ts[7] = (double)Clock(); for (m = 1; m <= 120; m++) { _x[m] = _u[m] + r * (_z[m] + r * _y[m]) + t * (_u[m + 3] + r * (_u[m + 2] + r * _u[m + 1]) + t * (_u[m + 6] + r * (_u[m + 5] + r * _u[m + 4]))); } ts[7] = (double)Clock() - ts[7]; for (m = 1; m <= 120; m++) { cksum[7] += (double)m * _x[m]; } /* loop 8 p.d.e. integration */ Init(); ts[8] = (double)Clock(); nl1 = 1; nl2 = 2; for (kx = 2; kx <= 3; kx++) { for (ky = 2; ky <= 21; ky++) { du1 = _u1[kx,ky + 1,nl1] - _u1[kx,ky - 1,nl1]; du2 = _u2[kx,ky + 1,nl1] - _u2[kx,ky - 1,nl1]; du3 = _u3[kx,ky + 1,nl1] - _u3[kx,ky - 1,nl1]; _u1[kx,ky,nl2] = _u1[kx,ky,nl1] + a11 * du1 + a12 * du2 + a13 * du3 + sig * (_u1[kx + 1,ky,nl1] - 2.0 * _u1[kx,ky,nl1] + _u1[kx - 1,ky,nl1]); _u2[kx,ky,nl2] = _u2[kx,ky,nl1] + a21 * du1 + a22 * du2 + a23 * du3 + sig * (_u2[kx + 1,ky,nl1] - 2.0 * _u2[kx,ky,nl1] + _u2[kx - 1,ky,nl1]); _u3[kx,ky,nl2] = _u3[kx,ky,nl1] + a31 * du1 + a32 * du2 + a33 * du3 + sig * (_u3[kx + 1,ky,nl1] - 2.0 * _u3[kx,ky,nl1] + _u3[kx - 1,ky,nl1]); } } ts[8] = (double)Clock() - ts[8]; for (i = 1; i <= 2; i++) { for (kx = 2; kx <= 3; kx++) { for (ky = 2; ky <= 21; ky++) { cksum[8] += (double)kx * (double)ky * (double)i * (_u1[kx,ky,i] + _u2[kx,ky,i] + _u3[kx,ky,i]); } } } /* loop 9 integrate predictors */ Init(); ts[9] = (double)Clock(); for (i = 1; i <= 100; i++) { _px[1,i] = b28 * _px[13,i] + b27 * _px[12,i] + b26 * _px[11,i] + b25 * _px[10,i] + b24 * _px[9,i] + b23 * _px[8,i] + b22 * _px[7,i] + c0 * (_px[5,i] + _px[6,i]) + _px[3,i]; } ts[9] = (double)Clock() - ts[9]; for (i = 1; i <= 100; i++) { cksum[9] += (double)i * _px[1,i]; } /* loop 10 difference predictors */ Init(); ts[10] = (double)Clock(); for (i = 1; i <= 100; i++) { ar = _cx[5,i]; br = ar - _px[5,i]; _px[5,i] = ar; cr = br - _px[6,i]; _px[6,i] = br; ar = cr - _px[7,i]; _px[7,i] = cr; br = ar - _px[8,i]; _px[8,i] = ar; cr = br - _px[9,i]; _px[9,i] = br; ar = cr - _px[10,i]; _px[10,i] = cr; br = ar - _px[11,i]; _px[11,i] = ar; cr = br - _px[12,i]; _px[12,i] = br; _px[14,i] = cr - _px[13,i]; _px[13,i] = cr; } ts[10] = (double)Clock() - ts[10]; for (i = 1; i <= 100; i++) { for (k = 5; k <= 14; k++) { cksum[10] += (double)k * (double)i * _px[k,i]; } } /* loop 11 first sum. */ Init(); ts[11] = (double)Clock(); _x[1] = _y[1]; for (k = 2; k <= 1000; k++) { _x[k] = _x[k - 1] + _y[k]; } ts[11] = (double)Clock() - ts[11]; for (k = 1; k <= 1000; k++) { cksum[11] += (double)k * _x[k]; } /* loop 12 first diff. */ Init(); ts[12] = (double)Clock(); for (k = 1; k <= 999; k++) { _x[k] = _y[k + 1] - _y[k]; } ts[12] = (double)Clock() - ts[12]; for (k = 1; k <= 999; k++) { cksum[12] += (double)k * _x[k]; } /* loop 13 2-d particle pusher */ Init(); ts[13] = (double)Clock(); for (ip = 1; ip <= 128; ip++) { i1 = (int)_p[1,ip]; j1 = (int)_p[2,ip]; _p[3,ip] += _b[i1,j1]; _p[4,ip] += _c[i1,j1]; _p[1,ip] += _p[3,ip]; _p[2,ip] += _p[4,ip]; // Each element of m_p, m_b and m_c is initialized to 1.00025 in Init(). // From the assignments above, // i2 = m_p[1,ip] = m_p[1,ip] + m_p[3,ip] = m_p[1,ip] + m_p[3,ip] + m_b[i1,j1] = 1 + 1 + 1 = 3 // j2 = m_p[2,ip] = m_p[2,ip] + m_p[4,ip] = m_p[2,ip] + m_p[4,ip] + m_c[i1,j1] = 1 + 1 + 1 = 3 i2 = (int)_p[1,ip]; j2 = (int)_p[2,ip]; // Accessing m_y, m_z upto 35 _p[1,ip] += _y[i2 + 32]; _p[2,ip] += _z[j2 + 32]; i2 += _e[i2 + 32]; j2 += _f[j2 + 32]; _h[i2,j2] += 1.0; } ts[13] = (double)Clock() - ts[13]; for (ip = 1; ip <= 128; ip++) { cksum[13] += (double)ip * (_p[3,ip] + _p[4,ip] + _p[1,ip] + _p[2,ip]); } for (k = 1; k <= 64; k++) { for (ix = 1; ix <= 8; ix++) { cksum[13] += (double)k * (double)ix * _h[k,ix]; } } /* loop 14 1-d particle pusher */ Init(); ts[14] = (double)Clock(); for (k = 1; k <= 150; k++) { // m_grd[150] = 13.636 // Therefore ix <= 13 ix = (int)_grd[k]; xi = (double)ix; _vx[k] += _ex[ix] + (_xx[k] - xi) * _dex[ix]; _xx[k] += _vx[k] + flx; ir = (int)_xx[k]; ri = (double)ir; rx1 = _xx[k] - ri; ir = System.Math.Abs(ir % 64); _xx[k] = ri + rx1; // ir < 64 since ir = ir % 64 // So m_rh is accessed upto 64 _rh[ir] += 1.0 - rx1; _rh[ir + 1] += rx1; } ts[14] = (double)Clock() - ts[14]; for (k = 1; k <= 150; k++) { cksum[14] += (double)k * (_vx[k] + _xx[k]); } for (k = 1; k <= 67; k++) { cksum[14] += (double)k * _rh[k]; } /* time the clock call */ ts[15] = (double)Clock(); ts[15] = (double)Clock() - ts[15]; /* scale= set to convert time to micro-seconds */ scale = 1.0; rt[15] = ts[15] * scale; nt = 14; t = s = uu = 0.0; for (k = 1; k <= nt; k++) { rt[k] = (ts[k] - ts[15]) * scale; t += rt[k]; mops[k] = _nrops[k] * _loops[k]; s += (double)mops[k]; rpm[k] = 0.0; if (rt[k] != 0.0) { rpm[k] = (double)mops[k] / rt[k]; } uu += rpm[k]; } uu /= (double)nt; s /= t; // Ensure that the array elements are live-out Escape(ts); Escape(rt); Escape(rpm); Escape(cksum); Escape(mops); } private void Init() { int j, k, l; for (k = 1; k <= 1000; k++) { _x[k] = 1.11; _y[k] = 1.123; _z[k] = 0.321; } for (k = 1; k <= 500; k++) { _u[k] = 0.00025; } for (k = 1; k <= 15; k++) { for (l = 1; l <= 100; l++) { _px[k,l] = l; _cx[k,l] = l; } } for (j = 1; j < 6; j++) { for (k = 1; k < 23; k++) { for (l = 1; l < 3; l++) { _u1[j,k,l] = k; _u2[j,k,l] = k + k; _u3[j,k,l] = k + k + k; } } } for (j = 1; j < 65; j++) { for (k = 1; k < 9; k++) { _b[j,k] = 1.00025; _c[j,k] = 1.00025; _h[j,k] = 1.00025; } } for (j = 1; j < 6; j++) { _bnk1[j] = j * 100; _bnk2[j] = j * 110; _bnk3[j] = j * 120; _bnk4[j] = j * 130; _bnk5[j] = j * 140; } for (j = 1; j < 5; j++) { for (k = 1; k < 513; k++) { _p[j,k] = 1.00025; } } for (j = 1; j < 193; j++) { _e[j] = _f[j] = 1; } for (j = 1; j < 68; j++) { _ex[j] = _rh[j] = _dex[j] = (double)j; } for (j = 1; j < 151; j++) { _vx[j] = 0.001; _xx[j] = 0.001; _grd[j] = (double)(j / 8 + 3); } } private bool TestBase() { bool result = Bench(); return result; } public static int Main() { var lloops = new MDLLoops(); bool result = lloops.TestBase(); return (result ? 100 : -1); } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/jit64/hfa/main/testB/hfa_nf0B_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="hfa_testB.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\dll\common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f32_common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f32_managed.csproj" /> <CMakeProjectReference Include="..\dll\CMakelists.txt" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="hfa_testB.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\dll\common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f32_common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f32_managed.csproj" /> <CMakeProjectReference Include="..\dll\CMakelists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.DirectoryServices.Protocols/tests/DeleteRequestTests.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.DirectoryServices.Protocols.Tests { public class DeleteRequestTests { [Fact] public void Ctor_Default() { var request = new DeleteRequest(); Assert.Empty(request.Controls); Assert.Null(request.DistinguishedName); Assert.Null(request.RequestId); } [Theory] [InlineData(null)] [InlineData("DistinguishedName")] public void Ctor_DistinguishedName(string distinguishedName) { var request = new DeleteRequest(distinguishedName); Assert.Empty(request.Controls); Assert.Equal(distinguishedName, request.DistinguishedName); Assert.Null(request.RequestId); } [Fact] public void DistinguishedName_Set_GetReturnsExpected() { var request = new DeleteRequest { DistinguishedName = "Name" }; Assert.Equal("Name", request.DistinguishedName); } [Fact] public void RequestId_Set_GetReturnsExpected() { var request = new DeleteRequest { RequestId = "Id" }; Assert.Equal("Id", request.RequestId); } } }
// 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.DirectoryServices.Protocols.Tests { public class DeleteRequestTests { [Fact] public void Ctor_Default() { var request = new DeleteRequest(); Assert.Empty(request.Controls); Assert.Null(request.DistinguishedName); Assert.Null(request.RequestId); } [Theory] [InlineData(null)] [InlineData("DistinguishedName")] public void Ctor_DistinguishedName(string distinguishedName) { var request = new DeleteRequest(distinguishedName); Assert.Empty(request.Controls); Assert.Equal(distinguishedName, request.DistinguishedName); Assert.Null(request.RequestId); } [Fact] public void DistinguishedName_Set_GetReturnsExpected() { var request = new DeleteRequest { DistinguishedName = "Name" }; Assert.Equal("Name", request.DistinguishedName); } [Fact] public void RequestId_Set_GetReturnsExpected() { var request = new DeleteRequest { RequestId = "Id" }; Assert.Equal("Id", request.RequestId); } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CounterName.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace System.Runtime.Caching { internal enum CounterName { Entries = 0, Hits, HitRatio, HitRatioBase, Misses, Trims, Turnover } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace System.Runtime.Caching { internal enum CounterName { Entries = 0, Hits, HitRatio, HitRatioBase, Misses, Trims, Turnover } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Properties/InternalsVisibleTo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/Exceptions/ForeignThread/ForeignThreadExceptions.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <Compile Include="ForeignThreadExceptions.cs" /> </ItemGroup> <ItemGroup> <CMakeProjectReference Include="CMakeLists.txt" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <Compile Include="ForeignThreadExceptions.cs" /> </ItemGroup> <ItemGroup> <CMakeProjectReference Include="CMakeLists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/installer/managed/Microsoft.NET.HostModel/Microsoft.NET.HostModel.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <Description>Abstractions for modifying .NET host binaries</Description> <IsShipping>false</IsShipping> <IsPackable>true</IsPackable> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> <IncludeSymbols>true</IncludeSymbols> <Serviceable>true</Serviceable> <GenerateDocumentationFile>true</GenerateDocumentationFile> <!-- Managed API isn't completely documented yet. TODO: https://github.com/dotnet/core-setup/issues/5108 --> <NoWarn>$(NoWarn);CS1591</NoWarn> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- Historically, the key for the managed projects is the AspNetCore key Arcade carries. --> <StrongNameKeyId>MicrosoftAspNetCore</StrongNameKeyId> <PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign> <PackageId Condition="'$(PgoInstrument)' == 'true'">Microsoft.Net.HostModel.PGO</PackageId> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Reflection.Metadata" Version="1.8.0" /> <PackageReference Include="System.Text.Json" Version="$(SystemTextJsonVersion)" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <Description>Abstractions for modifying .NET host binaries</Description> <IsShipping>false</IsShipping> <IsPackable>true</IsPackable> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> <IncludeSymbols>true</IncludeSymbols> <Serviceable>true</Serviceable> <GenerateDocumentationFile>true</GenerateDocumentationFile> <!-- Managed API isn't completely documented yet. TODO: https://github.com/dotnet/core-setup/issues/5108 --> <NoWarn>$(NoWarn);CS1591</NoWarn> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- Historically, the key for the managed projects is the AspNetCore key Arcade carries. --> <StrongNameKeyId>MicrosoftAspNetCore</StrongNameKeyId> <PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign> <PackageId Condition="'$(PgoInstrument)' == 'true'">Microsoft.Net.HostModel.PGO</PackageId> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Reflection.Metadata" Version="1.8.0" /> <PackageReference Include="System.Text.Json" Version="$(SystemTextJsonVersion)" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/Microsoft.Extensions.Caching.Abstractions/src/ICacheEntry.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 Microsoft.Extensions.Primitives; namespace Microsoft.Extensions.Caching.Memory { /// <summary> /// Represents an entry in the <see cref="IMemoryCache"/> implementation. /// </summary> public interface ICacheEntry : IDisposable { /// <summary> /// Gets the key of the cache entry. /// </summary> object Key { get; } /// <summary> /// Gets or set the value of the cache entry. /// </summary> object? Value { get; set; } /// <summary> /// Gets or sets an absolute expiration date for the cache entry. /// </summary> DateTimeOffset? AbsoluteExpiration { get; set; } /// <summary> /// Gets or sets an absolute expiration time, relative to now. /// </summary> TimeSpan? AbsoluteExpirationRelativeToNow { get; set; } /// <summary> /// Gets or sets how long a cache entry can be inactive (e.g. not accessed) before it will be removed. /// This will not extend the entry lifetime beyond the absolute expiration (if set). /// </summary> TimeSpan? SlidingExpiration { get; set; } /// <summary> /// Gets the <see cref="IChangeToken"/> instances which cause the cache entry to expire. /// </summary> IList<IChangeToken> ExpirationTokens { get; } /// <summary> /// Gets or sets the callbacks will be fired after the cache entry is evicted from the cache. /// </summary> IList<PostEvictionCallbackRegistration> PostEvictionCallbacks { get; } /// <summary> /// Gets or sets the priority for keeping the cache entry in the cache during a /// cleanup. The default is <see cref="CacheItemPriority.Normal"/>. /// </summary> CacheItemPriority Priority { get; set; } /// <summary> /// Gets or set the size of the cache entry value. /// </summary> long? Size { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using Microsoft.Extensions.Primitives; namespace Microsoft.Extensions.Caching.Memory { /// <summary> /// Represents an entry in the <see cref="IMemoryCache"/> implementation. /// </summary> public interface ICacheEntry : IDisposable { /// <summary> /// Gets the key of the cache entry. /// </summary> object Key { get; } /// <summary> /// Gets or set the value of the cache entry. /// </summary> object? Value { get; set; } /// <summary> /// Gets or sets an absolute expiration date for the cache entry. /// </summary> DateTimeOffset? AbsoluteExpiration { get; set; } /// <summary> /// Gets or sets an absolute expiration time, relative to now. /// </summary> TimeSpan? AbsoluteExpirationRelativeToNow { get; set; } /// <summary> /// Gets or sets how long a cache entry can be inactive (e.g. not accessed) before it will be removed. /// This will not extend the entry lifetime beyond the absolute expiration (if set). /// </summary> TimeSpan? SlidingExpiration { get; set; } /// <summary> /// Gets the <see cref="IChangeToken"/> instances which cause the cache entry to expire. /// </summary> IList<IChangeToken> ExpirationTokens { get; } /// <summary> /// Gets or sets the callbacks will be fired after the cache entry is evicted from the cache. /// </summary> IList<PostEvictionCallbackRegistration> PostEvictionCallbacks { get; } /// <summary> /// Gets or sets the priority for keeping the cache entry in the cache during a /// cleanup. The default is <see cref="CacheItemPriority.Normal"/>. /// </summary> CacheItemPriority Priority { get; set; } /// <summary> /// Gets or set the size of the cache entry value. /// </summary> long? Size { get; set; } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Collections.Specialized/tests/NameValueCollection/NameValueCollection.CopyToTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Collections.Specialized.Tests { public class NameValueCollectionCopyToTests { [Theory] [InlineData(0, 0)] [InlineData(0, 1)] [InlineData(5, 0)] [InlineData(5, 1)] public void CopyTo(int count, int index) { NameValueCollection nameValueCollection = Helpers.CreateNameValueCollection(count); string[] dest = new string[count + index + 5]; nameValueCollection.CopyTo(dest, index); for (int i = 0; i < index; i++) { Assert.Null(dest[i]); } for (int i = 0; i < count; i++) { Assert.Equal(nameValueCollection.Get(i), dest[i + index]); } for (int i = index + count; i < dest.Length; i++) { Assert.Null(dest[i]); } nameValueCollection.CopyTo(dest, index); for (int i = 0; i < count; i++) { Assert.Equal(nameValueCollection.Get(i), dest[i + index]); } } [Fact] public void CopyTo_MultipleValues_SameName() { NameValueCollection nameValueCollection = new NameValueCollection(); string name = "name"; nameValueCollection.Add(name, "value1"); nameValueCollection.Add(name, "value2"); nameValueCollection.Add(name, "value3"); string[] dest = new string[1]; nameValueCollection.CopyTo(dest, 0); Assert.Equal(nameValueCollection[0], dest[0]); } [Theory] [InlineData(0)] [InlineData(5)] public void CopyTo_Invalid(int count) { NameValueCollection nameValueCollection = Helpers.CreateNameValueCollection(count); AssertExtensions.Throws<ArgumentNullException>("dest", () => nameValueCollection.CopyTo(null, 0)); AssertExtensions.Throws<ArgumentException>("dest", null, () => nameValueCollection.CopyTo(new string[count, count], 0)); // in .NET Framework when passing multidimensional arrays Exception.ParamName is null. AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => nameValueCollection.CopyTo(new string[count], -1)); AssertExtensions.Throws<ArgumentException>(null, () => nameValueCollection.CopyTo(new string[count], 1)); AssertExtensions.Throws<ArgumentException>(null, () => nameValueCollection.CopyTo(new string[count], count + 1)); if (count > 0) { AssertExtensions.Throws<ArgumentException>(null, () => nameValueCollection.CopyTo(new string[count], count)); Assert.Throws<InvalidCastException>(() => nameValueCollection.CopyTo(new DictionaryEntry[count], 0)); } else { // InvalidCastException should not throw for an empty NameValueCollection nameValueCollection.CopyTo(new DictionaryEntry[count], 0); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.Collections.Specialized.Tests { public class NameValueCollectionCopyToTests { [Theory] [InlineData(0, 0)] [InlineData(0, 1)] [InlineData(5, 0)] [InlineData(5, 1)] public void CopyTo(int count, int index) { NameValueCollection nameValueCollection = Helpers.CreateNameValueCollection(count); string[] dest = new string[count + index + 5]; nameValueCollection.CopyTo(dest, index); for (int i = 0; i < index; i++) { Assert.Null(dest[i]); } for (int i = 0; i < count; i++) { Assert.Equal(nameValueCollection.Get(i), dest[i + index]); } for (int i = index + count; i < dest.Length; i++) { Assert.Null(dest[i]); } nameValueCollection.CopyTo(dest, index); for (int i = 0; i < count; i++) { Assert.Equal(nameValueCollection.Get(i), dest[i + index]); } } [Fact] public void CopyTo_MultipleValues_SameName() { NameValueCollection nameValueCollection = new NameValueCollection(); string name = "name"; nameValueCollection.Add(name, "value1"); nameValueCollection.Add(name, "value2"); nameValueCollection.Add(name, "value3"); string[] dest = new string[1]; nameValueCollection.CopyTo(dest, 0); Assert.Equal(nameValueCollection[0], dest[0]); } [Theory] [InlineData(0)] [InlineData(5)] public void CopyTo_Invalid(int count) { NameValueCollection nameValueCollection = Helpers.CreateNameValueCollection(count); AssertExtensions.Throws<ArgumentNullException>("dest", () => nameValueCollection.CopyTo(null, 0)); AssertExtensions.Throws<ArgumentException>("dest", null, () => nameValueCollection.CopyTo(new string[count, count], 0)); // in .NET Framework when passing multidimensional arrays Exception.ParamName is null. AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => nameValueCollection.CopyTo(new string[count], -1)); AssertExtensions.Throws<ArgumentException>(null, () => nameValueCollection.CopyTo(new string[count], 1)); AssertExtensions.Throws<ArgumentException>(null, () => nameValueCollection.CopyTo(new string[count], count + 1)); if (count > 0) { AssertExtensions.Throws<ArgumentException>(null, () => nameValueCollection.CopyTo(new string[count], count)); Assert.Throws<InvalidCastException>(() => nameValueCollection.CopyTo(new DictionaryEntry[count], 0)); } else { // InvalidCastException should not throw for an empty NameValueCollection nameValueCollection.CopyTo(new DictionaryEntry[count], 0); } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.SymbolStore; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Reflection.Emit { // deliberately not [serializable] public partial class ModuleBuilder : Module { internal static string UnmangleTypeName(string typeName) { // Gets the original type name, without '+' name mangling. int i = typeName.Length - 1; while (true) { i = typeName.LastIndexOf('+', i); if (i < 0) { break; } bool evenSlashes = true; int iSlash = i; while (typeName[--iSlash] == '\\') { evenSlashes = !evenSlashes; } // Even number of slashes means this '+' is a name separator if (evenSlashes) { break; } i = iSlash; } return typeName.Substring(i + 1); } #region Internal Data Members // _TypeBuilder contains both TypeBuilder and EnumBuilder objects private Dictionary<string, Type> _typeBuilderDict = null!; internal ModuleBuilderData _moduleData = null!; internal RuntimeModule _internalModule; // This is the "external" AssemblyBuilder // only the "external" ModuleBuilder has this set private readonly AssemblyBuilder _assemblyBuilder; internal AssemblyBuilder ContainingAssemblyBuilder => _assemblyBuilder; #endregion #region Constructor internal ModuleBuilder(AssemblyBuilder assemblyBuilder, RuntimeModule internalModule) { _internalModule = internalModule; _assemblyBuilder = assemblyBuilder; } #endregion #region Private Members internal void AddType(string name, Type type) => _typeBuilderDict.Add(name, type); internal void CheckTypeNameConflict(string strTypeName, Type? enclosingType) { if (_typeBuilderDict.TryGetValue(strTypeName, out Type? foundType) && ReferenceEquals(foundType.DeclaringType, enclosingType)) { // Cannot have two types with the same name throw new ArgumentException(SR.Argument_DuplicateTypeName); } } private static Type? GetType(string strFormat, Type baseType) { // This function takes a string to describe the compound type, such as "[,][]", and a baseType. if (string.IsNullOrEmpty(strFormat)) { return baseType; } // convert the format string to byte array and then call FormCompoundType return SymbolType.FormCompoundType(strFormat, baseType, 0); } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetTypeRef", StringMarshalling = StringMarshalling.Utf16)] private static partial int GetTypeRef(QCallModule module, string strFullName, QCallModule refedModule, string? strRefedModuleFileName, int tkResolution); [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetMemberRef")] private static partial int GetMemberRef(QCallModule module, QCallModule refedModule, int tr, int defToken); private int GetMemberRef(Module? refedModule, int tr, int defToken) { ModuleBuilder thisModule = this; RuntimeModule refedRuntimeModule = GetRuntimeModuleFromModule(refedModule); return GetMemberRef(new QCallModule(ref thisModule), new QCallModule(ref refedRuntimeModule), tr, defToken); } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetMemberRefFromSignature", StringMarshalling = StringMarshalling.Utf16)] private static partial int GetMemberRefFromSignature(QCallModule module, int tr, string methodName, byte[] signature, int length); private int GetMemberRefFromSignature(int tr, string methodName, byte[] signature, int length) { ModuleBuilder thisModule = this; return GetMemberRefFromSignature(new QCallModule(ref thisModule), tr, methodName, signature, length); } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetMemberRefOfMethodInfo")] private static partial int GetMemberRefOfMethodInfo(QCallModule module, int tr, RuntimeMethodHandleInternal method); private int GetMemberRefOfMethodInfo(int tr, RuntimeMethodInfo method) { Debug.Assert(method != null); ModuleBuilder thisModule = this; int result = GetMemberRefOfMethodInfo(new QCallModule(ref thisModule), tr, ((IRuntimeMethodInfo)method).Value); GC.KeepAlive(method); return result; } private int GetMemberRefOfMethodInfo(int tr, RuntimeConstructorInfo method) { Debug.Assert(method != null); ModuleBuilder thisModule = this; int result = GetMemberRefOfMethodInfo(new QCallModule(ref thisModule), tr, ((IRuntimeMethodInfo)method).Value); GC.KeepAlive(method); return result; } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetMemberRefOfFieldInfo")] private static partial int GetMemberRefOfFieldInfo(QCallModule module, int tkType, QCallTypeHandle declaringType, int tkField); private int GetMemberRefOfFieldInfo(int tkType, RuntimeTypeHandle declaringType, RuntimeFieldInfo runtimeField) { Debug.Assert(runtimeField != null); ModuleBuilder thisModule = this; return GetMemberRefOfFieldInfo(new QCallModule(ref thisModule), tkType, new QCallTypeHandle(ref declaringType), runtimeField.MetadataToken); } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetTokenFromTypeSpec")] private static partial int GetTokenFromTypeSpec(QCallModule pModule, byte[] signature, int length); private int GetTokenFromTypeSpec(byte[] signature, int length) { ModuleBuilder thisModule = this; return GetTokenFromTypeSpec(new QCallModule(ref thisModule), signature, length); } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetArrayMethodToken", StringMarshalling = StringMarshalling.Utf16)] private static partial int GetArrayMethodToken(QCallModule module, int tkTypeSpec, string methodName, byte[] signature, int sigLength); [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetStringConstant", StringMarshalling = StringMarshalling.Utf16)] private static partial int GetStringConstant(QCallModule module, string str, int length); [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_SetFieldRVAContent")] internal static partial void SetFieldRVAContent(QCallModule module, int fdToken, byte[]? data, int length); #endregion #region Internal Members internal virtual Type? FindTypeBuilderWithName(string strTypeName, bool ignoreCase) { if (ignoreCase) { foreach (string name in _typeBuilderDict.Keys) { if (string.Equals(name, strTypeName, StringComparison.OrdinalIgnoreCase)) { return _typeBuilderDict[name]; } } } else { if (_typeBuilderDict.TryGetValue(strTypeName, out Type? foundType)) { return foundType; } } return null; } private int GetTypeRefNested(Type type, Module? refedModule, string? strRefedModuleFileName) { // This function will generate correct TypeRef token for top level type and nested type. Type? enclosingType = type.DeclaringType; int tkResolution = 0; string typeName = type.FullName!; if (enclosingType != null) { tkResolution = GetTypeRefNested(enclosingType, refedModule, strRefedModuleFileName); typeName = UnmangleTypeName(typeName); } Debug.Assert(!type.IsByRef, "Must not be ByRef. Get token from TypeSpec."); Debug.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments."); ModuleBuilder thisModule = this; RuntimeModule refedRuntimeModule = GetRuntimeModuleFromModule(refedModule); return GetTypeRef(new QCallModule(ref thisModule), typeName, new QCallModule(ref refedRuntimeModule), strRefedModuleFileName, tkResolution); } internal int InternalGetConstructorToken(ConstructorInfo con!!, bool usingRef) { // Helper to get constructor token. If usingRef is true, we will never use the def token int tr; int mr; if (con is ConstructorBuilder conBuilder) { if (!usingRef && conBuilder.Module.Equals(this)) return conBuilder.MetadataToken; // constructor is defined in a different module tr = GetTypeTokenInternal(con.ReflectedType!); mr = GetMemberRef(con.ReflectedType!.Module, tr, conBuilder.MetadataToken); } else if (con is ConstructorOnTypeBuilderInstantiation conOnTypeBuilderInst) { if (usingRef) throw new InvalidOperationException(); tr = GetTypeTokenInternal(con.DeclaringType!); mr = GetMemberRef(con.DeclaringType!.Module, tr, conOnTypeBuilderInst.MetadataToken); } else if (con is RuntimeConstructorInfo rtCon && !con.ReflectedType!.IsArray) { // constructor is not a dynamic field // We need to get the TypeRef tokens tr = GetTypeTokenInternal(con.ReflectedType); mr = GetMemberRefOfMethodInfo(tr, rtCon); } else { // some user derived ConstructorInfo // go through the slower code path, i.e. retrieve parameters and form signature helper. ParameterInfo[] parameters = con.GetParameters(); if (parameters == null) { throw new ArgumentException(SR.Argument_InvalidConstructorInfo); } Type[] parameterTypes = new Type[parameters.Length]; Type[][] requiredCustomModifiers = new Type[parameters.Length][]; Type[][] optionalCustomModifiers = new Type[parameters.Length][]; for (int i = 0; i < parameters.Length; i++) { if (parameters[i] == null) { throw new ArgumentException(SR.Argument_InvalidConstructorInfo); } parameterTypes[i] = parameters[i].ParameterType; requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers(); optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers(); } tr = GetTypeTokenInternal(con.ReflectedType!); SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(this, con.CallingConvention, null, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers); byte[] sigBytes = sigHelp.InternalGetSignature(out int length); mr = GetMemberRefFromSignature(tr, con.Name, sigBytes, length); } return mr; } internal void Init(string strModuleName) { _moduleData = new ModuleBuilderData(this, strModuleName); _typeBuilderDict = new Dictionary<string, Type>(); } internal object SyncRoot => ContainingAssemblyBuilder.SyncRoot; #endregion #region Module Overrides internal RuntimeModule InternalModule => _internalModule; protected override ModuleHandle GetModuleHandleImpl() => new ModuleHandle(InternalModule); private static RuntimeModule GetRuntimeModuleFromModule(Module? m) { ModuleBuilder? mb = m as ModuleBuilder; if (mb != null) { return mb.InternalModule; } return (m as RuntimeModule)!; } private int GetMemberRefToken(MethodBase method, Type[]? optionalParameterTypes) { int tkParent; int cGenericParameters = 0; SignatureHelper sigHelp; if (method.IsGenericMethod) { if (!method.IsGenericMethodDefinition) { throw new InvalidOperationException(); } cGenericParameters = method.GetGenericArguments().Length; } if (optionalParameterTypes != null) { if ((method.CallingConvention & CallingConventions.VarArgs) == 0) { // Client should not supply optional parameter in default calling convention throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention); } } MethodInfo? masmi = method as MethodInfo; if (method.DeclaringType!.IsGenericType) { MethodBase methDef = GetGenericMethodBaseDefinition(method); sigHelp = GetMemberRefSignature(methDef, cGenericParameters); } else { sigHelp = GetMemberRefSignature(method, cGenericParameters); } if (optionalParameterTypes?.Length > 0) { sigHelp.AddSentinel(); sigHelp.AddArguments(optionalParameterTypes, null, null); } byte[] sigBytes = sigHelp.InternalGetSignature(out int sigLength); if (method.DeclaringType!.IsGenericType) { byte[] sig = SignatureHelper.GetTypeSigToken(this, method.DeclaringType).InternalGetSignature(out int length); tkParent = GetTokenFromTypeSpec(sig, length); } else if (!method.Module.Equals(this)) { // Use typeRef as parent because the method's declaringType lives in a different assembly tkParent = GetTypeToken(method.DeclaringType); } else { // Use methodDef as parent because the method lives in this assembly and its declaringType has no generic arguments if (masmi != null) tkParent = GetMethodToken(masmi); else tkParent = GetConstructorToken((method as ConstructorInfo)!); } return GetMemberRefFromSignature(tkParent, method.Name, sigBytes, sigLength); } internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type? returnType, Type[]? parameterTypes, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers, Type[]? optionalParameterTypes, int cGenericParameters) { SignatureHelper sig = SignatureHelper.GetMethodSigHelper(this, call, cGenericParameters, returnType, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers); if (optionalParameterTypes != null && optionalParameterTypes.Length != 0) { sig.AddSentinel(); sig.AddArguments(optionalParameterTypes, null, null); } return sig; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Module.ResolveMethod is marked as RequiresUnreferencedCode because it relies on tokens " + "which are not guaranteed to be stable across trimming. So if somebody hardcodes a token it could break. " + "The usage here is not like that as all these tokens come from existing metadata loaded from some IL " + "and so trimming has no effect (the tokens are read AFTER trimming occured).")] private static MethodBase GetGenericMethodBaseDefinition(MethodBase methodBase) { // methodInfo = G<Foo>.M<Bar> ==> methDef = G<T>.M<S> MethodInfo? masmi = methodBase as MethodInfo; MethodBase methDef; if (methodBase is MethodOnTypeBuilderInstantiation motbi) { methDef = motbi.m_method; } else if (methodBase is ConstructorOnTypeBuilderInstantiation cotbi) { methDef = cotbi.m_ctor; } else if (methodBase is MethodBuilder || methodBase is ConstructorBuilder) { // methodInfo must be GenericMethodDefinition; trying to emit G<?>.M<S> methDef = methodBase; } else { Debug.Assert(methodBase is RuntimeMethodInfo || methodBase is RuntimeConstructorInfo); if (methodBase.IsGenericMethod) { Debug.Assert(masmi != null); methDef = masmi.GetGenericMethodDefinition()!; methDef = methDef.Module.ResolveMethod( methodBase.MetadataToken, methDef.DeclaringType?.GetGenericArguments(), methDef.GetGenericArguments())!; } else { methDef = methodBase.Module.ResolveMethod( methodBase.MetadataToken, methodBase.DeclaringType?.GetGenericArguments(), null)!; } } return methDef; } internal SignatureHelper GetMemberRefSignature(MethodBase? method, int cGenericParameters) { switch (method) { case MethodBuilder methodBuilder: return methodBuilder.GetMethodSignature(); case ConstructorBuilder constructorBuilder: return constructorBuilder.GetMethodSignature(); case MethodOnTypeBuilderInstantiation motbi when motbi.m_method is MethodBuilder methodBuilder: return methodBuilder.GetMethodSignature(); case MethodOnTypeBuilderInstantiation motbi: method = motbi.m_method; break; case ConstructorOnTypeBuilderInstantiation cotbi when cotbi.m_ctor is ConstructorBuilder constructorBuilder: return constructorBuilder.GetMethodSignature(); case ConstructorOnTypeBuilderInstantiation cotbi: method = cotbi.m_ctor; break; } Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); ParameterInfo[] parameters = method.GetParametersNoCopy(); Type[] parameterTypes = new Type[parameters.Length]; Type[][] requiredCustomModifiers = new Type[parameterTypes.Length][]; Type[][] optionalCustomModifiers = new Type[parameterTypes.Length][]; for (int i = 0; i < parameters.Length; i++) { parameterTypes[i] = parameters[i].ParameterType; requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers(); optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers(); } ParameterInfo? returnParameter = method is MethodInfo mi ? mi.ReturnParameter : null; SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(this, method.CallingConvention, cGenericParameters, returnParameter?.ParameterType, returnParameter?.GetRequiredCustomModifiers(), returnParameter?.GetOptionalCustomModifiers(), parameterTypes, requiredCustomModifiers, optionalCustomModifiers); return sigHelp; } #endregion public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); #region ICustomAttributeProvider Members public override object[] GetCustomAttributes(bool inherit) { return InternalModule.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return InternalModule.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return InternalModule.IsDefined(attributeType, inherit); } public override IList<CustomAttributeData> GetCustomAttributesData() { return InternalModule.GetCustomAttributesData(); } #endregion #region Module Overrides [RequiresUnreferencedCode("Types might be removed")] public override Type[] GetTypes() { lock (SyncRoot) { return GetTypesNoLock(); } } internal Type[] GetTypesNoLock() { Type[] typeList = new Type[_typeBuilderDict.Count]; int i = 0; foreach (Type builder in _typeBuilderDict.Values) { EnumBuilder? enumBldr = builder as EnumBuilder; TypeBuilder tmpTypeBldr; if (enumBldr != null) tmpTypeBldr = enumBldr.m_typeBuilder; else tmpTypeBldr = (TypeBuilder)builder; // We should not return TypeBuilders. // Otherwise anyone can emit code in it. if (tmpTypeBldr.IsCreated()) typeList[i++] = tmpTypeBldr.UnderlyingSystemType; else typeList[i++] = builder; } return typeList; } [RequiresUnreferencedCode("Types might be removed")] public override Type? GetType(string className) { return GetType(className, false, false); } [RequiresUnreferencedCode("Types might be removed")] public override Type? GetType(string className, bool ignoreCase) { return GetType(className, false, ignoreCase); } [RequiresUnreferencedCode("Types might be removed")] public override Type? GetType(string className, bool throwOnError, bool ignoreCase) { lock (SyncRoot) { return GetTypeNoLock(className, throwOnError, ignoreCase); } } [RequiresUnreferencedCode("Types might be removed")] private Type? GetTypeNoLock(string className, bool throwOnError, bool ignoreCase) { // public API to to a type. The reason that we need this function override from module // is because clients might need to get foo[] when foo is being built. For example, if // foo class contains a data member of type foo[]. // This API first delegate to the Module.GetType implementation. If succeeded, great! // If not, we have to look up the current module to find the TypeBuilder to represent the base // type and form the Type object for "foo[,]". // Module.GetType() will verify className. Type? baseType = InternalModule.GetType(className, throwOnError, ignoreCase); if (baseType != null) return baseType; // Now try to see if we contain a TypeBuilder for this type or not. // Might have a compound type name, indicated via an unescaped // '[', '*' or '&'. Split the name at this point. string? baseName = null; string? parameters = null; int startIndex = 0; while (startIndex <= className.Length) { // Are there any possible special characters left? int i = className.AsSpan(startIndex).IndexOfAny('[', '*', '&'); if (i < 0) { // No, type name is simple. baseName = className; parameters = null; break; } i += startIndex; // Found a potential special character, but it might be escaped. int slashes = 0; for (int j = i - 1; j >= 0 && className[j] == '\\'; j--) slashes++; // Odd number of slashes indicates escaping. if (slashes % 2 == 1) { startIndex = i + 1; continue; } // Found the end of the base type name. baseName = className.Substring(0, i); parameters = className.Substring(i); break; } // If we didn't find a basename yet, the entire class name is // the base name and we don't have a composite type. if (baseName == null) { baseName = className; parameters = null; } baseName = baseName.Replace(@"\\", @"\").Replace(@"\[", "[").Replace(@"\*", "*").Replace(@"\&", "&"); if (parameters != null) { // try to see if reflection can find the base type. It can be such that reflection // does not support the complex format string yet! baseType = InternalModule.GetType(baseName, false, ignoreCase); } if (baseType == null) { // try to find it among the unbaked types. // starting with the current module first of all. baseType = FindTypeBuilderWithName(baseName, ignoreCase); if (baseType == null && Assembly is AssemblyBuilder) { // now goto Assembly level to find the type. List<ModuleBuilder> modList = ContainingAssemblyBuilder._assemblyData._moduleBuilderList; int size = modList.Count; for (int i = 0; i < size && baseType == null; i++) { ModuleBuilder mBuilder = modList[i]; baseType = mBuilder.FindTypeBuilderWithName(baseName, ignoreCase); } } if (baseType == null) { return null; } } if (parameters == null) { return baseType; } return GetType(parameters, baseType); } [RequiresAssemblyFiles(UnknownStringMessageInRAF)] public override string FullyQualifiedName => _moduleData._moduleName; [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override byte[] ResolveSignature(int metadataToken) { return InternalModule.ResolveSignature(metadataToken); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override MethodBase? ResolveMethod(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override FieldInfo? ResolveField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override Type ResolveType(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override MemberInfo? ResolveMember(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override string ResolveString(int metadataToken) { return InternalModule.ResolveString(metadataToken); } public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) { InternalModule.GetPEKind(out peKind, out machine); } public override int MDStreamVersion => InternalModule.MDStreamVersion; public override Guid ModuleVersionId => InternalModule.ModuleVersionId; public override int MetadataToken => InternalModule.MetadataToken; public override bool IsResource() => InternalModule.IsResource(); [RequiresUnreferencedCode("Fields might be removed")] public override FieldInfo[] GetFields(BindingFlags bindingFlags) { return InternalModule.GetFields(bindingFlags); } [RequiresUnreferencedCode("Fields might be removed")] public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { return InternalModule.GetField(name, bindingAttr); } [RequiresUnreferencedCode("Methods might be removed")] public override MethodInfo[] GetMethods(BindingFlags bindingFlags) { return InternalModule.GetMethods(bindingFlags); } [RequiresUnreferencedCode("Methods might be removed")] protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { // Cannot call InternalModule.GetMethods because it doesn't allow types to be null return InternalModule.GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers); } public override string ScopeName => InternalModule.ScopeName; [RequiresAssemblyFiles(UnknownStringMessageInRAF)] public override string Name => InternalModule.Name; public override Assembly Assembly => _assemblyBuilder; #endregion #region Public Members #region Define Type public TypeBuilder DefineType(string name) { lock (SyncRoot) { return DefineTypeNoLock(name, TypeAttributes.NotPublic, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); } } public TypeBuilder DefineType(string name, TypeAttributes attr) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); } } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent) { lock (SyncRoot) { AssemblyBuilder.CheckContext(parent); return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); } } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, int typesize) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, typesize); } } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, PackingSize packingSize, int typesize) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, null, packingSize, typesize); } } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, Type[]? interfaces) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); } } private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, Type[]? interfaces, PackingSize packingSize, int typesize) { return new TypeBuilder(name, attr, parent, interfaces, this, packingSize, typesize, null); } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, PackingSize packsize) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, packsize); } } private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, PackingSize packsize) { return new TypeBuilder(name, attr, parent, null, this, packsize, TypeBuilder.UnspecifiedTypeSize, null); } #endregion #region Define Enum // This API can only be used to construct a top-level (not nested) enum type. // Nested enum types can be defined manually using ModuleBuilder.DefineType. public EnumBuilder DefineEnum(string name, TypeAttributes visibility, Type underlyingType) { AssemblyBuilder.CheckContext(underlyingType); lock (SyncRoot) { EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType); // This enum is not generic, nested, and cannot have any element type. // Replace the TypeBuilder object in _typeBuilderDict with this EnumBuilder object. _typeBuilderDict[name] = enumBuilder; return enumBuilder; } } private EnumBuilder DefineEnumNoLock(string name, TypeAttributes visibility, Type underlyingType) { return new EnumBuilder(name, underlyingType, visibility, this); } #endregion #region Define Global Method [RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")] public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { return DefinePInvokeMethod(name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); } [RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")] public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { lock (SyncRoot) { // Global methods must be static. if ((attributes & MethodAttributes.Static) == 0) { throw new ArgumentException(SR.Argument_GlobalFunctionHasToBeStatic); } AssemblyBuilder.CheckContext(returnType); AssemblyBuilder.CheckContext(parameterTypes); return _moduleData._globalTypeBuilder.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); } } public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, Type? returnType, Type[]? parameterTypes) { return DefineGlobalMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes); } public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes) { return DefineGlobalMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null); } public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { lock (SyncRoot) { return DefineGlobalMethodNoLock(name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } } private MethodBuilder DefineGlobalMethodNoLock(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { if (_moduleData._hasGlobalBeenCreated) { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } ArgumentException.ThrowIfNullOrEmpty(name); if ((attributes & MethodAttributes.Static) == 0) { throw new ArgumentException(SR.Argument_GlobalFunctionHasToBeStatic); } AssemblyBuilder.CheckContext(returnType); AssemblyBuilder.CheckContext(requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes); AssemblyBuilder.CheckContext(requiredParameterTypeCustomModifiers); AssemblyBuilder.CheckContext(optionalParameterTypeCustomModifiers); return _moduleData._globalTypeBuilder.DefineMethod(name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } public void CreateGlobalFunctions() { lock (SyncRoot) { CreateGlobalFunctionsNoLock(); } } private void CreateGlobalFunctionsNoLock() { if (_moduleData._hasGlobalBeenCreated) { // cannot create globals twice throw new InvalidOperationException(SR.InvalidOperation_NotADebugModule); } _moduleData._globalTypeBuilder.CreateType(); _moduleData._hasGlobalBeenCreated = true; } #endregion #region Define Data public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttributes attributes) { // This method will define an initialized Data in .sdata. // We will create a fake TypeDef to represent the data with size. This TypeDef // will be the signature for the Field. lock (SyncRoot) { return DefineInitializedDataNoLock(name, data, attributes); } } private FieldBuilder DefineInitializedDataNoLock(string name, byte[] data, FieldAttributes attributes) { // This method will define an initialized Data in .sdata. // We will create a fake TypeDef to represent the data with size. This TypeDef // will be the signature for the Field. if (_moduleData._hasGlobalBeenCreated) { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } return _moduleData._globalTypeBuilder.DefineInitializedData(name, data, attributes); } public FieldBuilder DefineUninitializedData(string name, int size, FieldAttributes attributes) { lock (SyncRoot) { return DefineUninitializedDataNoLock(name, size, attributes); } } private FieldBuilder DefineUninitializedDataNoLock(string name, int size, FieldAttributes attributes) { // This method will define an uninitialized Data in .sdata. // We will create a fake TypeDef to represent the data with size. This TypeDef // will be the signature for the Field. if (_moduleData._hasGlobalBeenCreated) { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } return _moduleData._globalTypeBuilder.DefineUninitializedData(name, size, attributes); } #endregion #region GetToken // For a generic type definition, we should return the token for the generic type definition itself in two cases: // 1. GetTypeToken // 2. ldtoken (see ILGenerator) // For all other occasions we should return the generic type instantiated on its formal parameters. internal int GetTypeTokenInternal(Type type) { return GetTypeTokenInternal(type, getGenericDefinition: false); } private int GetTypeTokenInternal(Type type, bool getGenericDefinition) { lock (SyncRoot) { return GetTypeTokenWorkerNoLock(type, getGenericDefinition); } } internal int GetTypeToken(Type type) { return GetTypeTokenInternal(type, getGenericDefinition: true); } private int GetTypeTokenWorkerNoLock(Type type!!, bool getGenericDefinition) { AssemblyBuilder.CheckContext(type); // Return a token for the class relative to the Module. Tokens // are used to indentify objects when the objects are used in IL // instructions. Tokens are always relative to the Module. For example, // the token value for System.String is likely to be different from // Module to Module. Calling GetTypeToken will cause a reference to be // added to the Module. This reference becomes a permanent part of the Module, // multiple calls to this method with the same class have no additional side-effects. // This function is optimized to use the TypeDef token if the Type is within the // same module. We should also be aware of multiple dynamic modules and multiple // implementations of a Type. if ((type.IsGenericType && (!type.IsGenericTypeDefinition || !getGenericDefinition)) || type.IsGenericParameter || type.IsArray || type.IsPointer || type.IsByRef) { byte[] sig = SignatureHelper.GetTypeSigToken(this, type).InternalGetSignature(out int length); return GetTokenFromTypeSpec(sig, length); } Module refedModule = type.Module; if (refedModule.Equals(this)) { // no need to do anything additional other than defining the TypeRef Token TypeBuilder? typeBuilder; EnumBuilder? enumBuilder = type as EnumBuilder; typeBuilder = enumBuilder != null ? enumBuilder.m_typeBuilder : type as TypeBuilder; if (typeBuilder != null) { // If the type is defined in this module, just return the token. return typeBuilder.TypeToken; } else if (type is GenericTypeParameterBuilder paramBuilder) { return paramBuilder.MetadataToken; } return GetTypeRefNested(type, this, string.Empty); } // After this point, the referenced module is not the same as the referencing // module. ModuleBuilder? refedModuleBuilder = refedModule as ModuleBuilder; string referencedModuleFileName = string.Empty; if (refedModule.Assembly.Equals(Assembly)) { // if the referenced module is in the same assembly, the resolution // scope of the type token will be a module ref, we will need // the file name of the referenced module for that. // if the refed module is in a different assembly, the resolution // scope of the type token will be an assembly ref. We don't need // the file name of the referenced module. if (refedModuleBuilder == null) { refedModuleBuilder = ContainingAssemblyBuilder.GetModuleBuilder((RuntimeModule)refedModule); } referencedModuleFileName = refedModuleBuilder._moduleData._moduleName; } return GetTypeRefNested(type, refedModule, referencedModuleFileName); } internal int GetMethodToken(MethodInfo method) { lock (SyncRoot) { return GetMethodTokenNoLock(method, false); } } // For a method on a generic type, we should return the methoddef token on the generic type definition in two cases // 1. GetMethodToken // 2. ldtoken (see ILGenerator) // For all other occasions we should return the method on the generic type instantiated on the formal parameters. private int GetMethodTokenNoLock(MethodInfo method!!, bool getGenericTypeDefinition) { // Return a MemberRef token if MethodInfo is not defined in this module. Or // return the MethodDef token. int tr; int mr; if (method is MethodBuilder methBuilder) { int methodToken = methBuilder.MetadataToken; if (method.Module.Equals(this)) { return methodToken; } if (method.DeclaringType == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } // method is defined in a different module tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType) : GetTypeTokenInternal(method.DeclaringType); mr = GetMemberRef(method.DeclaringType.Module, tr, methodToken); } else if (method is MethodOnTypeBuilderInstantiation) { return GetMemberRefToken(method, null); } else if (method is SymbolMethod symMethod) { if (symMethod.GetModule() == this) return symMethod.MetadataToken; // form the method token return symMethod.GetToken(this); } else { Type? declaringType = method.DeclaringType; // We need to get the TypeRef tokens if (declaringType == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } if (declaringType.IsArray) { // use reflection to build signature to work around the E_T_VAR problem in EEClass ParameterInfo[] paramInfo = method.GetParameters(); Type[] tt = new Type[paramInfo.Length]; for (int i = 0; i < paramInfo.Length; i++) tt[i] = paramInfo[i].ParameterType; return GetArrayMethodToken(declaringType, method.Name, method.CallingConvention, method.ReturnType, tt); } else if (method is RuntimeMethodInfo rtMeth) { tr = getGenericTypeDefinition ? GetTypeToken(declaringType) : GetTypeTokenInternal(declaringType); mr = GetMemberRefOfMethodInfo(tr, rtMeth); } else { // some user derived ConstructorInfo // go through the slower code path, i.e. retrieve parameters and form signature helper. ParameterInfo[] parameters = method.GetParameters(); Type[] parameterTypes = new Type[parameters.Length]; Type[][] requiredCustomModifiers = new Type[parameterTypes.Length][]; Type[][] optionalCustomModifiers = new Type[parameterTypes.Length][]; for (int i = 0; i < parameters.Length; i++) { parameterTypes[i] = parameters[i].ParameterType; requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers(); optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers(); } tr = getGenericTypeDefinition ? GetTypeToken(declaringType) : GetTypeTokenInternal(declaringType); SignatureHelper sigHelp; try { sigHelp = SignatureHelper.GetMethodSigHelper( this, method.CallingConvention, method.ReturnType, method.ReturnParameter.GetRequiredCustomModifiers(), method.ReturnParameter.GetOptionalCustomModifiers(), parameterTypes, requiredCustomModifiers, optionalCustomModifiers); } catch (NotImplementedException) { // Legacy code deriving from MethodInfo may not have implemented ReturnParameter. sigHelp = SignatureHelper.GetMethodSigHelper(this, method.ReturnType, parameterTypes); } byte[] sigBytes = sigHelp.InternalGetSignature(out int length); mr = GetMemberRefFromSignature(tr, method.Name, sigBytes, length); } } return mr; } internal int GetMethodTokenInternal(MethodBase method, Type[]? optionalParameterTypes, bool useMethodDef) { int tk; MethodInfo? methodInfo = method as MethodInfo; if (method.IsGenericMethod) { // Constructors cannot be generic. Debug.Assert(methodInfo != null); // Given M<Bar> unbind to M<S> MethodInfo methodInfoUnbound = methodInfo; bool isGenericMethodDef = methodInfo.IsGenericMethodDefinition; if (!isGenericMethodDef) { methodInfoUnbound = methodInfo.GetGenericMethodDefinition()!; } if (!Equals(methodInfoUnbound.Module) || (methodInfoUnbound.DeclaringType != null && methodInfoUnbound.DeclaringType.IsGenericType)) { tk = GetMemberRefToken(methodInfoUnbound, null); } else { tk = GetMethodToken(methodInfoUnbound); } // For Ldtoken, Ldftn, and Ldvirtftn, we should emit the method def/ref token for a generic method definition. if (isGenericMethodDef && useMethodDef) { return tk; } // Create signature of method instantiation M<Bar> // Create MethodSepc M<Bar> with parent G?.M<S> byte[] sigBytes = SignatureHelper.GetMethodSpecSigHelper( this, methodInfo.GetGenericArguments()).InternalGetSignature(out int sigLength); ModuleBuilder thisModule = this; tk = TypeBuilder.DefineMethodSpec(new QCallModule(ref thisModule), tk, sigBytes, sigLength); } else { if (((method.CallingConvention & CallingConventions.VarArgs) == 0) && (method.DeclaringType == null || !method.DeclaringType.IsGenericType)) { if (methodInfo != null) { tk = GetMethodToken(methodInfo); } else { tk = GetConstructorToken((method as ConstructorInfo)!); } } else { tk = GetMemberRefToken(method, optionalParameterTypes); } } return tk; } internal int GetArrayMethodToken(Type arrayClass, string methodName, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes) { lock (SyncRoot) { return GetArrayMethodTokenNoLock(arrayClass, methodName, callingConvention, returnType, parameterTypes); } } private int GetArrayMethodTokenNoLock(Type arrayClass, string methodName, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes) { ArgumentNullException.ThrowIfNull(arrayClass); ArgumentException.ThrowIfNullOrEmpty(methodName); if (!arrayClass.IsArray) { throw new ArgumentException(SR.Argument_HasToBeArrayClass); } AssemblyBuilder.CheckContext(returnType, arrayClass); AssemblyBuilder.CheckContext(parameterTypes); // Return a token for the MethodInfo for a method on an Array. This is primarily // used to get the LoadElementAddress method. SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper( this, callingConvention, returnType, null, null, parameterTypes, null, null); byte[] sigBytes = sigHelp.InternalGetSignature(out int length); int typeSpec = GetTypeTokenInternal(arrayClass); ModuleBuilder thisModule = this; return GetArrayMethodToken(new QCallModule(ref thisModule), typeSpec, methodName, sigBytes, length); } public MethodInfo GetArrayMethod(Type arrayClass, string methodName, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes) { AssemblyBuilder.CheckContext(returnType, arrayClass); AssemblyBuilder.CheckContext(parameterTypes); // GetArrayMethod is useful when you have an array of a type whose definition has not been completed and // you want to access methods defined on Array. For example, you might define a type and want to define a // method that takes an array of the type as a parameter. In order to access the elements of the array, // you will need to call methods of the Array class. int token = GetArrayMethodToken(arrayClass, methodName, callingConvention, returnType, parameterTypes); return new SymbolMethod(this, token, arrayClass, methodName, callingConvention, returnType, parameterTypes); } internal int GetConstructorToken(ConstructorInfo con) { // Return a token for the ConstructorInfo relative to the Module. return InternalGetConstructorToken(con, false); } internal int GetFieldToken(FieldInfo field) { lock (SyncRoot) { return GetFieldTokenNoLock(field); } } private int GetFieldTokenNoLock(FieldInfo field!!) { int tr; int mr; if (field is FieldBuilder fdBuilder) { if (field.DeclaringType != null && field.DeclaringType.IsGenericType) { byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out int length); tr = GetTokenFromTypeSpec(sig, length); mr = GetMemberRef(this, tr, fdBuilder.MetadataToken); } else if (fdBuilder.Module.Equals(this)) { // field is defined in the same module return fdBuilder.MetadataToken; } else { // field is defined in a different module if (field.DeclaringType == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } tr = GetTypeTokenInternal(field.DeclaringType); mr = GetMemberRef(field.ReflectedType!.Module, tr, fdBuilder.MetadataToken); } } else if (field is RuntimeFieldInfo rtField) { // FieldInfo is not an dynamic field // We need to get the TypeRef tokens if (field.DeclaringType == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } if (field.DeclaringType != null && field.DeclaringType.IsGenericType) { byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out int length); tr = GetTokenFromTypeSpec(sig, length); mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType.TypeHandle, rtField); } else { tr = GetTypeTokenInternal(field.DeclaringType!); mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType!.TypeHandle, rtField); } } else if (field is FieldOnTypeBuilderInstantiation fOnTB) { FieldInfo fb = fOnTB.FieldInfo; byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType!).InternalGetSignature(out int length); tr = GetTokenFromTypeSpec(sig, length); mr = GetMemberRef(fb.ReflectedType!.Module, tr, fOnTB.MetadataToken); } else { // user defined FieldInfo tr = GetTypeTokenInternal(field.ReflectedType!); SignatureHelper sigHelp = SignatureHelper.GetFieldSigHelper(this); sigHelp.AddArgument(field.FieldType, field.GetRequiredCustomModifiers(), field.GetOptionalCustomModifiers()); byte[] sigBytes = sigHelp.InternalGetSignature(out int length); mr = GetMemberRefFromSignature(tr, field.Name, sigBytes, length); } return mr; } internal int GetStringConstant(string str!!) { // Returns a token representing a String constant. If the string // value has already been defined, the existing token will be returned. ModuleBuilder thisModule = this; return GetStringConstant(new QCallModule(ref thisModule), str, str.Length); } internal int GetSignatureToken(SignatureHelper sigHelper!!) { // Define signature token given a signature helper. This will define a metadata // token for the signature described by SignatureHelper. // Get the signature in byte form. byte[] sigBytes = sigHelper.InternalGetSignature(out int sigLength); ModuleBuilder thisModule = this; return TypeBuilder.GetTokenFromSig(new QCallModule(ref thisModule), sigBytes, sigLength); } internal int GetSignatureToken(byte[] sigBytes!!, int sigLength) { byte[] localSigBytes = new byte[sigBytes.Length]; Buffer.BlockCopy(sigBytes, 0, localSigBytes, 0, sigBytes.Length); ModuleBuilder thisModule = this; return TypeBuilder.GetTokenFromSig(new QCallModule(ref thisModule), localSigBytes, sigLength); } #endregion #region Other public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) { TypeBuilder.DefineCustomAttribute( this, 1, // This is hard coding the module token to 1 GetConstructorToken(con), binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!) { customBuilder.CreateCustomAttribute(this, 1); // This is hard coding the module token to 1 } #endregion #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.SymbolStore; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Reflection.Emit { // deliberately not [serializable] public partial class ModuleBuilder : Module { internal static string UnmangleTypeName(string typeName) { // Gets the original type name, without '+' name mangling. int i = typeName.Length - 1; while (true) { i = typeName.LastIndexOf('+', i); if (i < 0) { break; } bool evenSlashes = true; int iSlash = i; while (typeName[--iSlash] == '\\') { evenSlashes = !evenSlashes; } // Even number of slashes means this '+' is a name separator if (evenSlashes) { break; } i = iSlash; } return typeName.Substring(i + 1); } #region Internal Data Members // _TypeBuilder contains both TypeBuilder and EnumBuilder objects private Dictionary<string, Type> _typeBuilderDict = null!; internal ModuleBuilderData _moduleData = null!; internal RuntimeModule _internalModule; // This is the "external" AssemblyBuilder // only the "external" ModuleBuilder has this set private readonly AssemblyBuilder _assemblyBuilder; internal AssemblyBuilder ContainingAssemblyBuilder => _assemblyBuilder; #endregion #region Constructor internal ModuleBuilder(AssemblyBuilder assemblyBuilder, RuntimeModule internalModule) { _internalModule = internalModule; _assemblyBuilder = assemblyBuilder; } #endregion #region Private Members internal void AddType(string name, Type type) => _typeBuilderDict.Add(name, type); internal void CheckTypeNameConflict(string strTypeName, Type? enclosingType) { if (_typeBuilderDict.TryGetValue(strTypeName, out Type? foundType) && ReferenceEquals(foundType.DeclaringType, enclosingType)) { // Cannot have two types with the same name throw new ArgumentException(SR.Argument_DuplicateTypeName); } } private static Type? GetType(string strFormat, Type baseType) { // This function takes a string to describe the compound type, such as "[,][]", and a baseType. if (string.IsNullOrEmpty(strFormat)) { return baseType; } // convert the format string to byte array and then call FormCompoundType return SymbolType.FormCompoundType(strFormat, baseType, 0); } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetTypeRef", StringMarshalling = StringMarshalling.Utf16)] private static partial int GetTypeRef(QCallModule module, string strFullName, QCallModule refedModule, string? strRefedModuleFileName, int tkResolution); [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetMemberRef")] private static partial int GetMemberRef(QCallModule module, QCallModule refedModule, int tr, int defToken); private int GetMemberRef(Module? refedModule, int tr, int defToken) { ModuleBuilder thisModule = this; RuntimeModule refedRuntimeModule = GetRuntimeModuleFromModule(refedModule); return GetMemberRef(new QCallModule(ref thisModule), new QCallModule(ref refedRuntimeModule), tr, defToken); } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetMemberRefFromSignature", StringMarshalling = StringMarshalling.Utf16)] private static partial int GetMemberRefFromSignature(QCallModule module, int tr, string methodName, byte[] signature, int length); private int GetMemberRefFromSignature(int tr, string methodName, byte[] signature, int length) { ModuleBuilder thisModule = this; return GetMemberRefFromSignature(new QCallModule(ref thisModule), tr, methodName, signature, length); } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetMemberRefOfMethodInfo")] private static partial int GetMemberRefOfMethodInfo(QCallModule module, int tr, RuntimeMethodHandleInternal method); private int GetMemberRefOfMethodInfo(int tr, RuntimeMethodInfo method) { Debug.Assert(method != null); ModuleBuilder thisModule = this; int result = GetMemberRefOfMethodInfo(new QCallModule(ref thisModule), tr, ((IRuntimeMethodInfo)method).Value); GC.KeepAlive(method); return result; } private int GetMemberRefOfMethodInfo(int tr, RuntimeConstructorInfo method) { Debug.Assert(method != null); ModuleBuilder thisModule = this; int result = GetMemberRefOfMethodInfo(new QCallModule(ref thisModule), tr, ((IRuntimeMethodInfo)method).Value); GC.KeepAlive(method); return result; } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetMemberRefOfFieldInfo")] private static partial int GetMemberRefOfFieldInfo(QCallModule module, int tkType, QCallTypeHandle declaringType, int tkField); private int GetMemberRefOfFieldInfo(int tkType, RuntimeTypeHandle declaringType, RuntimeFieldInfo runtimeField) { Debug.Assert(runtimeField != null); ModuleBuilder thisModule = this; return GetMemberRefOfFieldInfo(new QCallModule(ref thisModule), tkType, new QCallTypeHandle(ref declaringType), runtimeField.MetadataToken); } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetTokenFromTypeSpec")] private static partial int GetTokenFromTypeSpec(QCallModule pModule, byte[] signature, int length); private int GetTokenFromTypeSpec(byte[] signature, int length) { ModuleBuilder thisModule = this; return GetTokenFromTypeSpec(new QCallModule(ref thisModule), signature, length); } [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetArrayMethodToken", StringMarshalling = StringMarshalling.Utf16)] private static partial int GetArrayMethodToken(QCallModule module, int tkTypeSpec, string methodName, byte[] signature, int sigLength); [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_GetStringConstant", StringMarshalling = StringMarshalling.Utf16)] private static partial int GetStringConstant(QCallModule module, string str, int length); [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "ModuleBuilder_SetFieldRVAContent")] internal static partial void SetFieldRVAContent(QCallModule module, int fdToken, byte[]? data, int length); #endregion #region Internal Members internal virtual Type? FindTypeBuilderWithName(string strTypeName, bool ignoreCase) { if (ignoreCase) { foreach (string name in _typeBuilderDict.Keys) { if (string.Equals(name, strTypeName, StringComparison.OrdinalIgnoreCase)) { return _typeBuilderDict[name]; } } } else { if (_typeBuilderDict.TryGetValue(strTypeName, out Type? foundType)) { return foundType; } } return null; } private int GetTypeRefNested(Type type, Module? refedModule, string? strRefedModuleFileName) { // This function will generate correct TypeRef token for top level type and nested type. Type? enclosingType = type.DeclaringType; int tkResolution = 0; string typeName = type.FullName!; if (enclosingType != null) { tkResolution = GetTypeRefNested(enclosingType, refedModule, strRefedModuleFileName); typeName = UnmangleTypeName(typeName); } Debug.Assert(!type.IsByRef, "Must not be ByRef. Get token from TypeSpec."); Debug.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments."); ModuleBuilder thisModule = this; RuntimeModule refedRuntimeModule = GetRuntimeModuleFromModule(refedModule); return GetTypeRef(new QCallModule(ref thisModule), typeName, new QCallModule(ref refedRuntimeModule), strRefedModuleFileName, tkResolution); } internal int InternalGetConstructorToken(ConstructorInfo con!!, bool usingRef) { // Helper to get constructor token. If usingRef is true, we will never use the def token int tr; int mr; if (con is ConstructorBuilder conBuilder) { if (!usingRef && conBuilder.Module.Equals(this)) return conBuilder.MetadataToken; // constructor is defined in a different module tr = GetTypeTokenInternal(con.ReflectedType!); mr = GetMemberRef(con.ReflectedType!.Module, tr, conBuilder.MetadataToken); } else if (con is ConstructorOnTypeBuilderInstantiation conOnTypeBuilderInst) { if (usingRef) throw new InvalidOperationException(); tr = GetTypeTokenInternal(con.DeclaringType!); mr = GetMemberRef(con.DeclaringType!.Module, tr, conOnTypeBuilderInst.MetadataToken); } else if (con is RuntimeConstructorInfo rtCon && !con.ReflectedType!.IsArray) { // constructor is not a dynamic field // We need to get the TypeRef tokens tr = GetTypeTokenInternal(con.ReflectedType); mr = GetMemberRefOfMethodInfo(tr, rtCon); } else { // some user derived ConstructorInfo // go through the slower code path, i.e. retrieve parameters and form signature helper. ParameterInfo[] parameters = con.GetParameters(); if (parameters == null) { throw new ArgumentException(SR.Argument_InvalidConstructorInfo); } Type[] parameterTypes = new Type[parameters.Length]; Type[][] requiredCustomModifiers = new Type[parameters.Length][]; Type[][] optionalCustomModifiers = new Type[parameters.Length][]; for (int i = 0; i < parameters.Length; i++) { if (parameters[i] == null) { throw new ArgumentException(SR.Argument_InvalidConstructorInfo); } parameterTypes[i] = parameters[i].ParameterType; requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers(); optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers(); } tr = GetTypeTokenInternal(con.ReflectedType!); SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(this, con.CallingConvention, null, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers); byte[] sigBytes = sigHelp.InternalGetSignature(out int length); mr = GetMemberRefFromSignature(tr, con.Name, sigBytes, length); } return mr; } internal void Init(string strModuleName) { _moduleData = new ModuleBuilderData(this, strModuleName); _typeBuilderDict = new Dictionary<string, Type>(); } internal object SyncRoot => ContainingAssemblyBuilder.SyncRoot; #endregion #region Module Overrides internal RuntimeModule InternalModule => _internalModule; protected override ModuleHandle GetModuleHandleImpl() => new ModuleHandle(InternalModule); private static RuntimeModule GetRuntimeModuleFromModule(Module? m) { ModuleBuilder? mb = m as ModuleBuilder; if (mb != null) { return mb.InternalModule; } return (m as RuntimeModule)!; } private int GetMemberRefToken(MethodBase method, Type[]? optionalParameterTypes) { int tkParent; int cGenericParameters = 0; SignatureHelper sigHelp; if (method.IsGenericMethod) { if (!method.IsGenericMethodDefinition) { throw new InvalidOperationException(); } cGenericParameters = method.GetGenericArguments().Length; } if (optionalParameterTypes != null) { if ((method.CallingConvention & CallingConventions.VarArgs) == 0) { // Client should not supply optional parameter in default calling convention throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention); } } MethodInfo? masmi = method as MethodInfo; if (method.DeclaringType!.IsGenericType) { MethodBase methDef = GetGenericMethodBaseDefinition(method); sigHelp = GetMemberRefSignature(methDef, cGenericParameters); } else { sigHelp = GetMemberRefSignature(method, cGenericParameters); } if (optionalParameterTypes?.Length > 0) { sigHelp.AddSentinel(); sigHelp.AddArguments(optionalParameterTypes, null, null); } byte[] sigBytes = sigHelp.InternalGetSignature(out int sigLength); if (method.DeclaringType!.IsGenericType) { byte[] sig = SignatureHelper.GetTypeSigToken(this, method.DeclaringType).InternalGetSignature(out int length); tkParent = GetTokenFromTypeSpec(sig, length); } else if (!method.Module.Equals(this)) { // Use typeRef as parent because the method's declaringType lives in a different assembly tkParent = GetTypeToken(method.DeclaringType); } else { // Use methodDef as parent because the method lives in this assembly and its declaringType has no generic arguments if (masmi != null) tkParent = GetMethodToken(masmi); else tkParent = GetConstructorToken((method as ConstructorInfo)!); } return GetMemberRefFromSignature(tkParent, method.Name, sigBytes, sigLength); } internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type? returnType, Type[]? parameterTypes, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers, Type[]? optionalParameterTypes, int cGenericParameters) { SignatureHelper sig = SignatureHelper.GetMethodSigHelper(this, call, cGenericParameters, returnType, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers); if (optionalParameterTypes != null && optionalParameterTypes.Length != 0) { sig.AddSentinel(); sig.AddArguments(optionalParameterTypes, null, null); } return sig; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Module.ResolveMethod is marked as RequiresUnreferencedCode because it relies on tokens " + "which are not guaranteed to be stable across trimming. So if somebody hardcodes a token it could break. " + "The usage here is not like that as all these tokens come from existing metadata loaded from some IL " + "and so trimming has no effect (the tokens are read AFTER trimming occured).")] private static MethodBase GetGenericMethodBaseDefinition(MethodBase methodBase) { // methodInfo = G<Foo>.M<Bar> ==> methDef = G<T>.M<S> MethodInfo? masmi = methodBase as MethodInfo; MethodBase methDef; if (methodBase is MethodOnTypeBuilderInstantiation motbi) { methDef = motbi.m_method; } else if (methodBase is ConstructorOnTypeBuilderInstantiation cotbi) { methDef = cotbi.m_ctor; } else if (methodBase is MethodBuilder || methodBase is ConstructorBuilder) { // methodInfo must be GenericMethodDefinition; trying to emit G<?>.M<S> methDef = methodBase; } else { Debug.Assert(methodBase is RuntimeMethodInfo || methodBase is RuntimeConstructorInfo); if (methodBase.IsGenericMethod) { Debug.Assert(masmi != null); methDef = masmi.GetGenericMethodDefinition()!; methDef = methDef.Module.ResolveMethod( methodBase.MetadataToken, methDef.DeclaringType?.GetGenericArguments(), methDef.GetGenericArguments())!; } else { methDef = methodBase.Module.ResolveMethod( methodBase.MetadataToken, methodBase.DeclaringType?.GetGenericArguments(), null)!; } } return methDef; } internal SignatureHelper GetMemberRefSignature(MethodBase? method, int cGenericParameters) { switch (method) { case MethodBuilder methodBuilder: return methodBuilder.GetMethodSignature(); case ConstructorBuilder constructorBuilder: return constructorBuilder.GetMethodSignature(); case MethodOnTypeBuilderInstantiation motbi when motbi.m_method is MethodBuilder methodBuilder: return methodBuilder.GetMethodSignature(); case MethodOnTypeBuilderInstantiation motbi: method = motbi.m_method; break; case ConstructorOnTypeBuilderInstantiation cotbi when cotbi.m_ctor is ConstructorBuilder constructorBuilder: return constructorBuilder.GetMethodSignature(); case ConstructorOnTypeBuilderInstantiation cotbi: method = cotbi.m_ctor; break; } Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); ParameterInfo[] parameters = method.GetParametersNoCopy(); Type[] parameterTypes = new Type[parameters.Length]; Type[][] requiredCustomModifiers = new Type[parameterTypes.Length][]; Type[][] optionalCustomModifiers = new Type[parameterTypes.Length][]; for (int i = 0; i < parameters.Length; i++) { parameterTypes[i] = parameters[i].ParameterType; requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers(); optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers(); } ParameterInfo? returnParameter = method is MethodInfo mi ? mi.ReturnParameter : null; SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(this, method.CallingConvention, cGenericParameters, returnParameter?.ParameterType, returnParameter?.GetRequiredCustomModifiers(), returnParameter?.GetOptionalCustomModifiers(), parameterTypes, requiredCustomModifiers, optionalCustomModifiers); return sigHelp; } #endregion public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); #region ICustomAttributeProvider Members public override object[] GetCustomAttributes(bool inherit) { return InternalModule.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return InternalModule.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return InternalModule.IsDefined(attributeType, inherit); } public override IList<CustomAttributeData> GetCustomAttributesData() { return InternalModule.GetCustomAttributesData(); } #endregion #region Module Overrides [RequiresUnreferencedCode("Types might be removed")] public override Type[] GetTypes() { lock (SyncRoot) { return GetTypesNoLock(); } } internal Type[] GetTypesNoLock() { Type[] typeList = new Type[_typeBuilderDict.Count]; int i = 0; foreach (Type builder in _typeBuilderDict.Values) { EnumBuilder? enumBldr = builder as EnumBuilder; TypeBuilder tmpTypeBldr; if (enumBldr != null) tmpTypeBldr = enumBldr.m_typeBuilder; else tmpTypeBldr = (TypeBuilder)builder; // We should not return TypeBuilders. // Otherwise anyone can emit code in it. if (tmpTypeBldr.IsCreated()) typeList[i++] = tmpTypeBldr.UnderlyingSystemType; else typeList[i++] = builder; } return typeList; } [RequiresUnreferencedCode("Types might be removed")] public override Type? GetType(string className) { return GetType(className, false, false); } [RequiresUnreferencedCode("Types might be removed")] public override Type? GetType(string className, bool ignoreCase) { return GetType(className, false, ignoreCase); } [RequiresUnreferencedCode("Types might be removed")] public override Type? GetType(string className, bool throwOnError, bool ignoreCase) { lock (SyncRoot) { return GetTypeNoLock(className, throwOnError, ignoreCase); } } [RequiresUnreferencedCode("Types might be removed")] private Type? GetTypeNoLock(string className, bool throwOnError, bool ignoreCase) { // public API to to a type. The reason that we need this function override from module // is because clients might need to get foo[] when foo is being built. For example, if // foo class contains a data member of type foo[]. // This API first delegate to the Module.GetType implementation. If succeeded, great! // If not, we have to look up the current module to find the TypeBuilder to represent the base // type and form the Type object for "foo[,]". // Module.GetType() will verify className. Type? baseType = InternalModule.GetType(className, throwOnError, ignoreCase); if (baseType != null) return baseType; // Now try to see if we contain a TypeBuilder for this type or not. // Might have a compound type name, indicated via an unescaped // '[', '*' or '&'. Split the name at this point. string? baseName = null; string? parameters = null; int startIndex = 0; while (startIndex <= className.Length) { // Are there any possible special characters left? int i = className.AsSpan(startIndex).IndexOfAny('[', '*', '&'); if (i < 0) { // No, type name is simple. baseName = className; parameters = null; break; } i += startIndex; // Found a potential special character, but it might be escaped. int slashes = 0; for (int j = i - 1; j >= 0 && className[j] == '\\'; j--) slashes++; // Odd number of slashes indicates escaping. if (slashes % 2 == 1) { startIndex = i + 1; continue; } // Found the end of the base type name. baseName = className.Substring(0, i); parameters = className.Substring(i); break; } // If we didn't find a basename yet, the entire class name is // the base name and we don't have a composite type. if (baseName == null) { baseName = className; parameters = null; } baseName = baseName.Replace(@"\\", @"\").Replace(@"\[", "[").Replace(@"\*", "*").Replace(@"\&", "&"); if (parameters != null) { // try to see if reflection can find the base type. It can be such that reflection // does not support the complex format string yet! baseType = InternalModule.GetType(baseName, false, ignoreCase); } if (baseType == null) { // try to find it among the unbaked types. // starting with the current module first of all. baseType = FindTypeBuilderWithName(baseName, ignoreCase); if (baseType == null && Assembly is AssemblyBuilder) { // now goto Assembly level to find the type. List<ModuleBuilder> modList = ContainingAssemblyBuilder._assemblyData._moduleBuilderList; int size = modList.Count; for (int i = 0; i < size && baseType == null; i++) { ModuleBuilder mBuilder = modList[i]; baseType = mBuilder.FindTypeBuilderWithName(baseName, ignoreCase); } } if (baseType == null) { return null; } } if (parameters == null) { return baseType; } return GetType(parameters, baseType); } [RequiresAssemblyFiles(UnknownStringMessageInRAF)] public override string FullyQualifiedName => _moduleData._moduleName; [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override byte[] ResolveSignature(int metadataToken) { return InternalModule.ResolveSignature(metadataToken); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override MethodBase? ResolveMethod(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override FieldInfo? ResolveField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override Type ResolveType(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override MemberInfo? ResolveMember(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override string ResolveString(int metadataToken) { return InternalModule.ResolveString(metadataToken); } public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) { InternalModule.GetPEKind(out peKind, out machine); } public override int MDStreamVersion => InternalModule.MDStreamVersion; public override Guid ModuleVersionId => InternalModule.ModuleVersionId; public override int MetadataToken => InternalModule.MetadataToken; public override bool IsResource() => InternalModule.IsResource(); [RequiresUnreferencedCode("Fields might be removed")] public override FieldInfo[] GetFields(BindingFlags bindingFlags) { return InternalModule.GetFields(bindingFlags); } [RequiresUnreferencedCode("Fields might be removed")] public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { return InternalModule.GetField(name, bindingAttr); } [RequiresUnreferencedCode("Methods might be removed")] public override MethodInfo[] GetMethods(BindingFlags bindingFlags) { return InternalModule.GetMethods(bindingFlags); } [RequiresUnreferencedCode("Methods might be removed")] protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { // Cannot call InternalModule.GetMethods because it doesn't allow types to be null return InternalModule.GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers); } public override string ScopeName => InternalModule.ScopeName; [RequiresAssemblyFiles(UnknownStringMessageInRAF)] public override string Name => InternalModule.Name; public override Assembly Assembly => _assemblyBuilder; #endregion #region Public Members #region Define Type public TypeBuilder DefineType(string name) { lock (SyncRoot) { return DefineTypeNoLock(name, TypeAttributes.NotPublic, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); } } public TypeBuilder DefineType(string name, TypeAttributes attr) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); } } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent) { lock (SyncRoot) { AssemblyBuilder.CheckContext(parent); return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); } } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, int typesize) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, typesize); } } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, PackingSize packingSize, int typesize) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, null, packingSize, typesize); } } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, Type[]? interfaces) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize); } } private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, Type[]? interfaces, PackingSize packingSize, int typesize) { return new TypeBuilder(name, attr, parent, interfaces, this, packingSize, typesize, null); } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, PackingSize packsize) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, packsize); } } private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, PackingSize packsize) { return new TypeBuilder(name, attr, parent, null, this, packsize, TypeBuilder.UnspecifiedTypeSize, null); } #endregion #region Define Enum // This API can only be used to construct a top-level (not nested) enum type. // Nested enum types can be defined manually using ModuleBuilder.DefineType. public EnumBuilder DefineEnum(string name, TypeAttributes visibility, Type underlyingType) { AssemblyBuilder.CheckContext(underlyingType); lock (SyncRoot) { EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType); // This enum is not generic, nested, and cannot have any element type. // Replace the TypeBuilder object in _typeBuilderDict with this EnumBuilder object. _typeBuilderDict[name] = enumBuilder; return enumBuilder; } } private EnumBuilder DefineEnumNoLock(string name, TypeAttributes visibility, Type underlyingType) { return new EnumBuilder(name, underlyingType, visibility, this); } #endregion #region Define Global Method [RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")] public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { return DefinePInvokeMethod(name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); } [RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")] public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { lock (SyncRoot) { // Global methods must be static. if ((attributes & MethodAttributes.Static) == 0) { throw new ArgumentException(SR.Argument_GlobalFunctionHasToBeStatic); } AssemblyBuilder.CheckContext(returnType); AssemblyBuilder.CheckContext(parameterTypes); return _moduleData._globalTypeBuilder.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); } } public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, Type? returnType, Type[]? parameterTypes) { return DefineGlobalMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes); } public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes) { return DefineGlobalMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null); } public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { lock (SyncRoot) { return DefineGlobalMethodNoLock(name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } } private MethodBuilder DefineGlobalMethodNoLock(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { if (_moduleData._hasGlobalBeenCreated) { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } ArgumentException.ThrowIfNullOrEmpty(name); if ((attributes & MethodAttributes.Static) == 0) { throw new ArgumentException(SR.Argument_GlobalFunctionHasToBeStatic); } AssemblyBuilder.CheckContext(returnType); AssemblyBuilder.CheckContext(requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes); AssemblyBuilder.CheckContext(requiredParameterTypeCustomModifiers); AssemblyBuilder.CheckContext(optionalParameterTypeCustomModifiers); return _moduleData._globalTypeBuilder.DefineMethod(name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } public void CreateGlobalFunctions() { lock (SyncRoot) { CreateGlobalFunctionsNoLock(); } } private void CreateGlobalFunctionsNoLock() { if (_moduleData._hasGlobalBeenCreated) { // cannot create globals twice throw new InvalidOperationException(SR.InvalidOperation_NotADebugModule); } _moduleData._globalTypeBuilder.CreateType(); _moduleData._hasGlobalBeenCreated = true; } #endregion #region Define Data public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttributes attributes) { // This method will define an initialized Data in .sdata. // We will create a fake TypeDef to represent the data with size. This TypeDef // will be the signature for the Field. lock (SyncRoot) { return DefineInitializedDataNoLock(name, data, attributes); } } private FieldBuilder DefineInitializedDataNoLock(string name, byte[] data, FieldAttributes attributes) { // This method will define an initialized Data in .sdata. // We will create a fake TypeDef to represent the data with size. This TypeDef // will be the signature for the Field. if (_moduleData._hasGlobalBeenCreated) { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } return _moduleData._globalTypeBuilder.DefineInitializedData(name, data, attributes); } public FieldBuilder DefineUninitializedData(string name, int size, FieldAttributes attributes) { lock (SyncRoot) { return DefineUninitializedDataNoLock(name, size, attributes); } } private FieldBuilder DefineUninitializedDataNoLock(string name, int size, FieldAttributes attributes) { // This method will define an uninitialized Data in .sdata. // We will create a fake TypeDef to represent the data with size. This TypeDef // will be the signature for the Field. if (_moduleData._hasGlobalBeenCreated) { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } return _moduleData._globalTypeBuilder.DefineUninitializedData(name, size, attributes); } #endregion #region GetToken // For a generic type definition, we should return the token for the generic type definition itself in two cases: // 1. GetTypeToken // 2. ldtoken (see ILGenerator) // For all other occasions we should return the generic type instantiated on its formal parameters. internal int GetTypeTokenInternal(Type type) { return GetTypeTokenInternal(type, getGenericDefinition: false); } private int GetTypeTokenInternal(Type type, bool getGenericDefinition) { lock (SyncRoot) { return GetTypeTokenWorkerNoLock(type, getGenericDefinition); } } internal int GetTypeToken(Type type) { return GetTypeTokenInternal(type, getGenericDefinition: true); } private int GetTypeTokenWorkerNoLock(Type type!!, bool getGenericDefinition) { AssemblyBuilder.CheckContext(type); // Return a token for the class relative to the Module. Tokens // are used to indentify objects when the objects are used in IL // instructions. Tokens are always relative to the Module. For example, // the token value for System.String is likely to be different from // Module to Module. Calling GetTypeToken will cause a reference to be // added to the Module. This reference becomes a permanent part of the Module, // multiple calls to this method with the same class have no additional side-effects. // This function is optimized to use the TypeDef token if the Type is within the // same module. We should also be aware of multiple dynamic modules and multiple // implementations of a Type. if ((type.IsGenericType && (!type.IsGenericTypeDefinition || !getGenericDefinition)) || type.IsGenericParameter || type.IsArray || type.IsPointer || type.IsByRef) { byte[] sig = SignatureHelper.GetTypeSigToken(this, type).InternalGetSignature(out int length); return GetTokenFromTypeSpec(sig, length); } Module refedModule = type.Module; if (refedModule.Equals(this)) { // no need to do anything additional other than defining the TypeRef Token TypeBuilder? typeBuilder; EnumBuilder? enumBuilder = type as EnumBuilder; typeBuilder = enumBuilder != null ? enumBuilder.m_typeBuilder : type as TypeBuilder; if (typeBuilder != null) { // If the type is defined in this module, just return the token. return typeBuilder.TypeToken; } else if (type is GenericTypeParameterBuilder paramBuilder) { return paramBuilder.MetadataToken; } return GetTypeRefNested(type, this, string.Empty); } // After this point, the referenced module is not the same as the referencing // module. ModuleBuilder? refedModuleBuilder = refedModule as ModuleBuilder; string referencedModuleFileName = string.Empty; if (refedModule.Assembly.Equals(Assembly)) { // if the referenced module is in the same assembly, the resolution // scope of the type token will be a module ref, we will need // the file name of the referenced module for that. // if the refed module is in a different assembly, the resolution // scope of the type token will be an assembly ref. We don't need // the file name of the referenced module. if (refedModuleBuilder == null) { refedModuleBuilder = ContainingAssemblyBuilder.GetModuleBuilder((RuntimeModule)refedModule); } referencedModuleFileName = refedModuleBuilder._moduleData._moduleName; } return GetTypeRefNested(type, refedModule, referencedModuleFileName); } internal int GetMethodToken(MethodInfo method) { lock (SyncRoot) { return GetMethodTokenNoLock(method, false); } } // For a method on a generic type, we should return the methoddef token on the generic type definition in two cases // 1. GetMethodToken // 2. ldtoken (see ILGenerator) // For all other occasions we should return the method on the generic type instantiated on the formal parameters. private int GetMethodTokenNoLock(MethodInfo method!!, bool getGenericTypeDefinition) { // Return a MemberRef token if MethodInfo is not defined in this module. Or // return the MethodDef token. int tr; int mr; if (method is MethodBuilder methBuilder) { int methodToken = methBuilder.MetadataToken; if (method.Module.Equals(this)) { return methodToken; } if (method.DeclaringType == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } // method is defined in a different module tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType) : GetTypeTokenInternal(method.DeclaringType); mr = GetMemberRef(method.DeclaringType.Module, tr, methodToken); } else if (method is MethodOnTypeBuilderInstantiation) { return GetMemberRefToken(method, null); } else if (method is SymbolMethod symMethod) { if (symMethod.GetModule() == this) return symMethod.MetadataToken; // form the method token return symMethod.GetToken(this); } else { Type? declaringType = method.DeclaringType; // We need to get the TypeRef tokens if (declaringType == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } if (declaringType.IsArray) { // use reflection to build signature to work around the E_T_VAR problem in EEClass ParameterInfo[] paramInfo = method.GetParameters(); Type[] tt = new Type[paramInfo.Length]; for (int i = 0; i < paramInfo.Length; i++) tt[i] = paramInfo[i].ParameterType; return GetArrayMethodToken(declaringType, method.Name, method.CallingConvention, method.ReturnType, tt); } else if (method is RuntimeMethodInfo rtMeth) { tr = getGenericTypeDefinition ? GetTypeToken(declaringType) : GetTypeTokenInternal(declaringType); mr = GetMemberRefOfMethodInfo(tr, rtMeth); } else { // some user derived ConstructorInfo // go through the slower code path, i.e. retrieve parameters and form signature helper. ParameterInfo[] parameters = method.GetParameters(); Type[] parameterTypes = new Type[parameters.Length]; Type[][] requiredCustomModifiers = new Type[parameterTypes.Length][]; Type[][] optionalCustomModifiers = new Type[parameterTypes.Length][]; for (int i = 0; i < parameters.Length; i++) { parameterTypes[i] = parameters[i].ParameterType; requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers(); optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers(); } tr = getGenericTypeDefinition ? GetTypeToken(declaringType) : GetTypeTokenInternal(declaringType); SignatureHelper sigHelp; try { sigHelp = SignatureHelper.GetMethodSigHelper( this, method.CallingConvention, method.ReturnType, method.ReturnParameter.GetRequiredCustomModifiers(), method.ReturnParameter.GetOptionalCustomModifiers(), parameterTypes, requiredCustomModifiers, optionalCustomModifiers); } catch (NotImplementedException) { // Legacy code deriving from MethodInfo may not have implemented ReturnParameter. sigHelp = SignatureHelper.GetMethodSigHelper(this, method.ReturnType, parameterTypes); } byte[] sigBytes = sigHelp.InternalGetSignature(out int length); mr = GetMemberRefFromSignature(tr, method.Name, sigBytes, length); } } return mr; } internal int GetMethodTokenInternal(MethodBase method, Type[]? optionalParameterTypes, bool useMethodDef) { int tk; MethodInfo? methodInfo = method as MethodInfo; if (method.IsGenericMethod) { // Constructors cannot be generic. Debug.Assert(methodInfo != null); // Given M<Bar> unbind to M<S> MethodInfo methodInfoUnbound = methodInfo; bool isGenericMethodDef = methodInfo.IsGenericMethodDefinition; if (!isGenericMethodDef) { methodInfoUnbound = methodInfo.GetGenericMethodDefinition()!; } if (!Equals(methodInfoUnbound.Module) || (methodInfoUnbound.DeclaringType != null && methodInfoUnbound.DeclaringType.IsGenericType)) { tk = GetMemberRefToken(methodInfoUnbound, null); } else { tk = GetMethodToken(methodInfoUnbound); } // For Ldtoken, Ldftn, and Ldvirtftn, we should emit the method def/ref token for a generic method definition. if (isGenericMethodDef && useMethodDef) { return tk; } // Create signature of method instantiation M<Bar> // Create MethodSepc M<Bar> with parent G?.M<S> byte[] sigBytes = SignatureHelper.GetMethodSpecSigHelper( this, methodInfo.GetGenericArguments()).InternalGetSignature(out int sigLength); ModuleBuilder thisModule = this; tk = TypeBuilder.DefineMethodSpec(new QCallModule(ref thisModule), tk, sigBytes, sigLength); } else { if (((method.CallingConvention & CallingConventions.VarArgs) == 0) && (method.DeclaringType == null || !method.DeclaringType.IsGenericType)) { if (methodInfo != null) { tk = GetMethodToken(methodInfo); } else { tk = GetConstructorToken((method as ConstructorInfo)!); } } else { tk = GetMemberRefToken(method, optionalParameterTypes); } } return tk; } internal int GetArrayMethodToken(Type arrayClass, string methodName, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes) { lock (SyncRoot) { return GetArrayMethodTokenNoLock(arrayClass, methodName, callingConvention, returnType, parameterTypes); } } private int GetArrayMethodTokenNoLock(Type arrayClass, string methodName, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes) { ArgumentNullException.ThrowIfNull(arrayClass); ArgumentException.ThrowIfNullOrEmpty(methodName); if (!arrayClass.IsArray) { throw new ArgumentException(SR.Argument_HasToBeArrayClass); } AssemblyBuilder.CheckContext(returnType, arrayClass); AssemblyBuilder.CheckContext(parameterTypes); // Return a token for the MethodInfo for a method on an Array. This is primarily // used to get the LoadElementAddress method. SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper( this, callingConvention, returnType, null, null, parameterTypes, null, null); byte[] sigBytes = sigHelp.InternalGetSignature(out int length); int typeSpec = GetTypeTokenInternal(arrayClass); ModuleBuilder thisModule = this; return GetArrayMethodToken(new QCallModule(ref thisModule), typeSpec, methodName, sigBytes, length); } public MethodInfo GetArrayMethod(Type arrayClass, string methodName, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes) { AssemblyBuilder.CheckContext(returnType, arrayClass); AssemblyBuilder.CheckContext(parameterTypes); // GetArrayMethod is useful when you have an array of a type whose definition has not been completed and // you want to access methods defined on Array. For example, you might define a type and want to define a // method that takes an array of the type as a parameter. In order to access the elements of the array, // you will need to call methods of the Array class. int token = GetArrayMethodToken(arrayClass, methodName, callingConvention, returnType, parameterTypes); return new SymbolMethod(this, token, arrayClass, methodName, callingConvention, returnType, parameterTypes); } internal int GetConstructorToken(ConstructorInfo con) { // Return a token for the ConstructorInfo relative to the Module. return InternalGetConstructorToken(con, false); } internal int GetFieldToken(FieldInfo field) { lock (SyncRoot) { return GetFieldTokenNoLock(field); } } private int GetFieldTokenNoLock(FieldInfo field!!) { int tr; int mr; if (field is FieldBuilder fdBuilder) { if (field.DeclaringType != null && field.DeclaringType.IsGenericType) { byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out int length); tr = GetTokenFromTypeSpec(sig, length); mr = GetMemberRef(this, tr, fdBuilder.MetadataToken); } else if (fdBuilder.Module.Equals(this)) { // field is defined in the same module return fdBuilder.MetadataToken; } else { // field is defined in a different module if (field.DeclaringType == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } tr = GetTypeTokenInternal(field.DeclaringType); mr = GetMemberRef(field.ReflectedType!.Module, tr, fdBuilder.MetadataToken); } } else if (field is RuntimeFieldInfo rtField) { // FieldInfo is not an dynamic field // We need to get the TypeRef tokens if (field.DeclaringType == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } if (field.DeclaringType != null && field.DeclaringType.IsGenericType) { byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out int length); tr = GetTokenFromTypeSpec(sig, length); mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType.TypeHandle, rtField); } else { tr = GetTypeTokenInternal(field.DeclaringType!); mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType!.TypeHandle, rtField); } } else if (field is FieldOnTypeBuilderInstantiation fOnTB) { FieldInfo fb = fOnTB.FieldInfo; byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType!).InternalGetSignature(out int length); tr = GetTokenFromTypeSpec(sig, length); mr = GetMemberRef(fb.ReflectedType!.Module, tr, fOnTB.MetadataToken); } else { // user defined FieldInfo tr = GetTypeTokenInternal(field.ReflectedType!); SignatureHelper sigHelp = SignatureHelper.GetFieldSigHelper(this); sigHelp.AddArgument(field.FieldType, field.GetRequiredCustomModifiers(), field.GetOptionalCustomModifiers()); byte[] sigBytes = sigHelp.InternalGetSignature(out int length); mr = GetMemberRefFromSignature(tr, field.Name, sigBytes, length); } return mr; } internal int GetStringConstant(string str!!) { // Returns a token representing a String constant. If the string // value has already been defined, the existing token will be returned. ModuleBuilder thisModule = this; return GetStringConstant(new QCallModule(ref thisModule), str, str.Length); } internal int GetSignatureToken(SignatureHelper sigHelper!!) { // Define signature token given a signature helper. This will define a metadata // token for the signature described by SignatureHelper. // Get the signature in byte form. byte[] sigBytes = sigHelper.InternalGetSignature(out int sigLength); ModuleBuilder thisModule = this; return TypeBuilder.GetTokenFromSig(new QCallModule(ref thisModule), sigBytes, sigLength); } internal int GetSignatureToken(byte[] sigBytes!!, int sigLength) { byte[] localSigBytes = new byte[sigBytes.Length]; Buffer.BlockCopy(sigBytes, 0, localSigBytes, 0, sigBytes.Length); ModuleBuilder thisModule = this; return TypeBuilder.GetTokenFromSig(new QCallModule(ref thisModule), localSigBytes, sigLength); } #endregion #region Other public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) { TypeBuilder.DefineCustomAttribute( this, 1, // This is hard coding the module token to 1 GetConstructorToken(con), binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!) { customBuilder.CreateCustomAttribute(this, 1); // This is hard coding the module token to 1 } #endregion #endregion } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; using System.IO; using System.IO.Strategies; using System.Threading; namespace Microsoft.Win32.SafeHandles { public sealed partial class SafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid { internal static bool DisableFileLocking { get; } = OperatingSystem.IsBrowser() // #40065: Emscripten does not support file locking || AppContextConfigHelper.GetBooleanConfig("System.IO.DisableFileLocking", "DOTNET_SYSTEM_IO_DISABLEFILELOCKING", defaultValue: false); // not using bool? as it's not thread safe private volatile NullableBool _canSeek = NullableBool.Undefined; private volatile NullableBool _supportsRandomAccess = NullableBool.Undefined; private bool _deleteOnClose; private bool _isLocked; public SafeFileHandle() : this(ownsHandle: true) { } private SafeFileHandle(bool ownsHandle) : base(ownsHandle) { SetHandle(new IntPtr(-1)); } public bool IsAsync { get; private set; } internal bool CanSeek => !IsClosed && GetCanSeek(); internal bool SupportsRandomAccess { get { NullableBool supportsRandomAccess = _supportsRandomAccess; if (supportsRandomAccess == NullableBool.Undefined) { _supportsRandomAccess = supportsRandomAccess = GetCanSeek() ? NullableBool.True : NullableBool.False; } return supportsRandomAccess == NullableBool.True; } set { Debug.Assert(value == false); // We should only use the setter to disable random access. _supportsRandomAccess = value ? NullableBool.True : NullableBool.False; } } internal ThreadPoolBoundHandle? ThreadPoolBinding => null; internal void EnsureThreadPoolBindingInitialized() { /* nop */ } internal bool TryGetCachedLength(out long cachedLength) { cachedLength = -1; return false; } private static SafeFileHandle Open(string path, Interop.Sys.OpenFlags flags, int mode, Func<Interop.ErrorInfo, Interop.Sys.OpenFlags, string, Exception?>? createOpenException) { Debug.Assert(path != null); SafeFileHandle handle = Interop.Sys.Open(path, flags, mode); handle._path = path; if (handle.IsInvalid) { Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); handle.Dispose(); if (createOpenException?.Invoke(error, flags, path) is Exception ex) { throw ex; } // If we fail to open the file due to a path not existing, we need to know whether to blame // the file itself or its directory. If we're creating the file, then we blame the directory, // otherwise we blame the file. // // When opening, we need to align with Windows, which considers a missing path to be // FileNotFound only if the containing directory exists. bool isDirectory = (error.Error == Interop.Error.ENOENT) && ((flags & Interop.Sys.OpenFlags.O_CREAT) != 0 || !DirectoryExists(System.IO.Path.GetDirectoryName(System.IO.Path.TrimEndingDirectorySeparator(path!))!)); Interop.CheckIo( error.Error, path, isDirectory, errorRewriter: e => (e.Error == Interop.Error.EISDIR) ? Interop.Error.EACCES.Info() : e); } return handle; } private static bool DirectoryExists(string fullPath) { Interop.Sys.FileStatus fileinfo; if (Interop.Sys.Stat(fullPath, out fileinfo) < 0) { return false; } return ((fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR); } // Each thread will have its own copy. This prevents race conditions if the handle had the last error. [ThreadStatic] internal static Interop.ErrorInfo? t_lastCloseErrorInfo; protected override bool ReleaseHandle() { // If DeleteOnClose was requested when constructed, delete the file now. // (Unix doesn't directly support DeleteOnClose, so we mimic it here.) // We delete the file before releasing the lock to detect the removal in Init. if (_deleteOnClose) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed, but the // name will be removed immediately. Debug.Assert(_path is not null); Interop.Sys.Unlink(_path); // ignore errors; it's valid that the path may no longer exist } // When the SafeFileHandle was opened, we likely issued an flock on the created descriptor in order to add // an advisory lock. This lock should be removed via closing the file descriptor, but close can be // interrupted, and we don't retry closes. As such, we could end up leaving the file locked, // which could prevent subsequent usage of the file until this process dies. To avoid that, we proactively // try to release the lock before we close the handle. if (_isLocked) { Interop.Sys.FLock(handle, Interop.Sys.LockOperations.LOCK_UN); // ignore any errors _isLocked = false; } // Close the descriptor. Although close is documented to potentially fail with EINTR, we never want // to retry, as the descriptor could actually have been closed, been subsequently reassigned, and // be in use elsewhere in the process. Instead, we simply check whether the call was successful. int result = Interop.Sys.Close(handle); if (result != 0) { t_lastCloseErrorInfo = Interop.Sys.GetLastErrorInfo(); } return result == 0; } public override bool IsInvalid { get { long h = (long)handle; return h < 0 || h > int.MaxValue; } } // If the file gets created a new, we'll select the permissions for it. Most Unix utilities by default use 666 (read and // write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out // a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the // actual permissions will typically be less than what we select here. private const Interop.Sys.Permissions DefaultOpenPermissions = Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH; // Specialized Open that returns the file length and permissions of the opened file. // This information is retrieved from the 'stat' syscall that must be performed to ensure the path is not a directory. internal static SafeFileHandle OpenReadOnly(string fullPath, FileOptions options, out long fileLength, out Interop.Sys.Permissions filePermissions) { SafeFileHandle handle = Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, options, preallocationSize: 0, DefaultOpenPermissions, out fileLength, out filePermissions, null); Debug.Assert(fileLength >= 0); return handle; } internal static SafeFileHandle Open(string fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize, Interop.Sys.Permissions openPermissions = DefaultOpenPermissions, Func<Interop.ErrorInfo, Interop.Sys.OpenFlags, string, Exception?>? createOpenException = null) { return Open(fullPath, mode, access, share, options, preallocationSize, openPermissions, out _, out _, createOpenException); } private static SafeFileHandle Open(string fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize, Interop.Sys.Permissions openPermissions, out long fileLength, out Interop.Sys.Permissions filePermissions, Func<Interop.ErrorInfo, Interop.Sys.OpenFlags, string, Exception?>? createOpenException = null) { // Translate the arguments into arguments for an open call. Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, access, share, options); SafeFileHandle? safeFileHandle = null; try { while (true) { safeFileHandle = Open(fullPath, openFlags, (int)openPermissions, createOpenException); // When Init return false, the path has changed to another file entry, and // we need to re-open the path to reflect that. if (safeFileHandle.Init(fullPath, mode, access, share, options, preallocationSize, out fileLength, out filePermissions)) { return safeFileHandle; } else { safeFileHandle.Dispose(); } } } catch (Exception) { safeFileHandle?.Dispose(); throw; } } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="share">The FileShare provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileShare share, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.Sys.OpenFlags flags = default; switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. break; case FileMode.Truncate: if (DisableFileLocking) { // if we don't lock the file, we can truncate it when opening // otherwise we truncate the file after getting the lock flags |= Interop.Sys.OpenFlags.O_TRUNC; } break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: flags |= Interop.Sys.OpenFlags.O_CREAT; break; case FileMode.Create: flags |= Interop.Sys.OpenFlags.O_CREAT; if (DisableFileLocking) { flags |= Interop.Sys.OpenFlags.O_TRUNC; } break; case FileMode.CreateNew: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL); break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.Sys.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.Sys.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.Sys.OpenFlags.O_WRONLY; break; } // Handle Inheritable, other FileShare flags are handled by Init if ((share & FileShare.Inheritable) == 0) { flags |= Interop.Sys.OpenFlags.O_CLOEXEC; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. // - Asynchronous: Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true // - DeleteOnClose: Doesn't have a Unix equivalent, but we approximate it in Dispose // - Encrypted: No equivalent on Unix and is ignored // - RandomAccess: Implemented after open if posix_fadvise is available // - SequentialScan: Implemented after open if posix_fadvise is available // - WriteThrough: Handled here if ((options & FileOptions.WriteThrough) != 0) { flags |= Interop.Sys.OpenFlags.O_SYNC; } return flags; } private bool Init(string path, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize, out long fileLength, out Interop.Sys.Permissions filePermissions) { Interop.Sys.FileStatus status = default; bool statusHasValue = false; fileLength = -1; filePermissions = 0; // Make sure our handle is not a directory. // We can omit the check when write access is requested. open will have failed with EISDIR. if ((access & FileAccess.Write) == 0) { // Stat the file descriptor to avoid race conditions. FStatCheckIO(path, ref status, ref statusHasValue); if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR) { throw Interop.GetExceptionForIoErrno(Interop.Error.EACCES.Info(), path, isDirectory: true); } if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFREG) { // we take advantage of the information provided by the fstat syscall // and for regular files (most common case) // avoid one extra sys call for determining whether file can be seeked _canSeek = NullableBool.True; Debug.Assert(Interop.Sys.LSeek(this, 0, Interop.Sys.SeekWhence.SEEK_CUR) >= 0); } fileLength = status.Size; filePermissions = (Interop.Sys.Permissions)(status.Mode & (int)Interop.Sys.Permissions.Mask); } IsAsync = (options & FileOptions.Asynchronous) != 0; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH; if (CanLockTheFile(lockOperation, access) && !(_isLocked = Interop.Sys.FLock(this, lockOperation | Interop.Sys.LockOperations.LOCK_NB) >= 0)) { // The only error we care about is EWOULDBLOCK, which indicates that the file is currently locked by someone // else and we would block trying to access it. Other errors, such as ENOTSUP (locking isn't supported) or // EACCES (the file system doesn't allow us to lock), will only hamper FileStream's usage without providing value, // given again that this is only advisory / best-effort. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EWOULDBLOCK) { throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory: false); } } // On Windows, DeleteOnClose happens when all kernel handles to the file are closed. // Unix kernels don't have this feature, and .NET deletes the file when the Handle gets disposed. // When the file is opened with an exclusive lock, we can use it to check the file at the path // still matches the file we've opened. // When the delete is performed by another .NET Handle, it holds the lock during the delete. // Since we've just obtained the lock, the file will already be removed/replaced. // We limit performing this check to cases where our file was opened with DeleteOnClose with // a mode of OpenOrCreate. if (_isLocked && ((options & FileOptions.DeleteOnClose) != 0) && share == FileShare.None && mode == FileMode.OpenOrCreate) { FStatCheckIO(path, ref status, ref statusHasValue); Interop.Sys.FileStatus pathStatus; if (Interop.Sys.Stat(path, out pathStatus) < 0) { // If the file was removed, re-open. // Otherwise throw the error 'stat' gave us (assuming this is the // error 'open' will give us if we'd call it now). Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); if (error.Error == Interop.Error.ENOENT) { return false; } throw Interop.GetExceptionForIoErrno(error, path); } if (pathStatus.Ino != status.Ino || pathStatus.Dev != status.Dev) { // The file was replaced, re-open return false; } } // Enable DeleteOnClose when we've succesfully locked the file. // On Windows, the locking happens atomically as part of opening the file. _deleteOnClose = (options & FileOptions.DeleteOnClose) != 0; // These provide hints around how the file will be accessed. Specifying both RandomAccess // and Sequential together doesn't make sense as they are two competing options on the same spectrum, // so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided). Interop.Sys.FileAdvice fadv = (options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM : (options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL : 0; if (fadv != 0) { FileStreamHelpers.CheckFileCall(Interop.Sys.PosixFAdvise(this, 0, 0, fadv), path, ignoreNotSupported: true); // just a hint. } if ((mode == FileMode.Create || mode == FileMode.Truncate) && !DisableFileLocking) { // Truncate the file now if the file mode requires it. This ensures that the file only will be truncated // if opened successfully. if (Interop.Sys.FTruncate(this, 0) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error != Interop.Error.EBADF && errorInfo.Error != Interop.Error.EINVAL) { // We know the file descriptor is valid and we know the size argument to FTruncate is correct, // so if EBADF or EINVAL is returned, it means we're dealing with a special file that can't be // truncated. Ignore the error in such cases; in all others, throw. throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory: false); } } } if (preallocationSize > 0 && Interop.Sys.FAllocate(this, 0, preallocationSize) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); // Only throw for errors that indicate there is not enough space. if (errorInfo.Error == Interop.Error.EFBIG || errorInfo.Error == Interop.Error.ENOSPC) { Dispose(); // Delete the file we've created. Debug.Assert(mode == FileMode.Create || mode == FileMode.CreateNew); Interop.Sys.Unlink(path!); throw new IOException(SR.Format(errorInfo.Error == Interop.Error.EFBIG ? SR.IO_FileTooLarge_Path_AllocationSize : SR.IO_DiskFull_Path_AllocationSize, path, preallocationSize)); } } return true; } private bool CanLockTheFile(Interop.Sys.LockOperations lockOperation, FileAccess access) { Debug.Assert(lockOperation == Interop.Sys.LockOperations.LOCK_EX || lockOperation == Interop.Sys.LockOperations.LOCK_SH); if (DisableFileLocking) { return false; } else if (lockOperation == Interop.Sys.LockOperations.LOCK_EX) { return true; // LOCK_EX is always OK } else if ((access & FileAccess.Write) == 0) { return true; // LOCK_SH is always OK when reading } if (!Interop.Sys.TryGetFileSystemType(this, out Interop.Sys.UnixFileSystemTypes unixFileSystemType)) { return false; // assume we should not acquire the lock if we don't know the File System } switch (unixFileSystemType) { case Interop.Sys.UnixFileSystemTypes.nfs: // #44546 case Interop.Sys.UnixFileSystemTypes.smb: case Interop.Sys.UnixFileSystemTypes.smb2: // #53182 case Interop.Sys.UnixFileSystemTypes.cifs: return false; // LOCK_SH is not OK when writing to NFS, CIFS or SMB default: return true; // in all other situations it should be OK } } private void FStatCheckIO(string path, ref Interop.Sys.FileStatus status, ref bool statusHasValue) { if (!statusHasValue) { if (Interop.Sys.FStat(this, out status) != 0) { Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); throw Interop.GetExceptionForIoErrno(error, path); } statusHasValue = true; } } private bool GetCanSeek() { Debug.Assert(!IsClosed); Debug.Assert(!IsInvalid); NullableBool canSeek = _canSeek; if (canSeek == NullableBool.Undefined) { _canSeek = canSeek = Interop.Sys.LSeek(this, 0, Interop.Sys.SeekWhence.SEEK_CUR) >= 0 ? NullableBool.True : NullableBool.False; } return canSeek == NullableBool.True; } internal long GetFileLength() { int result = Interop.Sys.FStat(this, out Interop.Sys.FileStatus status); FileStreamHelpers.CheckFileCall(result, Path); return status.Size; } private enum NullableBool { Undefined = 0, False = -1, True = 1 } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; using System.IO; using System.IO.Strategies; using System.Threading; namespace Microsoft.Win32.SafeHandles { public sealed partial class SafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid { internal static bool DisableFileLocking { get; } = OperatingSystem.IsBrowser() // #40065: Emscripten does not support file locking || AppContextConfigHelper.GetBooleanConfig("System.IO.DisableFileLocking", "DOTNET_SYSTEM_IO_DISABLEFILELOCKING", defaultValue: false); // not using bool? as it's not thread safe private volatile NullableBool _canSeek = NullableBool.Undefined; private volatile NullableBool _supportsRandomAccess = NullableBool.Undefined; private bool _deleteOnClose; private bool _isLocked; public SafeFileHandle() : this(ownsHandle: true) { } private SafeFileHandle(bool ownsHandle) : base(ownsHandle) { SetHandle(new IntPtr(-1)); } public bool IsAsync { get; private set; } internal bool CanSeek => !IsClosed && GetCanSeek(); internal bool SupportsRandomAccess { get { NullableBool supportsRandomAccess = _supportsRandomAccess; if (supportsRandomAccess == NullableBool.Undefined) { _supportsRandomAccess = supportsRandomAccess = GetCanSeek() ? NullableBool.True : NullableBool.False; } return supportsRandomAccess == NullableBool.True; } set { Debug.Assert(value == false); // We should only use the setter to disable random access. _supportsRandomAccess = value ? NullableBool.True : NullableBool.False; } } internal ThreadPoolBoundHandle? ThreadPoolBinding => null; internal void EnsureThreadPoolBindingInitialized() { /* nop */ } internal bool TryGetCachedLength(out long cachedLength) { cachedLength = -1; return false; } private static SafeFileHandle Open(string path, Interop.Sys.OpenFlags flags, int mode, Func<Interop.ErrorInfo, Interop.Sys.OpenFlags, string, Exception?>? createOpenException) { Debug.Assert(path != null); SafeFileHandle handle = Interop.Sys.Open(path, flags, mode); handle._path = path; if (handle.IsInvalid) { Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); handle.Dispose(); if (createOpenException?.Invoke(error, flags, path) is Exception ex) { throw ex; } // If we fail to open the file due to a path not existing, we need to know whether to blame // the file itself or its directory. If we're creating the file, then we blame the directory, // otherwise we blame the file. // // When opening, we need to align with Windows, which considers a missing path to be // FileNotFound only if the containing directory exists. bool isDirectory = (error.Error == Interop.Error.ENOENT) && ((flags & Interop.Sys.OpenFlags.O_CREAT) != 0 || !DirectoryExists(System.IO.Path.GetDirectoryName(System.IO.Path.TrimEndingDirectorySeparator(path!))!)); Interop.CheckIo( error.Error, path, isDirectory, errorRewriter: e => (e.Error == Interop.Error.EISDIR) ? Interop.Error.EACCES.Info() : e); } return handle; } private static bool DirectoryExists(string fullPath) { Interop.Sys.FileStatus fileinfo; if (Interop.Sys.Stat(fullPath, out fileinfo) < 0) { return false; } return ((fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR); } // Each thread will have its own copy. This prevents race conditions if the handle had the last error. [ThreadStatic] internal static Interop.ErrorInfo? t_lastCloseErrorInfo; protected override bool ReleaseHandle() { // If DeleteOnClose was requested when constructed, delete the file now. // (Unix doesn't directly support DeleteOnClose, so we mimic it here.) // We delete the file before releasing the lock to detect the removal in Init. if (_deleteOnClose) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed, but the // name will be removed immediately. Debug.Assert(_path is not null); Interop.Sys.Unlink(_path); // ignore errors; it's valid that the path may no longer exist } // When the SafeFileHandle was opened, we likely issued an flock on the created descriptor in order to add // an advisory lock. This lock should be removed via closing the file descriptor, but close can be // interrupted, and we don't retry closes. As such, we could end up leaving the file locked, // which could prevent subsequent usage of the file until this process dies. To avoid that, we proactively // try to release the lock before we close the handle. if (_isLocked) { Interop.Sys.FLock(handle, Interop.Sys.LockOperations.LOCK_UN); // ignore any errors _isLocked = false; } // Close the descriptor. Although close is documented to potentially fail with EINTR, we never want // to retry, as the descriptor could actually have been closed, been subsequently reassigned, and // be in use elsewhere in the process. Instead, we simply check whether the call was successful. int result = Interop.Sys.Close(handle); if (result != 0) { t_lastCloseErrorInfo = Interop.Sys.GetLastErrorInfo(); } return result == 0; } public override bool IsInvalid { get { long h = (long)handle; return h < 0 || h > int.MaxValue; } } // If the file gets created a new, we'll select the permissions for it. Most Unix utilities by default use 666 (read and // write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out // a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the // actual permissions will typically be less than what we select here. private const Interop.Sys.Permissions DefaultOpenPermissions = Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH; // Specialized Open that returns the file length and permissions of the opened file. // This information is retrieved from the 'stat' syscall that must be performed to ensure the path is not a directory. internal static SafeFileHandle OpenReadOnly(string fullPath, FileOptions options, out long fileLength, out Interop.Sys.Permissions filePermissions) { SafeFileHandle handle = Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, options, preallocationSize: 0, DefaultOpenPermissions, out fileLength, out filePermissions, null); Debug.Assert(fileLength >= 0); return handle; } internal static SafeFileHandle Open(string fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize, Interop.Sys.Permissions openPermissions = DefaultOpenPermissions, Func<Interop.ErrorInfo, Interop.Sys.OpenFlags, string, Exception?>? createOpenException = null) { return Open(fullPath, mode, access, share, options, preallocationSize, openPermissions, out _, out _, createOpenException); } private static SafeFileHandle Open(string fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize, Interop.Sys.Permissions openPermissions, out long fileLength, out Interop.Sys.Permissions filePermissions, Func<Interop.ErrorInfo, Interop.Sys.OpenFlags, string, Exception?>? createOpenException = null) { // Translate the arguments into arguments for an open call. Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, access, share, options); SafeFileHandle? safeFileHandle = null; try { while (true) { safeFileHandle = Open(fullPath, openFlags, (int)openPermissions, createOpenException); // When Init return false, the path has changed to another file entry, and // we need to re-open the path to reflect that. if (safeFileHandle.Init(fullPath, mode, access, share, options, preallocationSize, out fileLength, out filePermissions)) { return safeFileHandle; } else { safeFileHandle.Dispose(); } } } catch (Exception) { safeFileHandle?.Dispose(); throw; } } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="share">The FileShare provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileShare share, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.Sys.OpenFlags flags = default; switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. break; case FileMode.Truncate: if (DisableFileLocking) { // if we don't lock the file, we can truncate it when opening // otherwise we truncate the file after getting the lock flags |= Interop.Sys.OpenFlags.O_TRUNC; } break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: flags |= Interop.Sys.OpenFlags.O_CREAT; break; case FileMode.Create: flags |= Interop.Sys.OpenFlags.O_CREAT; if (DisableFileLocking) { flags |= Interop.Sys.OpenFlags.O_TRUNC; } break; case FileMode.CreateNew: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL); break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.Sys.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.Sys.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.Sys.OpenFlags.O_WRONLY; break; } // Handle Inheritable, other FileShare flags are handled by Init if ((share & FileShare.Inheritable) == 0) { flags |= Interop.Sys.OpenFlags.O_CLOEXEC; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. // - Asynchronous: Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true // - DeleteOnClose: Doesn't have a Unix equivalent, but we approximate it in Dispose // - Encrypted: No equivalent on Unix and is ignored // - RandomAccess: Implemented after open if posix_fadvise is available // - SequentialScan: Implemented after open if posix_fadvise is available // - WriteThrough: Handled here if ((options & FileOptions.WriteThrough) != 0) { flags |= Interop.Sys.OpenFlags.O_SYNC; } return flags; } private bool Init(string path, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize, out long fileLength, out Interop.Sys.Permissions filePermissions) { Interop.Sys.FileStatus status = default; bool statusHasValue = false; fileLength = -1; filePermissions = 0; // Make sure our handle is not a directory. // We can omit the check when write access is requested. open will have failed with EISDIR. if ((access & FileAccess.Write) == 0) { // Stat the file descriptor to avoid race conditions. FStatCheckIO(path, ref status, ref statusHasValue); if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR) { throw Interop.GetExceptionForIoErrno(Interop.Error.EACCES.Info(), path, isDirectory: true); } if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFREG) { // we take advantage of the information provided by the fstat syscall // and for regular files (most common case) // avoid one extra sys call for determining whether file can be seeked _canSeek = NullableBool.True; Debug.Assert(Interop.Sys.LSeek(this, 0, Interop.Sys.SeekWhence.SEEK_CUR) >= 0); } fileLength = status.Size; filePermissions = (Interop.Sys.Permissions)(status.Mode & (int)Interop.Sys.Permissions.Mask); } IsAsync = (options & FileOptions.Asynchronous) != 0; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH; if (CanLockTheFile(lockOperation, access) && !(_isLocked = Interop.Sys.FLock(this, lockOperation | Interop.Sys.LockOperations.LOCK_NB) >= 0)) { // The only error we care about is EWOULDBLOCK, which indicates that the file is currently locked by someone // else and we would block trying to access it. Other errors, such as ENOTSUP (locking isn't supported) or // EACCES (the file system doesn't allow us to lock), will only hamper FileStream's usage without providing value, // given again that this is only advisory / best-effort. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EWOULDBLOCK) { throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory: false); } } // On Windows, DeleteOnClose happens when all kernel handles to the file are closed. // Unix kernels don't have this feature, and .NET deletes the file when the Handle gets disposed. // When the file is opened with an exclusive lock, we can use it to check the file at the path // still matches the file we've opened. // When the delete is performed by another .NET Handle, it holds the lock during the delete. // Since we've just obtained the lock, the file will already be removed/replaced. // We limit performing this check to cases where our file was opened with DeleteOnClose with // a mode of OpenOrCreate. if (_isLocked && ((options & FileOptions.DeleteOnClose) != 0) && share == FileShare.None && mode == FileMode.OpenOrCreate) { FStatCheckIO(path, ref status, ref statusHasValue); Interop.Sys.FileStatus pathStatus; if (Interop.Sys.Stat(path, out pathStatus) < 0) { // If the file was removed, re-open. // Otherwise throw the error 'stat' gave us (assuming this is the // error 'open' will give us if we'd call it now). Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); if (error.Error == Interop.Error.ENOENT) { return false; } throw Interop.GetExceptionForIoErrno(error, path); } if (pathStatus.Ino != status.Ino || pathStatus.Dev != status.Dev) { // The file was replaced, re-open return false; } } // Enable DeleteOnClose when we've succesfully locked the file. // On Windows, the locking happens atomically as part of opening the file. _deleteOnClose = (options & FileOptions.DeleteOnClose) != 0; // These provide hints around how the file will be accessed. Specifying both RandomAccess // and Sequential together doesn't make sense as they are two competing options on the same spectrum, // so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided). Interop.Sys.FileAdvice fadv = (options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM : (options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL : 0; if (fadv != 0) { FileStreamHelpers.CheckFileCall(Interop.Sys.PosixFAdvise(this, 0, 0, fadv), path, ignoreNotSupported: true); // just a hint. } if ((mode == FileMode.Create || mode == FileMode.Truncate) && !DisableFileLocking) { // Truncate the file now if the file mode requires it. This ensures that the file only will be truncated // if opened successfully. if (Interop.Sys.FTruncate(this, 0) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error != Interop.Error.EBADF && errorInfo.Error != Interop.Error.EINVAL) { // We know the file descriptor is valid and we know the size argument to FTruncate is correct, // so if EBADF or EINVAL is returned, it means we're dealing with a special file that can't be // truncated. Ignore the error in such cases; in all others, throw. throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory: false); } } } if (preallocationSize > 0 && Interop.Sys.FAllocate(this, 0, preallocationSize) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); // Only throw for errors that indicate there is not enough space. if (errorInfo.Error == Interop.Error.EFBIG || errorInfo.Error == Interop.Error.ENOSPC) { Dispose(); // Delete the file we've created. Debug.Assert(mode == FileMode.Create || mode == FileMode.CreateNew); Interop.Sys.Unlink(path!); throw new IOException(SR.Format(errorInfo.Error == Interop.Error.EFBIG ? SR.IO_FileTooLarge_Path_AllocationSize : SR.IO_DiskFull_Path_AllocationSize, path, preallocationSize)); } } return true; } private bool CanLockTheFile(Interop.Sys.LockOperations lockOperation, FileAccess access) { Debug.Assert(lockOperation == Interop.Sys.LockOperations.LOCK_EX || lockOperation == Interop.Sys.LockOperations.LOCK_SH); if (DisableFileLocking) { return false; } else if (lockOperation == Interop.Sys.LockOperations.LOCK_EX) { return true; // LOCK_EX is always OK } else if ((access & FileAccess.Write) == 0) { return true; // LOCK_SH is always OK when reading } if (!Interop.Sys.TryGetFileSystemType(this, out Interop.Sys.UnixFileSystemTypes unixFileSystemType)) { return false; // assume we should not acquire the lock if we don't know the File System } switch (unixFileSystemType) { case Interop.Sys.UnixFileSystemTypes.nfs: // #44546 case Interop.Sys.UnixFileSystemTypes.smb: case Interop.Sys.UnixFileSystemTypes.smb2: // #53182 case Interop.Sys.UnixFileSystemTypes.cifs: return false; // LOCK_SH is not OK when writing to NFS, CIFS or SMB default: return true; // in all other situations it should be OK } } private void FStatCheckIO(string path, ref Interop.Sys.FileStatus status, ref bool statusHasValue) { if (!statusHasValue) { if (Interop.Sys.FStat(this, out status) != 0) { Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); throw Interop.GetExceptionForIoErrno(error, path); } statusHasValue = true; } } private bool GetCanSeek() { Debug.Assert(!IsClosed); Debug.Assert(!IsInvalid); NullableBool canSeek = _canSeek; if (canSeek == NullableBool.Undefined) { _canSeek = canSeek = Interop.Sys.LSeek(this, 0, Interop.Sys.SeekWhence.SEEK_CUR) >= 0 ? NullableBool.True : NullableBool.False; } return canSeek == NullableBool.True; } internal long GetFileLength() { int result = Interop.Sys.FStat(this, out Interop.Sys.FileStatus status); FileStreamHelpers.CheckFileCall(result, Path); return status.Size; } private enum NullableBool { Undefined = 0, False = -1, True = 1 } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Regression/JitBlue/GitHub_6238/GitHub_6238.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This test tests our signed contained compare logic // We should generate a signed set for the high compare, and an unsigned // set for the low compare // using System; using System.Runtime.CompilerServices; class Program { uint i; [MethodImpl(MethodImplOptions.NoInlining)] static int Test(long a, long b) { if (a < b) { return 5; } else { return 0; } } static int Main() { const int Pass = 100; const int Fail = -1; if (Test(-2L, 0L) == 5) { Console.WriteLine("Passed"); return Pass; } else { Console.WriteLine("Failed"); return Fail; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This test tests our signed contained compare logic // We should generate a signed set for the high compare, and an unsigned // set for the low compare // using System; using System.Runtime.CompilerServices; class Program { uint i; [MethodImpl(MethodImplOptions.NoInlining)] static int Test(long a, long b) { if (a < b) { return 5; } else { return 0; } } static int Main() { const int Pass = 100; const int Fail = -1; if (Test(-2L, 0L) == 5) { Console.WriteLine("Passed"); return Pass; } else { Console.WriteLine("Failed"); return Fail; } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Runtime/tests/System/GenericMathHelpers.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.Runtime.Versioning; namespace System.Tests { [RequiresPreviewFeatures] public static class AdditionOperatorsHelper<TSelf, TOther, TResult> where TSelf : IAdditionOperators<TSelf, TOther, TResult> { public static TResult op_Addition(TSelf left, TOther right) => left + right; } [RequiresPreviewFeatures] public static class AdditiveIdentityHelper<TSelf, TResult> where TSelf : IAdditiveIdentity<TSelf, TResult> { public static TResult AdditiveIdentity => TSelf.AdditiveIdentity; } [RequiresPreviewFeatures] public static class BinaryIntegerHelper<TSelf> where TSelf : IBinaryInteger<TSelf> { public static TSelf LeadingZeroCount(TSelf value) => TSelf.LeadingZeroCount(value); public static TSelf PopCount(TSelf value) => TSelf.PopCount(value); public static TSelf RotateLeft(TSelf value, int rotateAmount) => TSelf.RotateLeft(value, rotateAmount); public static TSelf RotateRight(TSelf value, int rotateAmount) => TSelf.RotateRight(value, rotateAmount); public static TSelf TrailingZeroCount(TSelf value) => TSelf.TrailingZeroCount(value); } [RequiresPreviewFeatures] public static class BinaryNumberHelper<TSelf> where TSelf : IBinaryNumber<TSelf> { public static bool IsPow2(TSelf value) => TSelf.IsPow2(value); public static TSelf Log2(TSelf value) => TSelf.Log2(value); } [RequiresPreviewFeatures] public static class BitwiseOperatorsHelper<TSelf, TOther, TResult> where TSelf : IBitwiseOperators<TSelf, TOther, TResult> { public static TResult op_BitwiseAnd(TSelf left, TOther right) => left & right; public static TResult op_BitwiseOr(TSelf left, TOther right) => left | right; public static TResult op_ExclusiveOr(TSelf left, TOther right) => left ^ right; public static TResult op_OnesComplement(TSelf value) => ~value; } [RequiresPreviewFeatures] public static class ComparisonOperatorsHelper<TSelf, TOther> where TSelf : IComparisonOperators<TSelf, TOther> { public static bool op_GreaterThan(TSelf left, TOther right) => left > right; public static bool op_GreaterThanOrEqual(TSelf left, TOther right) => left >= right; public static bool op_LessThan(TSelf left, TOther right) => left < right; public static bool op_LessThanOrEqual(TSelf left, TOther right) => left <= right; } [RequiresPreviewFeatures] public static class DecrementOperatorsHelper<TSelf> where TSelf : IDecrementOperators<TSelf> { public static TSelf op_Decrement(TSelf value) => --value; } [RequiresPreviewFeatures] public static class DivisionOperatorsHelper<TSelf, TOther, TResult> where TSelf : IDivisionOperators<TSelf, TOther, TResult> { public static TResult op_Division(TSelf left, TOther right) => left / right; } [RequiresPreviewFeatures] public static class EqualityOperatorsHelper<TSelf, TOther> where TSelf : IEqualityOperators<TSelf, TOther> { public static bool op_Equality(TSelf left, TOther right) => left == right; public static bool op_Inequality(TSelf left, TOther right) => left != right; } [RequiresPreviewFeatures] public static class IncrementOperatorsHelper<TSelf> where TSelf : IIncrementOperators<TSelf> { public static TSelf op_Increment(TSelf value) => ++value; } [RequiresPreviewFeatures] public static class ModulusOperatorsHelper<TSelf, TOther, TResult> where TSelf : IModulusOperators<TSelf, TOther, TResult> { public static TResult op_Modulus(TSelf left, TOther right) => left % right; } [RequiresPreviewFeatures] public static class MultiplyOperatorsHelper<TSelf, TOther, TResult> where TSelf : IMultiplyOperators<TSelf, TOther, TResult> { public static TResult op_Multiply(TSelf left, TOther right) => left * right; } [RequiresPreviewFeatures] public static class MinMaxValueHelper<TSelf> where TSelf : IMinMaxValue<TSelf> { public static TSelf MaxValue => TSelf.MaxValue; public static TSelf MinValue => TSelf.MinValue; } [RequiresPreviewFeatures] public static class MultiplicativeIdentityHelper<TSelf, TResult> where TSelf : IMultiplicativeIdentity<TSelf, TResult> { public static TResult MultiplicativeIdentity => TSelf.MultiplicativeIdentity; } [RequiresPreviewFeatures] public static class NumberHelper<TSelf> where TSelf : INumber<TSelf> { public static TSelf One => TSelf.One; public static TSelf Zero => TSelf.Zero; public static TSelf Abs(TSelf value) => TSelf.Abs(value); public static TSelf Clamp(TSelf value, TSelf min, TSelf max) => TSelf.Clamp(value, min, max); public static TSelf Create<TOther>(TOther value) where TOther : INumber<TOther> => TSelf.Create<TOther>(value); public static TSelf CreateSaturating<TOther>(TOther value) where TOther : INumber<TOther> => TSelf.CreateSaturating<TOther>(value); public static TSelf CreateTruncating<TOther>(TOther value) where TOther : INumber<TOther> => TSelf.CreateTruncating<TOther>(value); public static (TSelf Quotient, TSelf Remainder) DivRem(TSelf left, TSelf right) => TSelf.DivRem(left, right); public static TSelf Max(TSelf x, TSelf y) => TSelf.Max(x, y); public static TSelf Min(TSelf x, TSelf y) => TSelf.Min(x, y); public static TSelf Parse(string s, IFormatProvider provider) => TSelf.Parse(s, provider); public static TSelf Parse(string s, NumberStyles style, IFormatProvider provider) => TSelf.Parse(s, style, provider); public static TSelf Parse(ReadOnlySpan<char> s, IFormatProvider provider) => TSelf.Parse(s, provider); public static TSelf Parse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider) => TSelf.Parse(s, style, provider); public static TSelf Sign(TSelf value) => TSelf.Sign(value); public static bool TryCreate<TOther>(TOther value, out TSelf result) where TOther : INumber<TOther> => TSelf.TryCreate<TOther>(value, out result); public static bool TryParse(string s, IFormatProvider provider, out TSelf result) => TSelf.TryParse(s, provider, out result); public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out TSelf result) => TSelf.TryParse(s, style, provider, out result); public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider provider, out TSelf result) => TSelf.TryParse(s, provider, out result); public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out TSelf result) => TSelf.TryParse(s, style, provider, out result); } [RequiresPreviewFeatures] public static class ParseableHelper<TSelf> where TSelf : IParseable<TSelf> { public static TSelf Parse(string s, IFormatProvider provider) => TSelf.Parse(s, provider); public static bool TryParse(string s, IFormatProvider provider, out TSelf result) => TSelf.TryParse(s, provider, out result); } [RequiresPreviewFeatures] public static class ShiftOperatorsHelper<TSelf, TResult> where TSelf : IShiftOperators<TSelf, TResult> { public static TResult op_LeftShift(TSelf value, int shiftAmount) => value << shiftAmount; public static TResult op_RightShift(TSelf value, int shiftAmount) => value >> shiftAmount; } [RequiresPreviewFeatures] public static class SignedNumberHelper<TSelf> where TSelf : ISignedNumber<TSelf> { public static TSelf NegativeOne => TSelf.NegativeOne; } [RequiresPreviewFeatures] public static class SpanParseableHelper<TSelf> where TSelf : ISpanParseable<TSelf> { public static TSelf Parse(ReadOnlySpan<char> s, IFormatProvider provider) => TSelf.Parse(s, provider); public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider provider, out TSelf result) => TSelf.TryParse(s, provider, out result); } [RequiresPreviewFeatures] public static class SubtractionOperatorsHelper<TSelf, TOther, TResult> where TSelf : ISubtractionOperators<TSelf, TOther, TResult> { public static TResult op_Subtraction(TSelf left, TOther right) => left - right; } [RequiresPreviewFeatures] public static class UnaryNegationOperatorsHelper<TSelf, TResult> where TSelf : IUnaryNegationOperators<TSelf, TResult> { public static TResult op_UnaryNegation(TSelf value) => -value; } [RequiresPreviewFeatures] public static class UnaryPlusOperatorsHelper<TSelf, TResult> where TSelf : IUnaryPlusOperators<TSelf, TResult> { public static TResult op_UnaryPlus(TSelf value) => +value; } }
// 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.Runtime.Versioning; namespace System.Tests { [RequiresPreviewFeatures] public static class AdditionOperatorsHelper<TSelf, TOther, TResult> where TSelf : IAdditionOperators<TSelf, TOther, TResult> { public static TResult op_Addition(TSelf left, TOther right) => left + right; } [RequiresPreviewFeatures] public static class AdditiveIdentityHelper<TSelf, TResult> where TSelf : IAdditiveIdentity<TSelf, TResult> { public static TResult AdditiveIdentity => TSelf.AdditiveIdentity; } [RequiresPreviewFeatures] public static class BinaryIntegerHelper<TSelf> where TSelf : IBinaryInteger<TSelf> { public static TSelf LeadingZeroCount(TSelf value) => TSelf.LeadingZeroCount(value); public static TSelf PopCount(TSelf value) => TSelf.PopCount(value); public static TSelf RotateLeft(TSelf value, int rotateAmount) => TSelf.RotateLeft(value, rotateAmount); public static TSelf RotateRight(TSelf value, int rotateAmount) => TSelf.RotateRight(value, rotateAmount); public static TSelf TrailingZeroCount(TSelf value) => TSelf.TrailingZeroCount(value); } [RequiresPreviewFeatures] public static class BinaryNumberHelper<TSelf> where TSelf : IBinaryNumber<TSelf> { public static bool IsPow2(TSelf value) => TSelf.IsPow2(value); public static TSelf Log2(TSelf value) => TSelf.Log2(value); } [RequiresPreviewFeatures] public static class BitwiseOperatorsHelper<TSelf, TOther, TResult> where TSelf : IBitwiseOperators<TSelf, TOther, TResult> { public static TResult op_BitwiseAnd(TSelf left, TOther right) => left & right; public static TResult op_BitwiseOr(TSelf left, TOther right) => left | right; public static TResult op_ExclusiveOr(TSelf left, TOther right) => left ^ right; public static TResult op_OnesComplement(TSelf value) => ~value; } [RequiresPreviewFeatures] public static class ComparisonOperatorsHelper<TSelf, TOther> where TSelf : IComparisonOperators<TSelf, TOther> { public static bool op_GreaterThan(TSelf left, TOther right) => left > right; public static bool op_GreaterThanOrEqual(TSelf left, TOther right) => left >= right; public static bool op_LessThan(TSelf left, TOther right) => left < right; public static bool op_LessThanOrEqual(TSelf left, TOther right) => left <= right; } [RequiresPreviewFeatures] public static class DecrementOperatorsHelper<TSelf> where TSelf : IDecrementOperators<TSelf> { public static TSelf op_Decrement(TSelf value) => --value; } [RequiresPreviewFeatures] public static class DivisionOperatorsHelper<TSelf, TOther, TResult> where TSelf : IDivisionOperators<TSelf, TOther, TResult> { public static TResult op_Division(TSelf left, TOther right) => left / right; } [RequiresPreviewFeatures] public static class EqualityOperatorsHelper<TSelf, TOther> where TSelf : IEqualityOperators<TSelf, TOther> { public static bool op_Equality(TSelf left, TOther right) => left == right; public static bool op_Inequality(TSelf left, TOther right) => left != right; } [RequiresPreviewFeatures] public static class IncrementOperatorsHelper<TSelf> where TSelf : IIncrementOperators<TSelf> { public static TSelf op_Increment(TSelf value) => ++value; } [RequiresPreviewFeatures] public static class ModulusOperatorsHelper<TSelf, TOther, TResult> where TSelf : IModulusOperators<TSelf, TOther, TResult> { public static TResult op_Modulus(TSelf left, TOther right) => left % right; } [RequiresPreviewFeatures] public static class MultiplyOperatorsHelper<TSelf, TOther, TResult> where TSelf : IMultiplyOperators<TSelf, TOther, TResult> { public static TResult op_Multiply(TSelf left, TOther right) => left * right; } [RequiresPreviewFeatures] public static class MinMaxValueHelper<TSelf> where TSelf : IMinMaxValue<TSelf> { public static TSelf MaxValue => TSelf.MaxValue; public static TSelf MinValue => TSelf.MinValue; } [RequiresPreviewFeatures] public static class MultiplicativeIdentityHelper<TSelf, TResult> where TSelf : IMultiplicativeIdentity<TSelf, TResult> { public static TResult MultiplicativeIdentity => TSelf.MultiplicativeIdentity; } [RequiresPreviewFeatures] public static class NumberHelper<TSelf> where TSelf : INumber<TSelf> { public static TSelf One => TSelf.One; public static TSelf Zero => TSelf.Zero; public static TSelf Abs(TSelf value) => TSelf.Abs(value); public static TSelf Clamp(TSelf value, TSelf min, TSelf max) => TSelf.Clamp(value, min, max); public static TSelf Create<TOther>(TOther value) where TOther : INumber<TOther> => TSelf.Create<TOther>(value); public static TSelf CreateSaturating<TOther>(TOther value) where TOther : INumber<TOther> => TSelf.CreateSaturating<TOther>(value); public static TSelf CreateTruncating<TOther>(TOther value) where TOther : INumber<TOther> => TSelf.CreateTruncating<TOther>(value); public static (TSelf Quotient, TSelf Remainder) DivRem(TSelf left, TSelf right) => TSelf.DivRem(left, right); public static TSelf Max(TSelf x, TSelf y) => TSelf.Max(x, y); public static TSelf Min(TSelf x, TSelf y) => TSelf.Min(x, y); public static TSelf Parse(string s, IFormatProvider provider) => TSelf.Parse(s, provider); public static TSelf Parse(string s, NumberStyles style, IFormatProvider provider) => TSelf.Parse(s, style, provider); public static TSelf Parse(ReadOnlySpan<char> s, IFormatProvider provider) => TSelf.Parse(s, provider); public static TSelf Parse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider) => TSelf.Parse(s, style, provider); public static TSelf Sign(TSelf value) => TSelf.Sign(value); public static bool TryCreate<TOther>(TOther value, out TSelf result) where TOther : INumber<TOther> => TSelf.TryCreate<TOther>(value, out result); public static bool TryParse(string s, IFormatProvider provider, out TSelf result) => TSelf.TryParse(s, provider, out result); public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out TSelf result) => TSelf.TryParse(s, style, provider, out result); public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider provider, out TSelf result) => TSelf.TryParse(s, provider, out result); public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out TSelf result) => TSelf.TryParse(s, style, provider, out result); } [RequiresPreviewFeatures] public static class ParseableHelper<TSelf> where TSelf : IParseable<TSelf> { public static TSelf Parse(string s, IFormatProvider provider) => TSelf.Parse(s, provider); public static bool TryParse(string s, IFormatProvider provider, out TSelf result) => TSelf.TryParse(s, provider, out result); } [RequiresPreviewFeatures] public static class ShiftOperatorsHelper<TSelf, TResult> where TSelf : IShiftOperators<TSelf, TResult> { public static TResult op_LeftShift(TSelf value, int shiftAmount) => value << shiftAmount; public static TResult op_RightShift(TSelf value, int shiftAmount) => value >> shiftAmount; } [RequiresPreviewFeatures] public static class SignedNumberHelper<TSelf> where TSelf : ISignedNumber<TSelf> { public static TSelf NegativeOne => TSelf.NegativeOne; } [RequiresPreviewFeatures] public static class SpanParseableHelper<TSelf> where TSelf : ISpanParseable<TSelf> { public static TSelf Parse(ReadOnlySpan<char> s, IFormatProvider provider) => TSelf.Parse(s, provider); public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider provider, out TSelf result) => TSelf.TryParse(s, provider, out result); } [RequiresPreviewFeatures] public static class SubtractionOperatorsHelper<TSelf, TOther, TResult> where TSelf : ISubtractionOperators<TSelf, TOther, TResult> { public static TResult op_Subtraction(TSelf left, TOther right) => left - right; } [RequiresPreviewFeatures] public static class UnaryNegationOperatorsHelper<TSelf, TResult> where TSelf : IUnaryNegationOperators<TSelf, TResult> { public static TResult op_UnaryNegation(TSelf value) => -value; } [RequiresPreviewFeatures] public static class UnaryPlusOperatorsHelper<TSelf, TResult> where TSelf : IUnaryPlusOperators<TSelf, TResult> { public static TResult op_UnaryPlus(TSelf value) => +value; } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.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.Immutable; using System.IO; using System.Reflection.Internal; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.PortableExecutable { /// <summary> /// An object used to read PE (Portable Executable) and COFF (Common Object File Format) headers from a stream. /// </summary> public sealed class PEHeaders { private readonly CoffHeader _coffHeader; private readonly PEHeader? _peHeader; private readonly ImmutableArray<SectionHeader> _sectionHeaders; private readonly CorHeader? _corHeader; private readonly bool _isLoadedImage; private readonly int _metadataStartOffset = -1; private readonly int _metadataSize; private readonly int _coffHeaderStartOffset = -1; private readonly int _corHeaderStartOffset = -1; private readonly int _peHeaderStartOffset = -1; internal const ushort DosSignature = 0x5A4D; // 'M' 'Z' internal const int PESignatureOffsetLocation = 0x3C; internal const uint PESignature = 0x00004550; // PE00 internal const int PESignatureSize = sizeof(uint); /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image starting at the stream's current position and ending at the end of the stream.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> public PEHeaders(Stream peStream) : this(peStream, 0) { } /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param> /// <param name="size">Size of the PE image.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception> public PEHeaders(Stream peStream, int size) : this(peStream, size, isLoadedImage: false) { } /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param> /// <param name="size">Size of the PE image.</param> /// <param name="isLoadedImage">True if the PE image has been loaded into memory by the OS loader.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception> public PEHeaders(Stream peStream!!, int size, bool isLoadedImage) { if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream)); } _isLoadedImage = isLoadedImage; int actualSize = StreamExtensions.GetAndValidateSize(peStream, size, nameof(peStream)); var reader = new PEBinaryReader(peStream, actualSize); bool isCoffOnly; SkipDosHeader(ref reader, out isCoffOnly); _coffHeaderStartOffset = reader.CurrentOffset; _coffHeader = new CoffHeader(ref reader); if (!isCoffOnly) { _peHeaderStartOffset = reader.CurrentOffset; _peHeader = new PEHeader(ref reader); } _sectionHeaders = this.ReadSectionHeaders(ref reader); if (!isCoffOnly) { int offset; if (TryCalculateCorHeaderOffset(actualSize, out offset)) { _corHeaderStartOffset = offset; reader.Seek(offset); _corHeader = new CorHeader(ref reader); } } CalculateMetadataLocation(actualSize, out _metadataStartOffset, out _metadataSize); } /// <summary> /// Gets the offset (in bytes) from the start of the PE image to the start of the CLI metadata. /// or -1 if the image does not contain metadata. /// </summary> public int MetadataStartOffset { get { return _metadataStartOffset; } } /// <summary> /// Gets the size of the CLI metadata 0 if the image does not contain metadata.) /// </summary> public int MetadataSize { get { return _metadataSize; } } /// <summary> /// Gets the COFF header of the image. /// </summary> public CoffHeader CoffHeader { get { return _coffHeader; } } /// <summary> /// Gets the byte offset from the start of the PE image to the start of the COFF header. /// </summary> public int CoffHeaderStartOffset { get { return _coffHeaderStartOffset; } } /// <summary> /// Determines if the image is Coff only. /// </summary> public bool IsCoffOnly { get { return _peHeader == null; } } /// <summary> /// Gets the PE header of the image or null if the image is COFF only. /// </summary> public PEHeader? PEHeader { get { return _peHeader; } } /// <summary> /// Gets the byte offset from the start of the image to /// </summary> public int PEHeaderStartOffset { get { return _peHeaderStartOffset; } } /// <summary> /// Gets the PE section headers. /// </summary> public ImmutableArray<SectionHeader> SectionHeaders { get { return _sectionHeaders; } } /// <summary> /// Gets the CLI header or null if the image does not have one. /// </summary> public CorHeader? CorHeader { get { return _corHeader; } } /// <summary> /// Gets the byte offset from the start of the image to the COR header or -1 if the image does not have one. /// </summary> public int CorHeaderStartOffset { get { return _corHeaderStartOffset; } } /// <summary> /// Determines if the image represents a Windows console application. /// </summary> public bool IsConsoleApplication { get { return _peHeader != null && _peHeader.Subsystem == Subsystem.WindowsCui; } } /// <summary> /// Determines if the image represents a dynamically linked library. /// </summary> public bool IsDll { get { return (_coffHeader.Characteristics & Characteristics.Dll) != 0; } } /// <summary> /// Determines if the image represents an executable. /// </summary> public bool IsExe { get { return (_coffHeader.Characteristics & Characteristics.Dll) == 0; } } private bool TryCalculateCorHeaderOffset(long peStreamSize, out int startOffset) { if (!TryGetDirectoryOffset(_peHeader!.CorHeaderTableDirectory, out startOffset, canCrossSectionBoundary: false)) { startOffset = -1; return false; } int length = _peHeader.CorHeaderTableDirectory.Size; if (length < COR20Constants.SizeOfCorHeader) { throw new BadImageFormatException(SR.InvalidCorHeaderSize); } return true; } private void SkipDosHeader(ref PEBinaryReader reader, out bool isCOFFOnly) { // Look for DOS Signature "MZ" ushort dosSig = reader.ReadUInt16(); if (dosSig != DosSignature) { // If image doesn't start with DOS signature, let's assume it is a // COFF (Common Object File Format), aka .OBJ file. // See CLiteWeightStgdbRW::FindObjMetaData in ndp\clr\src\MD\enc\peparse.cpp if (dosSig != 0 || reader.ReadUInt16() != 0xffff) { isCOFFOnly = true; reader.Seek(0); } else { // Might need to handle other formats. Anonymous or LTCG objects, for example. throw new BadImageFormatException(SR.UnknownFileFormat); } } else { isCOFFOnly = false; } if (!isCOFFOnly) { // Skip the DOS Header reader.Seek(PESignatureOffsetLocation); int ntHeaderOffset = reader.ReadInt32(); reader.Seek(ntHeaderOffset); // Look for PESignature "PE\0\0" uint ntSignature = reader.ReadUInt32(); if (ntSignature != PESignature) { throw new BadImageFormatException(SR.InvalidPESignature); } } } private ImmutableArray<SectionHeader> ReadSectionHeaders(ref PEBinaryReader reader) { int numberOfSections = _coffHeader.NumberOfSections; if (numberOfSections < 0) { throw new BadImageFormatException(SR.InvalidNumberOfSections); } var builder = ImmutableArray.CreateBuilder<SectionHeader>(numberOfSections); for (int i = 0; i < numberOfSections; i++) { builder.Add(new SectionHeader(ref reader)); } return builder.MoveToImmutable(); } /// <summary> /// Gets the offset (in bytes) from the start of the image to the given directory data. /// </summary> /// <param name="directory">PE directory entry</param> /// <param name="offset">Offset from the start of the image to the given directory data</param> /// <returns>True if the directory data is found, false otherwise.</returns> public bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset) { return TryGetDirectoryOffset(directory, out offset, canCrossSectionBoundary: true); } internal bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset, bool canCrossSectionBoundary) { int sectionIndex = GetContainingSectionIndex(directory.RelativeVirtualAddress); if (sectionIndex < 0) { offset = -1; return false; } int relativeOffset = directory.RelativeVirtualAddress - _sectionHeaders[sectionIndex].VirtualAddress; if (!canCrossSectionBoundary && directory.Size > _sectionHeaders[sectionIndex].VirtualSize - relativeOffset) { throw new BadImageFormatException(SR.SectionTooSmall); } offset = _isLoadedImage ? directory.RelativeVirtualAddress : _sectionHeaders[sectionIndex].PointerToRawData + relativeOffset; return true; } /// <summary> /// Searches sections of the PE image for the one that contains specified Relative Virtual Address. /// </summary> /// <param name="relativeVirtualAddress">Address.</param> /// <returns> /// Index of the section that contains <paramref name="relativeVirtualAddress"/>, /// or -1 if there is none. /// </returns> public int GetContainingSectionIndex(int relativeVirtualAddress) { for (int i = 0; i < _sectionHeaders.Length; i++) { if (_sectionHeaders[i].VirtualAddress <= relativeVirtualAddress && relativeVirtualAddress < _sectionHeaders[i].VirtualAddress + _sectionHeaders[i].VirtualSize) { return i; } } return -1; } internal int IndexOfSection(string name) { for (int i = 0; i < SectionHeaders.Length; i++) { if (SectionHeaders[i].Name.Equals(name, StringComparison.Ordinal)) { return i; } } return -1; } private void CalculateMetadataLocation(long peImageSize, out int start, out int size) { if (IsCoffOnly) { int cormeta = IndexOfSection(".cormeta"); if (cormeta == -1) { start = -1; size = 0; return; } if (_isLoadedImage) { start = SectionHeaders[cormeta].VirtualAddress; size = SectionHeaders[cormeta].VirtualSize; } else { start = SectionHeaders[cormeta].PointerToRawData; size = SectionHeaders[cormeta].SizeOfRawData; } } else if (_corHeader == null) { start = 0; size = 0; return; } else { if (!TryGetDirectoryOffset(_corHeader.MetadataDirectory, out start, canCrossSectionBoundary: false)) { throw new BadImageFormatException(SR.MissingDataDirectory); } size = _corHeader.MetadataDirectory.Size; } if (start < 0 || start >= peImageSize || size <= 0 || start > peImageSize - size) { throw new BadImageFormatException(SR.InvalidMetadataSectionSpan); } } } }
// 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.Immutable; using System.IO; using System.Reflection.Internal; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.PortableExecutable { /// <summary> /// An object used to read PE (Portable Executable) and COFF (Common Object File Format) headers from a stream. /// </summary> public sealed class PEHeaders { private readonly CoffHeader _coffHeader; private readonly PEHeader? _peHeader; private readonly ImmutableArray<SectionHeader> _sectionHeaders; private readonly CorHeader? _corHeader; private readonly bool _isLoadedImage; private readonly int _metadataStartOffset = -1; private readonly int _metadataSize; private readonly int _coffHeaderStartOffset = -1; private readonly int _corHeaderStartOffset = -1; private readonly int _peHeaderStartOffset = -1; internal const ushort DosSignature = 0x5A4D; // 'M' 'Z' internal const int PESignatureOffsetLocation = 0x3C; internal const uint PESignature = 0x00004550; // PE00 internal const int PESignatureSize = sizeof(uint); /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image starting at the stream's current position and ending at the end of the stream.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> public PEHeaders(Stream peStream) : this(peStream, 0) { } /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param> /// <param name="size">Size of the PE image.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception> public PEHeaders(Stream peStream, int size) : this(peStream, size, isLoadedImage: false) { } /// <summary> /// Reads PE headers from the current location in the stream. /// </summary> /// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param> /// <param name="size">Size of the PE image.</param> /// <param name="isLoadedImage">True if the PE image has been loaded into memory by the OS loader.</param> /// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception> /// <exception cref="IOException">Error reading from the stream.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception> public PEHeaders(Stream peStream!!, int size, bool isLoadedImage) { if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream)); } _isLoadedImage = isLoadedImage; int actualSize = StreamExtensions.GetAndValidateSize(peStream, size, nameof(peStream)); var reader = new PEBinaryReader(peStream, actualSize); bool isCoffOnly; SkipDosHeader(ref reader, out isCoffOnly); _coffHeaderStartOffset = reader.CurrentOffset; _coffHeader = new CoffHeader(ref reader); if (!isCoffOnly) { _peHeaderStartOffset = reader.CurrentOffset; _peHeader = new PEHeader(ref reader); } _sectionHeaders = this.ReadSectionHeaders(ref reader); if (!isCoffOnly) { int offset; if (TryCalculateCorHeaderOffset(actualSize, out offset)) { _corHeaderStartOffset = offset; reader.Seek(offset); _corHeader = new CorHeader(ref reader); } } CalculateMetadataLocation(actualSize, out _metadataStartOffset, out _metadataSize); } /// <summary> /// Gets the offset (in bytes) from the start of the PE image to the start of the CLI metadata. /// or -1 if the image does not contain metadata. /// </summary> public int MetadataStartOffset { get { return _metadataStartOffset; } } /// <summary> /// Gets the size of the CLI metadata 0 if the image does not contain metadata.) /// </summary> public int MetadataSize { get { return _metadataSize; } } /// <summary> /// Gets the COFF header of the image. /// </summary> public CoffHeader CoffHeader { get { return _coffHeader; } } /// <summary> /// Gets the byte offset from the start of the PE image to the start of the COFF header. /// </summary> public int CoffHeaderStartOffset { get { return _coffHeaderStartOffset; } } /// <summary> /// Determines if the image is Coff only. /// </summary> public bool IsCoffOnly { get { return _peHeader == null; } } /// <summary> /// Gets the PE header of the image or null if the image is COFF only. /// </summary> public PEHeader? PEHeader { get { return _peHeader; } } /// <summary> /// Gets the byte offset from the start of the image to /// </summary> public int PEHeaderStartOffset { get { return _peHeaderStartOffset; } } /// <summary> /// Gets the PE section headers. /// </summary> public ImmutableArray<SectionHeader> SectionHeaders { get { return _sectionHeaders; } } /// <summary> /// Gets the CLI header or null if the image does not have one. /// </summary> public CorHeader? CorHeader { get { return _corHeader; } } /// <summary> /// Gets the byte offset from the start of the image to the COR header or -1 if the image does not have one. /// </summary> public int CorHeaderStartOffset { get { return _corHeaderStartOffset; } } /// <summary> /// Determines if the image represents a Windows console application. /// </summary> public bool IsConsoleApplication { get { return _peHeader != null && _peHeader.Subsystem == Subsystem.WindowsCui; } } /// <summary> /// Determines if the image represents a dynamically linked library. /// </summary> public bool IsDll { get { return (_coffHeader.Characteristics & Characteristics.Dll) != 0; } } /// <summary> /// Determines if the image represents an executable. /// </summary> public bool IsExe { get { return (_coffHeader.Characteristics & Characteristics.Dll) == 0; } } private bool TryCalculateCorHeaderOffset(long peStreamSize, out int startOffset) { if (!TryGetDirectoryOffset(_peHeader!.CorHeaderTableDirectory, out startOffset, canCrossSectionBoundary: false)) { startOffset = -1; return false; } int length = _peHeader.CorHeaderTableDirectory.Size; if (length < COR20Constants.SizeOfCorHeader) { throw new BadImageFormatException(SR.InvalidCorHeaderSize); } return true; } private void SkipDosHeader(ref PEBinaryReader reader, out bool isCOFFOnly) { // Look for DOS Signature "MZ" ushort dosSig = reader.ReadUInt16(); if (dosSig != DosSignature) { // If image doesn't start with DOS signature, let's assume it is a // COFF (Common Object File Format), aka .OBJ file. // See CLiteWeightStgdbRW::FindObjMetaData in ndp\clr\src\MD\enc\peparse.cpp if (dosSig != 0 || reader.ReadUInt16() != 0xffff) { isCOFFOnly = true; reader.Seek(0); } else { // Might need to handle other formats. Anonymous or LTCG objects, for example. throw new BadImageFormatException(SR.UnknownFileFormat); } } else { isCOFFOnly = false; } if (!isCOFFOnly) { // Skip the DOS Header reader.Seek(PESignatureOffsetLocation); int ntHeaderOffset = reader.ReadInt32(); reader.Seek(ntHeaderOffset); // Look for PESignature "PE\0\0" uint ntSignature = reader.ReadUInt32(); if (ntSignature != PESignature) { throw new BadImageFormatException(SR.InvalidPESignature); } } } private ImmutableArray<SectionHeader> ReadSectionHeaders(ref PEBinaryReader reader) { int numberOfSections = _coffHeader.NumberOfSections; if (numberOfSections < 0) { throw new BadImageFormatException(SR.InvalidNumberOfSections); } var builder = ImmutableArray.CreateBuilder<SectionHeader>(numberOfSections); for (int i = 0; i < numberOfSections; i++) { builder.Add(new SectionHeader(ref reader)); } return builder.MoveToImmutable(); } /// <summary> /// Gets the offset (in bytes) from the start of the image to the given directory data. /// </summary> /// <param name="directory">PE directory entry</param> /// <param name="offset">Offset from the start of the image to the given directory data</param> /// <returns>True if the directory data is found, false otherwise.</returns> public bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset) { return TryGetDirectoryOffset(directory, out offset, canCrossSectionBoundary: true); } internal bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset, bool canCrossSectionBoundary) { int sectionIndex = GetContainingSectionIndex(directory.RelativeVirtualAddress); if (sectionIndex < 0) { offset = -1; return false; } int relativeOffset = directory.RelativeVirtualAddress - _sectionHeaders[sectionIndex].VirtualAddress; if (!canCrossSectionBoundary && directory.Size > _sectionHeaders[sectionIndex].VirtualSize - relativeOffset) { throw new BadImageFormatException(SR.SectionTooSmall); } offset = _isLoadedImage ? directory.RelativeVirtualAddress : _sectionHeaders[sectionIndex].PointerToRawData + relativeOffset; return true; } /// <summary> /// Searches sections of the PE image for the one that contains specified Relative Virtual Address. /// </summary> /// <param name="relativeVirtualAddress">Address.</param> /// <returns> /// Index of the section that contains <paramref name="relativeVirtualAddress"/>, /// or -1 if there is none. /// </returns> public int GetContainingSectionIndex(int relativeVirtualAddress) { for (int i = 0; i < _sectionHeaders.Length; i++) { if (_sectionHeaders[i].VirtualAddress <= relativeVirtualAddress && relativeVirtualAddress < _sectionHeaders[i].VirtualAddress + _sectionHeaders[i].VirtualSize) { return i; } } return -1; } internal int IndexOfSection(string name) { for (int i = 0; i < SectionHeaders.Length; i++) { if (SectionHeaders[i].Name.Equals(name, StringComparison.Ordinal)) { return i; } } return -1; } private void CalculateMetadataLocation(long peImageSize, out int start, out int size) { if (IsCoffOnly) { int cormeta = IndexOfSection(".cormeta"); if (cormeta == -1) { start = -1; size = 0; return; } if (_isLoadedImage) { start = SectionHeaders[cormeta].VirtualAddress; size = SectionHeaders[cormeta].VirtualSize; } else { start = SectionHeaders[cormeta].PointerToRawData; size = SectionHeaders[cormeta].SizeOfRawData; } } else if (_corHeader == null) { start = 0; size = 0; return; } else { if (!TryGetDirectoryOffset(_corHeader.MetadataDirectory, out start, canCrossSectionBoundary: false)) { throw new BadImageFormatException(SR.MissingDataDirectory); } size = _corHeader.MetadataDirectory.Size; } if (start < 0 || start >= peImageSize || size <= 0 || start > peImageSize - size) { throw new BadImageFormatException(SR.InvalidMetadataSectionSpan); } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/PolicyEnforcement.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.Authentication.ExtendedProtection { public enum PolicyEnforcement { Never, WhenSupported, Always } }
// 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.Authentication.ExtendedProtection { public enum PolicyEnforcement { Never, WhenSupported, Always } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/GC/Scenarios/GCSimulator/GCSimulator_365.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 1 -tp 0 -dz 17 -sdz 8517 -dc 10000 -sdc 5000 -lt 4 -f -dp 0.4 -dw 0.0</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 1 -tp 0 -dz 17 -sdz 8517 -dc 10000 -sdc 5000 -lt 4 -f -dp 0.4 -dw 0.0</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/TestClasses/ConstaintsTestExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Extensions.Logging.Generators.Tests.TestClasses { using ConstraintInAnotherNamespace; namespace UsesConstraintInAnotherNamespace { public partial class MessagePrinter<T> where T : Message { public void Print(ILogger logger, T message) { Log.Message(logger, message.Text); } internal static partial class Log { [LoggerMessage(EventId = 1, Level = LogLevel.Information, Message = "The message is {Text}.")] internal static partial void Message(ILogger logger, string? text); } } public partial class MessagePrinterHasConstraintOnLogClassAndLogMethod<T> where T : Message { public void Print(ILogger logger, T message) { Log<Message>.Message(logger, message); } internal static partial class Log<U> where U : Message { [LoggerMessage(EventId = 1, Level = LogLevel.Information, Message = "The message is {Text}.")] internal static partial void Message(ILogger logger, U text); } } } internal static partial class ConstraintsTestExtensions<T> where T : class { [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "M0{p0}")] public static partial void M0(ILogger logger, int p0); public static void Foo(T dummy) { } } internal static partial class ConstraintsTestExtensions1<T> where T : struct { [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "M0{p0}")] public static partial void M0(ILogger logger, int p0); public static void Foo(T dummy) { } } internal static partial class ConstraintsTestExtensions2<T> where T : unmanaged { [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "M0{p0}")] public static partial void M0(ILogger logger, int p0); public static void Foo(T dummy) { } } internal static partial class ConstraintsTestExtensions3<T> where T : new() { [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "M0{p0}")] public static partial void M0(ILogger logger, int p0); public static void Foo(T dummy) { } } internal static partial class ConstraintsTestExtensions4<T> where T : System.Attribute { [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "M0{p0}")] public static partial void M0(ILogger logger, int p0); public static void Foo(T dummy) { } } internal static partial class ConstraintsTestExtensions5<T> where T : notnull { [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "M0{p0}")] public static partial void M0(ILogger logger, int p0); public static void Foo(T dummy) { } } } namespace ConstraintInAnotherNamespace { public class Message { public string? Text { get; set; } public override string ToString() { return $"`{Text}`"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Extensions.Logging.Generators.Tests.TestClasses { using ConstraintInAnotherNamespace; namespace UsesConstraintInAnotherNamespace { public partial class MessagePrinter<T> where T : Message { public void Print(ILogger logger, T message) { Log.Message(logger, message.Text); } internal static partial class Log { [LoggerMessage(EventId = 1, Level = LogLevel.Information, Message = "The message is {Text}.")] internal static partial void Message(ILogger logger, string? text); } } public partial class MessagePrinterHasConstraintOnLogClassAndLogMethod<T> where T : Message { public void Print(ILogger logger, T message) { Log<Message>.Message(logger, message); } internal static partial class Log<U> where U : Message { [LoggerMessage(EventId = 1, Level = LogLevel.Information, Message = "The message is {Text}.")] internal static partial void Message(ILogger logger, U text); } } } internal static partial class ConstraintsTestExtensions<T> where T : class { [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "M0{p0}")] public static partial void M0(ILogger logger, int p0); public static void Foo(T dummy) { } } internal static partial class ConstraintsTestExtensions1<T> where T : struct { [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "M0{p0}")] public static partial void M0(ILogger logger, int p0); public static void Foo(T dummy) { } } internal static partial class ConstraintsTestExtensions2<T> where T : unmanaged { [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "M0{p0}")] public static partial void M0(ILogger logger, int p0); public static void Foo(T dummy) { } } internal static partial class ConstraintsTestExtensions3<T> where T : new() { [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "M0{p0}")] public static partial void M0(ILogger logger, int p0); public static void Foo(T dummy) { } } internal static partial class ConstraintsTestExtensions4<T> where T : System.Attribute { [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "M0{p0}")] public static partial void M0(ILogger logger, int p0); public static void Foo(T dummy) { } } internal static partial class ConstraintsTestExtensions5<T> where T : notnull { [LoggerMessage(EventId = 0, Level = LogLevel.Debug, Message = "M0{p0}")] public static partial void M0(ILogger logger, int p0); public static void Foo(T dummy) { } } } namespace ConstraintInAnotherNamespace { public class Message { public string? Text { get; set; } public override string ToString() { return $"`{Text}`"; } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslVisitor.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.Xml.Xsl.Xslt { internal abstract class XslVisitor<T> { protected virtual T Visit(XslNode node) => node.NodeType switch { XslNodeType.ApplyImports => VisitApplyImports((XslNode)node), XslNodeType.ApplyTemplates => VisitApplyTemplates((XslNode)node), XslNodeType.Attribute => VisitAttribute((NodeCtor)node), XslNodeType.AttributeSet => VisitAttributeSet((AttributeSet)node), XslNodeType.CallTemplate => VisitCallTemplate((XslNode)node), XslNodeType.Choose => VisitChoose((XslNode)node), XslNodeType.Comment => VisitComment((XslNode)node), XslNodeType.Copy => VisitCopy((XslNode)node), XslNodeType.CopyOf => VisitCopyOf((XslNode)node), XslNodeType.Element => VisitElement((NodeCtor)node), XslNodeType.Error => VisitError((XslNode)node), XslNodeType.ForEach => VisitForEach((XslNode)node), XslNodeType.If => VisitIf((XslNode)node), XslNodeType.Key => VisitKey((Key)node), XslNodeType.List => VisitList((XslNode)node), XslNodeType.LiteralAttribute => VisitLiteralAttribute((XslNode)node), XslNodeType.LiteralElement => VisitLiteralElement((XslNode)node), XslNodeType.Message => VisitMessage((XslNode)node), XslNodeType.Nop => VisitNop((XslNode)node), XslNodeType.Number => VisitNumber((Number)node), XslNodeType.Otherwise => VisitOtherwise((XslNode)node), XslNodeType.Param => VisitParam((VarPar)node), XslNodeType.PI => VisitPI((XslNode)node), XslNodeType.Sort => VisitSort((Sort)node), XslNodeType.Template => VisitTemplate((Template)node), XslNodeType.Text => VisitText((Text)node), XslNodeType.UseAttributeSet => VisitUseAttributeSet((XslNode)node), XslNodeType.ValueOf => VisitValueOf((XslNode)node), XslNodeType.ValueOfDoe => VisitValueOfDoe((XslNode)node), XslNodeType.Variable => VisitVariable((VarPar)node), XslNodeType.WithParam => VisitWithParam((VarPar)node), _ => VisitUnknown((XslNode)node), }; protected virtual T VisitApplyImports(XslNode node) { return VisitChildren(node); } protected virtual T VisitApplyTemplates(XslNode node) { return VisitChildren(node); } protected virtual T VisitAttribute(NodeCtor node) { return VisitChildren(node); } protected virtual T VisitAttributeSet(AttributeSet node) { return VisitChildren(node); } protected virtual T VisitCallTemplate(XslNode node) { return VisitChildren(node); } protected virtual T VisitChoose(XslNode node) { return VisitChildren(node); } protected virtual T VisitComment(XslNode node) { return VisitChildren(node); } protected virtual T VisitCopy(XslNode node) { return VisitChildren(node); } protected virtual T VisitCopyOf(XslNode node) { return VisitChildren(node); } protected virtual T VisitElement(NodeCtor node) { return VisitChildren(node); } protected virtual T VisitError(XslNode node) { return VisitChildren(node); } protected virtual T VisitForEach(XslNode node) { return VisitChildren(node); } protected virtual T VisitIf(XslNode node) { return VisitChildren(node); } protected virtual T VisitKey(Key node) { return VisitChildren(node); } protected virtual T VisitList(XslNode node) { return VisitChildren(node); } protected virtual T VisitLiteralAttribute(XslNode node) { return VisitChildren(node); } protected virtual T VisitLiteralElement(XslNode node) { return VisitChildren(node); } protected virtual T VisitMessage(XslNode node) { return VisitChildren(node); } protected virtual T VisitNop(XslNode node) { return VisitChildren(node); } protected virtual T VisitNumber(Number node) { return VisitChildren(node); } protected virtual T VisitOtherwise(XslNode node) { return VisitChildren(node); } protected virtual T VisitParam(VarPar node) { return VisitChildren(node); } protected virtual T VisitPI(XslNode node) { return VisitChildren(node); } protected virtual T VisitSort(Sort node) { return VisitChildren(node); } protected virtual T VisitTemplate(Template node) { return VisitChildren(node); } protected virtual T VisitText(Text node) { return VisitChildren(node); } protected virtual T VisitUseAttributeSet(XslNode node) { return VisitChildren(node); } protected virtual T VisitValueOf(XslNode node) { return VisitChildren(node); } protected virtual T VisitValueOfDoe(XslNode node) { return VisitChildren(node); } protected virtual T VisitVariable(VarPar node) { return VisitChildren(node); } protected virtual T VisitWithParam(VarPar node) { return VisitChildren(node); } protected virtual T VisitUnknown(XslNode node) { return VisitChildren(node); } protected virtual T VisitChildren(XslNode node) { foreach (XslNode child in node.Content) { this.Visit(child); } return default(T)!; } } }
// 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.Xml.Xsl.Xslt { internal abstract class XslVisitor<T> { protected virtual T Visit(XslNode node) => node.NodeType switch { XslNodeType.ApplyImports => VisitApplyImports((XslNode)node), XslNodeType.ApplyTemplates => VisitApplyTemplates((XslNode)node), XslNodeType.Attribute => VisitAttribute((NodeCtor)node), XslNodeType.AttributeSet => VisitAttributeSet((AttributeSet)node), XslNodeType.CallTemplate => VisitCallTemplate((XslNode)node), XslNodeType.Choose => VisitChoose((XslNode)node), XslNodeType.Comment => VisitComment((XslNode)node), XslNodeType.Copy => VisitCopy((XslNode)node), XslNodeType.CopyOf => VisitCopyOf((XslNode)node), XslNodeType.Element => VisitElement((NodeCtor)node), XslNodeType.Error => VisitError((XslNode)node), XslNodeType.ForEach => VisitForEach((XslNode)node), XslNodeType.If => VisitIf((XslNode)node), XslNodeType.Key => VisitKey((Key)node), XslNodeType.List => VisitList((XslNode)node), XslNodeType.LiteralAttribute => VisitLiteralAttribute((XslNode)node), XslNodeType.LiteralElement => VisitLiteralElement((XslNode)node), XslNodeType.Message => VisitMessage((XslNode)node), XslNodeType.Nop => VisitNop((XslNode)node), XslNodeType.Number => VisitNumber((Number)node), XslNodeType.Otherwise => VisitOtherwise((XslNode)node), XslNodeType.Param => VisitParam((VarPar)node), XslNodeType.PI => VisitPI((XslNode)node), XslNodeType.Sort => VisitSort((Sort)node), XslNodeType.Template => VisitTemplate((Template)node), XslNodeType.Text => VisitText((Text)node), XslNodeType.UseAttributeSet => VisitUseAttributeSet((XslNode)node), XslNodeType.ValueOf => VisitValueOf((XslNode)node), XslNodeType.ValueOfDoe => VisitValueOfDoe((XslNode)node), XslNodeType.Variable => VisitVariable((VarPar)node), XslNodeType.WithParam => VisitWithParam((VarPar)node), _ => VisitUnknown((XslNode)node), }; protected virtual T VisitApplyImports(XslNode node) { return VisitChildren(node); } protected virtual T VisitApplyTemplates(XslNode node) { return VisitChildren(node); } protected virtual T VisitAttribute(NodeCtor node) { return VisitChildren(node); } protected virtual T VisitAttributeSet(AttributeSet node) { return VisitChildren(node); } protected virtual T VisitCallTemplate(XslNode node) { return VisitChildren(node); } protected virtual T VisitChoose(XslNode node) { return VisitChildren(node); } protected virtual T VisitComment(XslNode node) { return VisitChildren(node); } protected virtual T VisitCopy(XslNode node) { return VisitChildren(node); } protected virtual T VisitCopyOf(XslNode node) { return VisitChildren(node); } protected virtual T VisitElement(NodeCtor node) { return VisitChildren(node); } protected virtual T VisitError(XslNode node) { return VisitChildren(node); } protected virtual T VisitForEach(XslNode node) { return VisitChildren(node); } protected virtual T VisitIf(XslNode node) { return VisitChildren(node); } protected virtual T VisitKey(Key node) { return VisitChildren(node); } protected virtual T VisitList(XslNode node) { return VisitChildren(node); } protected virtual T VisitLiteralAttribute(XslNode node) { return VisitChildren(node); } protected virtual T VisitLiteralElement(XslNode node) { return VisitChildren(node); } protected virtual T VisitMessage(XslNode node) { return VisitChildren(node); } protected virtual T VisitNop(XslNode node) { return VisitChildren(node); } protected virtual T VisitNumber(Number node) { return VisitChildren(node); } protected virtual T VisitOtherwise(XslNode node) { return VisitChildren(node); } protected virtual T VisitParam(VarPar node) { return VisitChildren(node); } protected virtual T VisitPI(XslNode node) { return VisitChildren(node); } protected virtual T VisitSort(Sort node) { return VisitChildren(node); } protected virtual T VisitTemplate(Template node) { return VisitChildren(node); } protected virtual T VisitText(Text node) { return VisitChildren(node); } protected virtual T VisitUseAttributeSet(XslNode node) { return VisitChildren(node); } protected virtual T VisitValueOf(XslNode node) { return VisitChildren(node); } protected virtual T VisitValueOfDoe(XslNode node) { return VisitChildren(node); } protected virtual T VisitVariable(VarPar node) { return VisitChildren(node); } protected virtual T VisitWithParam(VarPar node) { return VisitChildren(node); } protected virtual T VisitUnknown(XslNode node) { return VisitChildren(node); } protected virtual T VisitChildren(XslNode node) { foreach (XslNode child in node.Content) { this.Visit(child); } return default(T)!; } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MetricsEventSource.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.Diagnostics.Tracing; using System.Globalization; using System.Runtime.Versioning; using System.Text; namespace System.Diagnostics.Metrics { /// <summary> /// This EventSource is intended to let out-of-process tools (such as dotnet-counters) do /// ad-hoc monitoring for the new Instrument APIs. This source only supports one listener /// at a time. Each new listener will overwrite the configuration about which metrics /// are being collected and the time interval for the collection. In the future it would /// be nice to have support for multiple concurrent out-of-proc tools but EventSource's /// handling of filter arguments doesn't make that easy right now. /// /// Configuration - The EventSource accepts the following filter arguments: /// - SessionId - An arbitrary opaque string that will be sent back to the listener in /// many event payloads. If listener B reconfigures the EventSource while listener A /// is still running it is possible that each of them will observe some of the events /// that were generated using the other's requested configuration. Filtering on sessionId /// allows each listener to ignore those events. /// - RefreshInterval - The frequency in seconds for sending the metric time series data. /// The format is anything parsable using double.TryParse(). Any /// value less than AggregationManager.MinCollectionTimeSecs (currently 0.1 sec) is rounded /// up to the minimum. If not specified the default interval is 1 second. /// - Metrics - A semicolon separated list. Each item in the list is either the name of a /// Meter or 'meter_name\instrument_name'. For example "Foo;System.Runtime\gc-gen0-size" /// would include all instruments in the 'Foo' meter and the single 'gc-gen0-size' instrument /// in the 'System.Runtime' meter. /// - MaxTimeSeries - An integer that sets an upper bound on the number of time series /// this event source will track. Because instruments can have unbounded sets of tags /// even specifying a single metric could create unbounded load without this limit. /// - MaxHistograms - An integer that sets an upper bound on the number of histograms /// this event source will track. This allows setting a tighter bound on histograms /// than time series in general given that histograms use considerably more memory. /// </summary> [EventSource(Name = "System.Diagnostics.Metrics")] internal sealed class MetricsEventSource : EventSource { public static readonly MetricsEventSource Log = new(); public static class Keywords { /// <summary> /// Indicates diagnostics messages from MetricsEventSource should be included. /// </summary> public const EventKeywords Messages = (EventKeywords)0x1; /// <summary> /// Indicates that all the time series data points should be included /// </summary> public const EventKeywords TimeSeriesValues = (EventKeywords)0x2; /// <summary> /// Indicates that instrument published notifications should be included /// </summary> public const EventKeywords InstrumentPublishing = (EventKeywords)0x4; } private CommandHandler _handler; private MetricsEventSource() { _handler = new CommandHandler(); } /// <summary> /// Used to send ad-hoc diagnostics to humans. /// </summary> [Event(1, Keywords = Keywords.Messages)] public void Message(string? Message) { WriteEvent(1, Message); } [Event(2, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void CollectionStart(string sessionId, DateTime intervalStartTime, DateTime intervalEndTime) { WriteEvent(2, sessionId, intervalStartTime, intervalEndTime); } [Event(3, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void CollectionStop(string sessionId, DateTime intervalStartTime, DateTime intervalEndTime) { WriteEvent(3, sessionId, intervalStartTime, intervalEndTime); } [Event(4, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void CounterRateValuePublished(string sessionId, string meterName, string? meterVersion, string instrumentName, string? unit, string tags, string rate) { WriteEvent(4, sessionId, meterName, meterVersion ?? "", instrumentName, unit ?? "", tags, rate); } [Event(5, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void GaugeValuePublished(string sessionId, string meterName, string? meterVersion, string instrumentName, string? unit, string tags, string lastValue) { WriteEvent(5, sessionId, meterName, meterVersion ?? "", instrumentName, unit ?? "", tags, lastValue); } [Event(6, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void HistogramValuePublished(string sessionId, string meterName, string? meterVersion, string instrumentName, string? unit, string tags, string quantiles) { WriteEvent(6, sessionId, meterName, meterVersion ?? "", instrumentName, unit ?? "", tags, quantiles); } // Sent when we begin to monitor the value of a intrument, either because new session filter arguments changed subscriptions // or because an instrument matching the pre-existing filter has just been created. This event precedes all *MetricPublished events // for the same named instrument. [Event(7, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void BeginInstrumentReporting(string sessionId, string meterName, string? meterVersion, string instrumentName, string instrumentType, string? unit, string? description) { WriteEvent(7, sessionId, meterName, meterVersion ?? "", instrumentName, instrumentType, unit ?? "", description ?? ""); } // Sent when we stop monitoring the value of a intrument, either because new session filter arguments changed subscriptions // or because the Meter has been disposed. [Event(8, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void EndInstrumentReporting(string sessionId, string meterName, string? meterVersion, string instrumentName, string instrumentType, string? unit, string? description) { WriteEvent(8, sessionId, meterName, meterVersion ?? "", instrumentName, instrumentType, unit ?? "", description ?? ""); } [Event(9, Keywords = Keywords.TimeSeriesValues | Keywords.Messages | Keywords.InstrumentPublishing)] public void Error(string sessionId, string errorMessage) { WriteEvent(9, sessionId, errorMessage); } [Event(10, Keywords = Keywords.TimeSeriesValues | Keywords.InstrumentPublishing)] public void InitialInstrumentEnumerationComplete(string sessionId) { WriteEvent(10, sessionId); } [Event(11, Keywords = Keywords.InstrumentPublishing)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void InstrumentPublished(string sessionId, string meterName, string? meterVersion, string instrumentName, string instrumentType, string? unit, string? description) { WriteEvent(11, sessionId, meterName, meterVersion ?? "", instrumentName, instrumentType, unit ?? "", description ?? ""); } [Event(12, Keywords = Keywords.TimeSeriesValues)] public void TimeSeriesLimitReached(string sessionId) { WriteEvent(12, sessionId); } [Event(13, Keywords = Keywords.TimeSeriesValues)] public void HistogramLimitReached(string sessionId) { WriteEvent(13, sessionId); } [Event(14, Keywords = Keywords.TimeSeriesValues)] public void ObservableInstrumentCallbackError(string sessionId, string errorMessage) { WriteEvent(14, sessionId, errorMessage); } [Event(15, Keywords = Keywords.TimeSeriesValues | Keywords.Messages | Keywords.InstrumentPublishing)] public void MultipleSessionsNotSupportedError(string runningSessionId) { WriteEvent(15, runningSessionId); } /// <summary> /// Called when the EventSource gets a command from a EventListener or ETW. /// </summary> [NonEvent] protected override void OnEventCommand(EventCommandEventArgs command) { lock (this) { _handler.OnEventCommand(command); } } // EventSource assumes that every method defined on it represents an event. // Methods that are declared explicitly can use the [NonEvent] attribute to opt-out but // lambdas can't. Putting all the command handling logic in this nested class // is a simpler way to opt everything out in bulk. private sealed class CommandHandler { private AggregationManager? _aggregationManager; private string _sessionId = ""; public void OnEventCommand(EventCommandEventArgs command) { try { #if OS_ISBROWSER_SUPPORT if (OperatingSystem.IsBrowser()) { // AggregationManager uses a dedicated thread to avoid losing data for apps experiencing threadpool starvation // and browser doesn't support Thread.Start() // // This limitation shouldn't really matter because browser also doesn't support out-of-proc EventSource communication // which is the intended scenario for this EventSource. If it matters in the future AggregationManager can be // modified to have some other fallback path that works for browser. Log.Error("", "System.Diagnostics.Metrics EventSource not supported on browser"); return; } #endif if (command.Command == EventCommand.Update || command.Command == EventCommand.Disable || command.Command == EventCommand.Enable) { if (_aggregationManager != null) { if (command.Command == EventCommand.Enable || command.Command == EventCommand.Update) { // trying to add more sessions is not supported // EventSource doesn't provide an API that allows us to enumerate the listeners' // filter arguments independently or to easily track them ourselves. For example // removing a listener still shows up as EventCommand.Enable as long as at least // one other listener is active. In the future we might be able to figure out how // to infer the changes from the info we do have or add a better API but for now // I am taking the simple route and not supporting it. Log.MultipleSessionsNotSupportedError(_sessionId); return; } _aggregationManager.Dispose(); _aggregationManager = null; Log.Message($"Previous session with id {_sessionId} is stopped"); } _sessionId = ""; } if ((command.Command == EventCommand.Update || command.Command == EventCommand.Enable) && command.Arguments != null) { if (command.Arguments!.TryGetValue("SessionId", out string? id)) { _sessionId = id!; Log.Message($"SessionId argument received: {_sessionId}"); } else { _sessionId = System.Guid.NewGuid().ToString(); Log.Message($"New session started. SessionId auto-generated: {_sessionId}"); } double defaultIntervalSecs = 1; Debug.Assert(AggregationManager.MinCollectionTimeSecs <= defaultIntervalSecs); double refreshIntervalSecs = defaultIntervalSecs; if (command.Arguments!.TryGetValue("RefreshInterval", out string? refreshInterval)) { Log.Message($"RefreshInterval argument received: {refreshInterval}"); if (!double.TryParse(refreshInterval, out refreshIntervalSecs)) { Log.Message($"Failed to parse RefreshInterval. Using default {defaultIntervalSecs}s."); refreshIntervalSecs = defaultIntervalSecs; } else if (refreshIntervalSecs < AggregationManager.MinCollectionTimeSecs) { Log.Message($"RefreshInterval too small. Using minimum interval {AggregationManager.MinCollectionTimeSecs} seconds."); refreshIntervalSecs = AggregationManager.MinCollectionTimeSecs; } } else { Log.Message($"No RefreshInterval argument received. Using default {defaultIntervalSecs}s."); refreshIntervalSecs = defaultIntervalSecs; } int defaultMaxTimeSeries = 1000; int maxTimeSeries; if (command.Arguments!.TryGetValue("MaxTimeSeries", out string? maxTimeSeriesString)) { Log.Message($"MaxTimeSeries argument received: {maxTimeSeriesString}"); if (!int.TryParse(maxTimeSeriesString, out maxTimeSeries)) { Log.Message($"Failed to parse MaxTimeSeries. Using default {defaultMaxTimeSeries}"); maxTimeSeries = defaultMaxTimeSeries; } } else { Log.Message($"No MaxTimeSeries argument received. Using default {defaultMaxTimeSeries}"); maxTimeSeries = defaultMaxTimeSeries; } int defaultMaxHistograms = 20; int maxHistograms; if (command.Arguments!.TryGetValue("MaxHistograms", out string? maxHistogramsString)) { Log.Message($"MaxHistograms argument received: {maxHistogramsString}"); if (!int.TryParse(maxHistogramsString, out maxHistograms)) { Log.Message($"Failed to parse MaxHistograms. Using default {defaultMaxHistograms}"); maxHistograms = defaultMaxHistograms; } } else { Log.Message($"No MaxHistogram argument received. Using default {defaultMaxHistograms}"); maxHistograms = defaultMaxHistograms; } string sessionId = _sessionId; _aggregationManager = new AggregationManager( maxTimeSeries, maxHistograms, (i, s) => TransmitMetricValue(i, s, sessionId), (startIntervalTime, endIntervalTime) => Log.CollectionStart(sessionId, startIntervalTime, endIntervalTime), (startIntervalTime, endIntervalTime) => Log.CollectionStop(sessionId, startIntervalTime, endIntervalTime), i => Log.BeginInstrumentReporting(sessionId, i.Meter.Name, i.Meter.Version, i.Name, i.GetType().Name, i.Unit, i.Description), i => Log.EndInstrumentReporting(sessionId, i.Meter.Name, i.Meter.Version, i.Name, i.GetType().Name, i.Unit, i.Description), i => Log.InstrumentPublished(sessionId, i.Meter.Name, i.Meter.Version, i.Name, i.GetType().Name, i.Unit, i.Description), () => Log.InitialInstrumentEnumerationComplete(sessionId), e => Log.Error(sessionId, e.ToString()), () => Log.TimeSeriesLimitReached(sessionId), () => Log.HistogramLimitReached(sessionId), e => Log.ObservableInstrumentCallbackError(sessionId, e.ToString())); _aggregationManager.SetCollectionPeriod(TimeSpan.FromSeconds(refreshIntervalSecs)); if (command.Arguments!.TryGetValue("Metrics", out string? metricsSpecs)) { Log.Message($"Metrics argument received: {metricsSpecs}"); ParseSpecs(metricsSpecs); } else { Log.Message("No Metrics argument received"); } _aggregationManager.Start(); } } catch (Exception e) when (LogError(e)) { // this will never run } } private bool LogError(Exception e) { Log.Error(_sessionId, e.ToString()); // this code runs as an exception filter // returning false ensures the catch handler isn't run return false; } private static readonly char[] s_instrumentSeperators = new char[] { '\r', '\n', ',', ';' }; [UnsupportedOSPlatform("browser")] private void ParseSpecs(string? metricsSpecs) { if (metricsSpecs == null) { return; } string[] specStrings = metricsSpecs.Split(s_instrumentSeperators, StringSplitOptions.RemoveEmptyEntries); foreach (string specString in specStrings) { if (!MetricSpec.TryParse(specString, out MetricSpec spec)) { Log.Message($"Failed to parse metric spec: {specString}"); } else { Log.Message($"Parsed metric: {spec}"); if (spec.InstrumentName != null) { _aggregationManager!.Include(spec.MeterName, spec.InstrumentName); } else { _aggregationManager!.Include(spec.MeterName); } } } } private void TransmitMetricValue(Instrument instrument, LabeledAggregationStatistics stats, string sessionId) { if (stats.AggregationStatistics is RateStatistics rateStats) { Log.CounterRateValuePublished(sessionId, instrument.Meter.Name, instrument.Meter.Version, instrument.Name, instrument.Unit, FormatTags(stats.Labels), rateStats.Delta.HasValue ? rateStats.Delta.Value.ToString(CultureInfo.InvariantCulture) : ""); } else if (stats.AggregationStatistics is LastValueStatistics lastValueStats) { Log.GaugeValuePublished(sessionId, instrument.Meter.Name, instrument.Meter.Version, instrument.Name, instrument.Unit, FormatTags(stats.Labels), lastValueStats.LastValue.HasValue ? lastValueStats.LastValue.Value.ToString(CultureInfo.InvariantCulture) : ""); } else if (stats.AggregationStatistics is HistogramStatistics histogramStats) { Log.HistogramValuePublished(sessionId, instrument.Meter.Name, instrument.Meter.Version, instrument.Name, instrument.Unit, FormatTags(stats.Labels), FormatQuantiles(histogramStats.Quantiles)); } } private string FormatTags(KeyValuePair<string, string>[] labels) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < labels.Length; i++) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}", labels[i].Key, labels[i].Value); if (i != labels.Length - 1) { sb.Append(','); } } return sb.ToString(); } private string FormatQuantiles(QuantileValue[] quantiles) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < quantiles.Length; i++) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}", quantiles[i].Quantile, quantiles[i].Value); if (i != quantiles.Length - 1) { sb.Append(';'); } } return sb.ToString(); } } private sealed class MetricSpec { private const char MeterInstrumentSeparator = '\\'; public string MeterName { get; private set; } public string? InstrumentName { get; private set; } public MetricSpec(string meterName, string? instrumentName) { MeterName = meterName; InstrumentName = instrumentName; } public static bool TryParse(string text, out MetricSpec spec) { int slashIdx = text.IndexOf(MeterInstrumentSeparator); if (slashIdx == -1) { spec = new MetricSpec(text.Trim(), null); return true; } else { string meterName = text.Substring(0, slashIdx).Trim(); string? instrumentName = text.Substring(slashIdx + 1).Trim(); spec = new MetricSpec(meterName, instrumentName); return true; } } public override string ToString() => InstrumentName != null ? MeterName + MeterInstrumentSeparator + InstrumentName : MeterName; } } }
// 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.Diagnostics.Tracing; using System.Globalization; using System.Runtime.Versioning; using System.Text; namespace System.Diagnostics.Metrics { /// <summary> /// This EventSource is intended to let out-of-process tools (such as dotnet-counters) do /// ad-hoc monitoring for the new Instrument APIs. This source only supports one listener /// at a time. Each new listener will overwrite the configuration about which metrics /// are being collected and the time interval for the collection. In the future it would /// be nice to have support for multiple concurrent out-of-proc tools but EventSource's /// handling of filter arguments doesn't make that easy right now. /// /// Configuration - The EventSource accepts the following filter arguments: /// - SessionId - An arbitrary opaque string that will be sent back to the listener in /// many event payloads. If listener B reconfigures the EventSource while listener A /// is still running it is possible that each of them will observe some of the events /// that were generated using the other's requested configuration. Filtering on sessionId /// allows each listener to ignore those events. /// - RefreshInterval - The frequency in seconds for sending the metric time series data. /// The format is anything parsable using double.TryParse(). Any /// value less than AggregationManager.MinCollectionTimeSecs (currently 0.1 sec) is rounded /// up to the minimum. If not specified the default interval is 1 second. /// - Metrics - A semicolon separated list. Each item in the list is either the name of a /// Meter or 'meter_name\instrument_name'. For example "Foo;System.Runtime\gc-gen0-size" /// would include all instruments in the 'Foo' meter and the single 'gc-gen0-size' instrument /// in the 'System.Runtime' meter. /// - MaxTimeSeries - An integer that sets an upper bound on the number of time series /// this event source will track. Because instruments can have unbounded sets of tags /// even specifying a single metric could create unbounded load without this limit. /// - MaxHistograms - An integer that sets an upper bound on the number of histograms /// this event source will track. This allows setting a tighter bound on histograms /// than time series in general given that histograms use considerably more memory. /// </summary> [EventSource(Name = "System.Diagnostics.Metrics")] internal sealed class MetricsEventSource : EventSource { public static readonly MetricsEventSource Log = new(); public static class Keywords { /// <summary> /// Indicates diagnostics messages from MetricsEventSource should be included. /// </summary> public const EventKeywords Messages = (EventKeywords)0x1; /// <summary> /// Indicates that all the time series data points should be included /// </summary> public const EventKeywords TimeSeriesValues = (EventKeywords)0x2; /// <summary> /// Indicates that instrument published notifications should be included /// </summary> public const EventKeywords InstrumentPublishing = (EventKeywords)0x4; } private CommandHandler _handler; private MetricsEventSource() { _handler = new CommandHandler(); } /// <summary> /// Used to send ad-hoc diagnostics to humans. /// </summary> [Event(1, Keywords = Keywords.Messages)] public void Message(string? Message) { WriteEvent(1, Message); } [Event(2, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void CollectionStart(string sessionId, DateTime intervalStartTime, DateTime intervalEndTime) { WriteEvent(2, sessionId, intervalStartTime, intervalEndTime); } [Event(3, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void CollectionStop(string sessionId, DateTime intervalStartTime, DateTime intervalEndTime) { WriteEvent(3, sessionId, intervalStartTime, intervalEndTime); } [Event(4, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void CounterRateValuePublished(string sessionId, string meterName, string? meterVersion, string instrumentName, string? unit, string tags, string rate) { WriteEvent(4, sessionId, meterName, meterVersion ?? "", instrumentName, unit ?? "", tags, rate); } [Event(5, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void GaugeValuePublished(string sessionId, string meterName, string? meterVersion, string instrumentName, string? unit, string tags, string lastValue) { WriteEvent(5, sessionId, meterName, meterVersion ?? "", instrumentName, unit ?? "", tags, lastValue); } [Event(6, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void HistogramValuePublished(string sessionId, string meterName, string? meterVersion, string instrumentName, string? unit, string tags, string quantiles) { WriteEvent(6, sessionId, meterName, meterVersion ?? "", instrumentName, unit ?? "", tags, quantiles); } // Sent when we begin to monitor the value of a intrument, either because new session filter arguments changed subscriptions // or because an instrument matching the pre-existing filter has just been created. This event precedes all *MetricPublished events // for the same named instrument. [Event(7, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void BeginInstrumentReporting(string sessionId, string meterName, string? meterVersion, string instrumentName, string instrumentType, string? unit, string? description) { WriteEvent(7, sessionId, meterName, meterVersion ?? "", instrumentName, instrumentType, unit ?? "", description ?? ""); } // Sent when we stop monitoring the value of a intrument, either because new session filter arguments changed subscriptions // or because the Meter has been disposed. [Event(8, Keywords = Keywords.TimeSeriesValues)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void EndInstrumentReporting(string sessionId, string meterName, string? meterVersion, string instrumentName, string instrumentType, string? unit, string? description) { WriteEvent(8, sessionId, meterName, meterVersion ?? "", instrumentName, instrumentType, unit ?? "", description ?? ""); } [Event(9, Keywords = Keywords.TimeSeriesValues | Keywords.Messages | Keywords.InstrumentPublishing)] public void Error(string sessionId, string errorMessage) { WriteEvent(9, sessionId, errorMessage); } [Event(10, Keywords = Keywords.TimeSeriesValues | Keywords.InstrumentPublishing)] public void InitialInstrumentEnumerationComplete(string sessionId) { WriteEvent(10, sessionId); } [Event(11, Keywords = Keywords.InstrumentPublishing)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This calls WriteEvent with all primitive arguments which is safe. Primitives are always serialized properly.")] public void InstrumentPublished(string sessionId, string meterName, string? meterVersion, string instrumentName, string instrumentType, string? unit, string? description) { WriteEvent(11, sessionId, meterName, meterVersion ?? "", instrumentName, instrumentType, unit ?? "", description ?? ""); } [Event(12, Keywords = Keywords.TimeSeriesValues)] public void TimeSeriesLimitReached(string sessionId) { WriteEvent(12, sessionId); } [Event(13, Keywords = Keywords.TimeSeriesValues)] public void HistogramLimitReached(string sessionId) { WriteEvent(13, sessionId); } [Event(14, Keywords = Keywords.TimeSeriesValues)] public void ObservableInstrumentCallbackError(string sessionId, string errorMessage) { WriteEvent(14, sessionId, errorMessage); } [Event(15, Keywords = Keywords.TimeSeriesValues | Keywords.Messages | Keywords.InstrumentPublishing)] public void MultipleSessionsNotSupportedError(string runningSessionId) { WriteEvent(15, runningSessionId); } /// <summary> /// Called when the EventSource gets a command from a EventListener or ETW. /// </summary> [NonEvent] protected override void OnEventCommand(EventCommandEventArgs command) { lock (this) { _handler.OnEventCommand(command); } } // EventSource assumes that every method defined on it represents an event. // Methods that are declared explicitly can use the [NonEvent] attribute to opt-out but // lambdas can't. Putting all the command handling logic in this nested class // is a simpler way to opt everything out in bulk. private sealed class CommandHandler { private AggregationManager? _aggregationManager; private string _sessionId = ""; public void OnEventCommand(EventCommandEventArgs command) { try { #if OS_ISBROWSER_SUPPORT if (OperatingSystem.IsBrowser()) { // AggregationManager uses a dedicated thread to avoid losing data for apps experiencing threadpool starvation // and browser doesn't support Thread.Start() // // This limitation shouldn't really matter because browser also doesn't support out-of-proc EventSource communication // which is the intended scenario for this EventSource. If it matters in the future AggregationManager can be // modified to have some other fallback path that works for browser. Log.Error("", "System.Diagnostics.Metrics EventSource not supported on browser"); return; } #endif if (command.Command == EventCommand.Update || command.Command == EventCommand.Disable || command.Command == EventCommand.Enable) { if (_aggregationManager != null) { if (command.Command == EventCommand.Enable || command.Command == EventCommand.Update) { // trying to add more sessions is not supported // EventSource doesn't provide an API that allows us to enumerate the listeners' // filter arguments independently or to easily track them ourselves. For example // removing a listener still shows up as EventCommand.Enable as long as at least // one other listener is active. In the future we might be able to figure out how // to infer the changes from the info we do have or add a better API but for now // I am taking the simple route and not supporting it. Log.MultipleSessionsNotSupportedError(_sessionId); return; } _aggregationManager.Dispose(); _aggregationManager = null; Log.Message($"Previous session with id {_sessionId} is stopped"); } _sessionId = ""; } if ((command.Command == EventCommand.Update || command.Command == EventCommand.Enable) && command.Arguments != null) { if (command.Arguments!.TryGetValue("SessionId", out string? id)) { _sessionId = id!; Log.Message($"SessionId argument received: {_sessionId}"); } else { _sessionId = System.Guid.NewGuid().ToString(); Log.Message($"New session started. SessionId auto-generated: {_sessionId}"); } double defaultIntervalSecs = 1; Debug.Assert(AggregationManager.MinCollectionTimeSecs <= defaultIntervalSecs); double refreshIntervalSecs = defaultIntervalSecs; if (command.Arguments!.TryGetValue("RefreshInterval", out string? refreshInterval)) { Log.Message($"RefreshInterval argument received: {refreshInterval}"); if (!double.TryParse(refreshInterval, out refreshIntervalSecs)) { Log.Message($"Failed to parse RefreshInterval. Using default {defaultIntervalSecs}s."); refreshIntervalSecs = defaultIntervalSecs; } else if (refreshIntervalSecs < AggregationManager.MinCollectionTimeSecs) { Log.Message($"RefreshInterval too small. Using minimum interval {AggregationManager.MinCollectionTimeSecs} seconds."); refreshIntervalSecs = AggregationManager.MinCollectionTimeSecs; } } else { Log.Message($"No RefreshInterval argument received. Using default {defaultIntervalSecs}s."); refreshIntervalSecs = defaultIntervalSecs; } int defaultMaxTimeSeries = 1000; int maxTimeSeries; if (command.Arguments!.TryGetValue("MaxTimeSeries", out string? maxTimeSeriesString)) { Log.Message($"MaxTimeSeries argument received: {maxTimeSeriesString}"); if (!int.TryParse(maxTimeSeriesString, out maxTimeSeries)) { Log.Message($"Failed to parse MaxTimeSeries. Using default {defaultMaxTimeSeries}"); maxTimeSeries = defaultMaxTimeSeries; } } else { Log.Message($"No MaxTimeSeries argument received. Using default {defaultMaxTimeSeries}"); maxTimeSeries = defaultMaxTimeSeries; } int defaultMaxHistograms = 20; int maxHistograms; if (command.Arguments!.TryGetValue("MaxHistograms", out string? maxHistogramsString)) { Log.Message($"MaxHistograms argument received: {maxHistogramsString}"); if (!int.TryParse(maxHistogramsString, out maxHistograms)) { Log.Message($"Failed to parse MaxHistograms. Using default {defaultMaxHistograms}"); maxHistograms = defaultMaxHistograms; } } else { Log.Message($"No MaxHistogram argument received. Using default {defaultMaxHistograms}"); maxHistograms = defaultMaxHistograms; } string sessionId = _sessionId; _aggregationManager = new AggregationManager( maxTimeSeries, maxHistograms, (i, s) => TransmitMetricValue(i, s, sessionId), (startIntervalTime, endIntervalTime) => Log.CollectionStart(sessionId, startIntervalTime, endIntervalTime), (startIntervalTime, endIntervalTime) => Log.CollectionStop(sessionId, startIntervalTime, endIntervalTime), i => Log.BeginInstrumentReporting(sessionId, i.Meter.Name, i.Meter.Version, i.Name, i.GetType().Name, i.Unit, i.Description), i => Log.EndInstrumentReporting(sessionId, i.Meter.Name, i.Meter.Version, i.Name, i.GetType().Name, i.Unit, i.Description), i => Log.InstrumentPublished(sessionId, i.Meter.Name, i.Meter.Version, i.Name, i.GetType().Name, i.Unit, i.Description), () => Log.InitialInstrumentEnumerationComplete(sessionId), e => Log.Error(sessionId, e.ToString()), () => Log.TimeSeriesLimitReached(sessionId), () => Log.HistogramLimitReached(sessionId), e => Log.ObservableInstrumentCallbackError(sessionId, e.ToString())); _aggregationManager.SetCollectionPeriod(TimeSpan.FromSeconds(refreshIntervalSecs)); if (command.Arguments!.TryGetValue("Metrics", out string? metricsSpecs)) { Log.Message($"Metrics argument received: {metricsSpecs}"); ParseSpecs(metricsSpecs); } else { Log.Message("No Metrics argument received"); } _aggregationManager.Start(); } } catch (Exception e) when (LogError(e)) { // this will never run } } private bool LogError(Exception e) { Log.Error(_sessionId, e.ToString()); // this code runs as an exception filter // returning false ensures the catch handler isn't run return false; } private static readonly char[] s_instrumentSeperators = new char[] { '\r', '\n', ',', ';' }; [UnsupportedOSPlatform("browser")] private void ParseSpecs(string? metricsSpecs) { if (metricsSpecs == null) { return; } string[] specStrings = metricsSpecs.Split(s_instrumentSeperators, StringSplitOptions.RemoveEmptyEntries); foreach (string specString in specStrings) { if (!MetricSpec.TryParse(specString, out MetricSpec spec)) { Log.Message($"Failed to parse metric spec: {specString}"); } else { Log.Message($"Parsed metric: {spec}"); if (spec.InstrumentName != null) { _aggregationManager!.Include(spec.MeterName, spec.InstrumentName); } else { _aggregationManager!.Include(spec.MeterName); } } } } private void TransmitMetricValue(Instrument instrument, LabeledAggregationStatistics stats, string sessionId) { if (stats.AggregationStatistics is RateStatistics rateStats) { Log.CounterRateValuePublished(sessionId, instrument.Meter.Name, instrument.Meter.Version, instrument.Name, instrument.Unit, FormatTags(stats.Labels), rateStats.Delta.HasValue ? rateStats.Delta.Value.ToString(CultureInfo.InvariantCulture) : ""); } else if (stats.AggregationStatistics is LastValueStatistics lastValueStats) { Log.GaugeValuePublished(sessionId, instrument.Meter.Name, instrument.Meter.Version, instrument.Name, instrument.Unit, FormatTags(stats.Labels), lastValueStats.LastValue.HasValue ? lastValueStats.LastValue.Value.ToString(CultureInfo.InvariantCulture) : ""); } else if (stats.AggregationStatistics is HistogramStatistics histogramStats) { Log.HistogramValuePublished(sessionId, instrument.Meter.Name, instrument.Meter.Version, instrument.Name, instrument.Unit, FormatTags(stats.Labels), FormatQuantiles(histogramStats.Quantiles)); } } private string FormatTags(KeyValuePair<string, string>[] labels) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < labels.Length; i++) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}", labels[i].Key, labels[i].Value); if (i != labels.Length - 1) { sb.Append(','); } } return sb.ToString(); } private string FormatQuantiles(QuantileValue[] quantiles) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < quantiles.Length; i++) { sb.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}", quantiles[i].Quantile, quantiles[i].Value); if (i != quantiles.Length - 1) { sb.Append(';'); } } return sb.ToString(); } } private sealed class MetricSpec { private const char MeterInstrumentSeparator = '\\'; public string MeterName { get; private set; } public string? InstrumentName { get; private set; } public MetricSpec(string meterName, string? instrumentName) { MeterName = meterName; InstrumentName = instrumentName; } public static bool TryParse(string text, out MetricSpec spec) { int slashIdx = text.IndexOf(MeterInstrumentSeparator); if (slashIdx == -1) { spec = new MetricSpec(text.Trim(), null); return true; } else { string meterName = text.Substring(0, slashIdx).Trim(); string? instrumentName = text.Substring(slashIdx + 1).Trim(); spec = new MetricSpec(meterName, instrumentName); return true; } } public override string ToString() => InstrumentName != null ? MeterName + MeterInstrumentSeparator + InstrumentName : MeterName; } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/HardwareIntrinsics/General/Vector128/GreaterThanOrEqualAll.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\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 GreaterThanOrEqualAllUInt16() { var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAllUInt16(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBooleanBinaryOpTest__GreaterThanOrEqualAllUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, 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 Vector128<UInt16> _fld1; public Vector128<UInt16> _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<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanOrEqualAllUInt16 testClass) { var result = Vector128.GreaterThanOrEqualAll(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__GreaterThanOrEqualAllUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public VectorBooleanBinaryOpTest__GreaterThanOrEqualAllUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.GreaterThanOrEqualAll( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThanOrEqualAll), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThanOrEqualAll), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.GreaterThanOrEqualAll( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Vector128.GreaterThanOrEqualAll(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAllUInt16(); var result = Vector128.GreaterThanOrEqualAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.GreaterThanOrEqualAll(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.GreaterThanOrEqualAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<UInt16> op1, Vector128<UInt16> op2, bool result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt16[] left, UInt16[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] >= right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.GreaterThanOrEqualAll)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GreaterThanOrEqualAllUInt16() { var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAllUInt16(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBooleanBinaryOpTest__GreaterThanOrEqualAllUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, 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 Vector128<UInt16> _fld1; public Vector128<UInt16> _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<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__GreaterThanOrEqualAllUInt16 testClass) { var result = Vector128.GreaterThanOrEqualAll(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__GreaterThanOrEqualAllUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public VectorBooleanBinaryOpTest__GreaterThanOrEqualAllUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.GreaterThanOrEqualAll( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThanOrEqualAll), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThanOrEqualAll), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.GreaterThanOrEqualAll( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Vector128.GreaterThanOrEqualAll(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__GreaterThanOrEqualAllUInt16(); var result = Vector128.GreaterThanOrEqualAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.GreaterThanOrEqualAll(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.GreaterThanOrEqualAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<UInt16> op1, Vector128<UInt16> op2, bool result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt16[] left, UInt16[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] >= right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.GreaterThanOrEqualAll)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {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,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Directed/cmov/Bool_Or_Op_cs_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Bool_Or_Op.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Bool_Or_Op.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Methodical/explicit/coverage/seq_gc_short_1_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="seq_gc_short_1.cs" /> <Compile Include="body_safe_short.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> <AllowUnsafeBlocks>True</AllowUnsafeBlocks> <DebugType>Full</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="seq_gc_short_1.cs" /> <Compile Include="body_safe_short.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/UnzipEven.Vector128.SByte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void UnzipEven_Vector128_SByte() { var test = new SimpleBinaryOpTest__UnzipEven_Vector128_SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__UnzipEven_Vector128_SByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<SByte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__UnzipEven_Vector128_SByte testClass) { var result = AdvSimd.Arm64.UnzipEven(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__UnzipEven_Vector128_SByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.UnzipEven( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__UnzipEven_Vector128_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__UnzipEven_Vector128_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.UnzipEven( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.UnzipEven( AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.UnzipEven), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.UnzipEven), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.UnzipEven( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.UnzipEven( AdvSimd.LoadVector128((SByte*)(pClsVar1)), AdvSimd.LoadVector128((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.UnzipEven(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.UnzipEven(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__UnzipEven_Vector128_SByte(); var result = AdvSimd.Arm64.UnzipEven(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__UnzipEven_Vector128_SByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.UnzipEven( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.UnzipEven(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.UnzipEven( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.UnzipEven(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.Arm64.UnzipEven( AdvSimd.LoadVector128((SByte*)(&test._fld1)), AdvSimd.LoadVector128((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; int index = 0; int half = RetElementCount / 2; for (var i = 0; i < RetElementCount; i+=2, index++) { if (result[index] != left[i] || result[index + half] != right[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.UnzipEven)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void UnzipEven_Vector128_SByte() { var test = new SimpleBinaryOpTest__UnzipEven_Vector128_SByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__UnzipEven_Vector128_SByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<SByte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__UnzipEven_Vector128_SByte testClass) { var result = AdvSimd.Arm64.UnzipEven(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__UnzipEven_Vector128_SByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.UnzipEven( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__UnzipEven_Vector128_SByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__UnzipEven_Vector128_SByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.UnzipEven( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.UnzipEven( AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.UnzipEven), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.UnzipEven), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.UnzipEven( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.UnzipEven( AdvSimd.LoadVector128((SByte*)(pClsVar1)), AdvSimd.LoadVector128((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.UnzipEven(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.UnzipEven(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__UnzipEven_Vector128_SByte(); var result = AdvSimd.Arm64.UnzipEven(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__UnzipEven_Vector128_SByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.UnzipEven( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.UnzipEven(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.UnzipEven( AdvSimd.LoadVector128((SByte*)(pFld1)), AdvSimd.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.UnzipEven(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.Arm64.UnzipEven( AdvSimd.LoadVector128((SByte*)(&test._fld1)), AdvSimd.LoadVector128((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; int index = 0; int half = RetElementCount / 2; for (var i = 0; i < RetElementCount; i+=2, index++) { if (result[index] != left[i] || result[index + half] != right[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.UnzipEven)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ExtractVector64.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.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 ExtractVector64_Int32_1() { var test = new ExtractVectorTest__ExtractVector64_Int32_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 ExtractVectorTest__ExtractVector64_Int32_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector64<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(ExtractVectorTest__ExtractVector64_Int32_1 testClass) { var result = AdvSimd.ExtractVector64(_fld1, _fld2, ElementIndex); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ExtractVectorTest__ExtractVector64_Int32_1 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) { var result = AdvSimd.ExtractVector64( AdvSimd.LoadVector64((Int32*)pFld1), AdvSimd.LoadVector64((Int32*)pFld2), ElementIndex ); 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<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly byte ElementIndex = 1; private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector64<Int32> _clsVar2; private Vector64<Int32> _fld1; private Vector64<Int32> _fld2; private DataTable _dataTable; static ExtractVectorTest__ExtractVector64_Int32_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public ExtractVectorTest__ExtractVector64_Int32_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ExtractVector64( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr), ElementIndex ); 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.ExtractVector64( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)), ElementIndex ); 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.ExtractVector64), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr), ElementIndex }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractVector64), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)), ElementIndex }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ExtractVector64( _clsVar1, _clsVar2, ElementIndex ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector64<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ExtractVector64( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector64((Int32*)(pClsVar2)), ElementIndex ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.ExtractVector64(op1, op2, ElementIndex); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ExtractVector64(op1, op2, ElementIndex); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ExtractVectorTest__ExtractVector64_Int32_1(); var result = AdvSimd.ExtractVector64(test._fld1, test._fld2, ElementIndex); 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 ExtractVectorTest__ExtractVector64_Int32_1(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector64<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.ExtractVector64( AdvSimd.LoadVector64((Int32*)pFld1), AdvSimd.LoadVector64((Int32*)pFld2), ElementIndex ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ExtractVector64(_fld1, _fld2, ElementIndex); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) { var result = AdvSimd.ExtractVector64( AdvSimd.LoadVector64((Int32*)pFld1), AdvSimd.LoadVector64((Int32*)pFld2), ElementIndex ); 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.ExtractVector64(test._fld1, test._fld2, ElementIndex); 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.ExtractVector64( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector64((Int32*)(&test._fld2)), ElementIndex ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> op1, Vector64<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<Vector64<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<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ExtractVector(firstOp, secondOp, ElementIndex, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ExtractVector64)}<Int32>(Vector64<Int32>, Vector64<Int32>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.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 ExtractVector64_Int32_1() { var test = new ExtractVectorTest__ExtractVector64_Int32_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 ExtractVectorTest__ExtractVector64_Int32_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector64<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(ExtractVectorTest__ExtractVector64_Int32_1 testClass) { var result = AdvSimd.ExtractVector64(_fld1, _fld2, ElementIndex); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ExtractVectorTest__ExtractVector64_Int32_1 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) { var result = AdvSimd.ExtractVector64( AdvSimd.LoadVector64((Int32*)pFld1), AdvSimd.LoadVector64((Int32*)pFld2), ElementIndex ); 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<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly byte ElementIndex = 1; private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector64<Int32> _clsVar2; private Vector64<Int32> _fld1; private Vector64<Int32> _fld2; private DataTable _dataTable; static ExtractVectorTest__ExtractVector64_Int32_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public ExtractVectorTest__ExtractVector64_Int32_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ExtractVector64( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr), ElementIndex ); 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.ExtractVector64( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)), ElementIndex ); 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.ExtractVector64), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr), ElementIndex }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ExtractVector64), new Type[] { typeof(Vector64<Int32>), typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)), ElementIndex }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ExtractVector64( _clsVar1, _clsVar2, ElementIndex ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector64<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ExtractVector64( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector64((Int32*)(pClsVar2)), ElementIndex ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.ExtractVector64(op1, op2, ElementIndex); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ExtractVector64(op1, op2, ElementIndex); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ExtractVectorTest__ExtractVector64_Int32_1(); var result = AdvSimd.ExtractVector64(test._fld1, test._fld2, ElementIndex); 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 ExtractVectorTest__ExtractVector64_Int32_1(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector64<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.ExtractVector64( AdvSimd.LoadVector64((Int32*)pFld1), AdvSimd.LoadVector64((Int32*)pFld2), ElementIndex ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ExtractVector64(_fld1, _fld2, ElementIndex); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector64<Int32>* pFld2 = &_fld2) { var result = AdvSimd.ExtractVector64( AdvSimd.LoadVector64((Int32*)pFld1), AdvSimd.LoadVector64((Int32*)pFld2), ElementIndex ); 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.ExtractVector64(test._fld1, test._fld2, ElementIndex); 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.ExtractVector64( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector64((Int32*)(&test._fld2)), ElementIndex ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> op1, Vector64<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<Vector64<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<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ExtractVector(firstOp, secondOp, ElementIndex, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ExtractVector64)}<Int32>(Vector64<Int32>, Vector64<Int32>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Data.Common/src/System/Data/Common/UInt16Storage.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.Xml; using System.Collections; using System.Diagnostics.CodeAnalysis; namespace System.Data.Common { internal sealed class UInt16Storage : DataStorage { private const ushort DefaultValue = ushort.MinValue; private ushort[] _values = default!; // Late-initialized public UInt16Storage(DataColumn column) : base(column, typeof(ushort), DefaultValue, StorageType.UInt16) { } public override object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Sum: ulong sum = DefaultValue; foreach (int record in records) { if (HasValue(record)) { checked { sum += _values[record]; } hasData = true; } } if (hasData) { return sum; } return _nullValue; case AggregateType.Mean: long meanSum = DefaultValue; int meanCount = 0; foreach (int record in records) { if (HasValue(record)) { checked { meanSum += _values[record]; } meanCount++; hasData = true; } } if (hasData) { ushort mean; checked { mean = (ushort)(meanSum / meanCount); } return mean; } return _nullValue; case AggregateType.Var: case AggregateType.StDev: int count = 0; double var = 0.0f; double prec = 0.0f; double dsum = 0.0f; double sqrsum = 0.0f; foreach (int record in records) { if (HasValue(record)) { dsum += _values[record]; sqrsum += _values[record] * (double)_values[record]; count++; } } if (count > 1) { var = count * sqrsum - (dsum * dsum); prec = var / (dsum * dsum); // we are dealing with the risk of a cancellation error // double is guaranteed only for 15 digits so a difference // with a result less than 1e-15 should be considered as zero if ((prec < 1e-15) || (var < 0)) var = 0; else var = var / (count * (count - 1)); if (kind == AggregateType.StDev) { return Math.Sqrt(var); } return var; } return _nullValue; case AggregateType.Min: ushort min = ushort.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (HasValue(record)) { min = Math.Min(_values[record], min); hasData = true; } } if (hasData) { return min; } return _nullValue; case AggregateType.Max: ushort max = ushort.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (HasValue(record)) { max = Math.Max(_values[record], max); hasData = true; } } if (hasData) { return max; } return _nullValue; case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } return null!; case AggregateType.Count: count = 0; for (int i = 0; i < records.Length; i++) { if (HasValue(records[i])) { count++; } } return count; } } catch (OverflowException) { throw ExprException.Overflow(typeof(ushort)); } throw ExceptionBuilder.AggregateException(kind, _dataType); } public override int Compare(int recordNo1, int recordNo2) { ushort valueNo1 = _values[recordNo1]; ushort valueNo2 = _values[recordNo2]; if (valueNo1 == DefaultValue || valueNo2 == DefaultValue) { int bitCheck = CompareBits(recordNo1, recordNo2); if (0 != bitCheck) { return bitCheck; } } //return valueNo1.CompareTo(valueNo2); return valueNo1 - valueNo2; // copied from UInt16.CompareTo(UInt16) } public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { return (HasValue(recordNo) ? 1 : 0); } ushort valueNo1 = _values[recordNo]; if ((DefaultValue == valueNo1) && !HasValue(recordNo)) { return -1; } return valueNo1.CompareTo((ushort)value); //return ((int)valueNo1 - (int)valueNo2); // copied from UInt16.CompareTo(UInt16) } public override object ConvertValue(object? value) { if (_nullValue != value) { if (null != value) { value = ((IConvertible)value).ToUInt16(FormatProvider); } else { value = _nullValue; } } return value; } public override void Copy(int recordNo1, int recordNo2) { CopyBits(recordNo1, recordNo2); _values[recordNo2] = _values[recordNo1]; } public override object Get(int record) { ushort value = _values[record]; if (!value.Equals(DefaultValue)) { return value; } return GetBits(record); } public override void Set(int record, object value) { System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { _values[record] = DefaultValue; SetNullBit(record, true); } else { _values[record] = ((IConvertible)value).ToUInt16(FormatProvider); SetNullBit(record, false); } } public override void SetCapacity(int capacity) { ushort[] newValues = new ushort[capacity]; if (null != _values) { Array.Copy(_values, newValues, Math.Min(capacity, _values.Length)); } _values = newValues; base.SetCapacity(capacity); } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] public override object ConvertXmlToObject(string s) { return XmlConvert.ToUInt16(s); } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] public override string ConvertObjectToXml(object value) { return XmlConvert.ToString((ushort)value); } protected override object GetEmptyStorage(int recordCount) { return new ushort[recordCount]; } protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { ushort[] typedStore = (ushort[])store; typedStore[storeIndex] = _values[record]; nullbits.Set(storeIndex, !HasValue(record)); } protected override void SetStorage(object store, BitArray nullbits) { _values = (ushort[])store; SetNullStorage(nullbits); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Xml; using System.Collections; using System.Diagnostics.CodeAnalysis; namespace System.Data.Common { internal sealed class UInt16Storage : DataStorage { private const ushort DefaultValue = ushort.MinValue; private ushort[] _values = default!; // Late-initialized public UInt16Storage(DataColumn column) : base(column, typeof(ushort), DefaultValue, StorageType.UInt16) { } public override object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Sum: ulong sum = DefaultValue; foreach (int record in records) { if (HasValue(record)) { checked { sum += _values[record]; } hasData = true; } } if (hasData) { return sum; } return _nullValue; case AggregateType.Mean: long meanSum = DefaultValue; int meanCount = 0; foreach (int record in records) { if (HasValue(record)) { checked { meanSum += _values[record]; } meanCount++; hasData = true; } } if (hasData) { ushort mean; checked { mean = (ushort)(meanSum / meanCount); } return mean; } return _nullValue; case AggregateType.Var: case AggregateType.StDev: int count = 0; double var = 0.0f; double prec = 0.0f; double dsum = 0.0f; double sqrsum = 0.0f; foreach (int record in records) { if (HasValue(record)) { dsum += _values[record]; sqrsum += _values[record] * (double)_values[record]; count++; } } if (count > 1) { var = count * sqrsum - (dsum * dsum); prec = var / (dsum * dsum); // we are dealing with the risk of a cancellation error // double is guaranteed only for 15 digits so a difference // with a result less than 1e-15 should be considered as zero if ((prec < 1e-15) || (var < 0)) var = 0; else var = var / (count * (count - 1)); if (kind == AggregateType.StDev) { return Math.Sqrt(var); } return var; } return _nullValue; case AggregateType.Min: ushort min = ushort.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (HasValue(record)) { min = Math.Min(_values[record], min); hasData = true; } } if (hasData) { return min; } return _nullValue; case AggregateType.Max: ushort max = ushort.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (HasValue(record)) { max = Math.Max(_values[record], max); hasData = true; } } if (hasData) { return max; } return _nullValue; case AggregateType.First: // Does not seem to be implemented if (records.Length > 0) { return _values[records[0]]; } return null!; case AggregateType.Count: count = 0; for (int i = 0; i < records.Length; i++) { if (HasValue(records[i])) { count++; } } return count; } } catch (OverflowException) { throw ExprException.Overflow(typeof(ushort)); } throw ExceptionBuilder.AggregateException(kind, _dataType); } public override int Compare(int recordNo1, int recordNo2) { ushort valueNo1 = _values[recordNo1]; ushort valueNo2 = _values[recordNo2]; if (valueNo1 == DefaultValue || valueNo2 == DefaultValue) { int bitCheck = CompareBits(recordNo1, recordNo2); if (0 != bitCheck) { return bitCheck; } } //return valueNo1.CompareTo(valueNo2); return valueNo1 - valueNo2; // copied from UInt16.CompareTo(UInt16) } public override int CompareValueTo(int recordNo, object? value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { return (HasValue(recordNo) ? 1 : 0); } ushort valueNo1 = _values[recordNo]; if ((DefaultValue == valueNo1) && !HasValue(recordNo)) { return -1; } return valueNo1.CompareTo((ushort)value); //return ((int)valueNo1 - (int)valueNo2); // copied from UInt16.CompareTo(UInt16) } public override object ConvertValue(object? value) { if (_nullValue != value) { if (null != value) { value = ((IConvertible)value).ToUInt16(FormatProvider); } else { value = _nullValue; } } return value; } public override void Copy(int recordNo1, int recordNo2) { CopyBits(recordNo1, recordNo2); _values[recordNo2] = _values[recordNo1]; } public override object Get(int record) { ushort value = _values[record]; if (!value.Equals(DefaultValue)) { return value; } return GetBits(record); } public override void Set(int record, object value) { System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { _values[record] = DefaultValue; SetNullBit(record, true); } else { _values[record] = ((IConvertible)value).ToUInt16(FormatProvider); SetNullBit(record, false); } } public override void SetCapacity(int capacity) { ushort[] newValues = new ushort[capacity]; if (null != _values) { Array.Copy(_values, newValues, Math.Min(capacity, _values.Length)); } _values = newValues; base.SetCapacity(capacity); } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] public override object ConvertXmlToObject(string s) { return XmlConvert.ToUInt16(s); } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] public override string ConvertObjectToXml(object value) { return XmlConvert.ToString((ushort)value); } protected override object GetEmptyStorage(int recordCount) { return new ushort[recordCount]; } protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { ushort[] typedStore = (ushort[])store; typedStore[storeIndex] = _values[record]; nullbits.Set(storeIndex, !HasValue(record)); } protected override void SetStorage(object store, BitArray nullbits) { _values = (ushort[])store; SetNullStorage(nullbits); } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Performance/CodeQuality/Benchstones/BenchI/QuickSort/QuickSort.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; namespace Benchstone.BenchI { public static class QuickSort { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 80000; #endif const int MAXNUM = 200; const int MODULUS = 0x20000; const int C = 13849; const int A = 25173; static int s_seed = 7; static int Random(int size) { unchecked { s_seed = s_seed * A + C; } return (s_seed % size); } static void Quick(int lo, int hi, int[] arr) { int i, j; int pivot, temp; if (lo < hi) { for (i = lo, j = hi, pivot = arr[hi]; i < j;) { while (i < j && arr[i] <= pivot){ ++i; } while (j > i && arr[j] >= pivot) { --j; } if (i < j) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // need to swap the pivot and a[i](or a[j] as i==j) so // that the pivot will be at its final place in the sorted array if (i != hi) { temp = arr[i]; arr[i] = pivot; arr[hi] = temp; } Quick(lo, i - 1, arr); Quick(i + 1, hi, arr); } } [MethodImpl(MethodImplOptions.NoInlining)] static bool Bench() { int[] buffer = new int[MAXNUM]; for (int j = 0; j < MAXNUM; ++j) { int temp = Random(MODULUS); if (temp < 0){ temp = (-temp); } buffer[j] = temp; } Quick(0, MAXNUM - 1, buffer); for (int j = 0; j < MAXNUM - 1; ++j) { if (buffer[j] > buffer[j+1]) { return false; } } return true; } static bool TestBase() { bool result = true; for (int i = 0; i < Iterations; i++) { result &= Bench(); } return result; } public static int Main() { bool result = TestBase(); return (result ? 100 : -1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; using System.Runtime.CompilerServices; namespace Benchstone.BenchI { public static class QuickSort { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 80000; #endif const int MAXNUM = 200; const int MODULUS = 0x20000; const int C = 13849; const int A = 25173; static int s_seed = 7; static int Random(int size) { unchecked { s_seed = s_seed * A + C; } return (s_seed % size); } static void Quick(int lo, int hi, int[] arr) { int i, j; int pivot, temp; if (lo < hi) { for (i = lo, j = hi, pivot = arr[hi]; i < j;) { while (i < j && arr[i] <= pivot){ ++i; } while (j > i && arr[j] >= pivot) { --j; } if (i < j) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // need to swap the pivot and a[i](or a[j] as i==j) so // that the pivot will be at its final place in the sorted array if (i != hi) { temp = arr[i]; arr[i] = pivot; arr[hi] = temp; } Quick(lo, i - 1, arr); Quick(i + 1, hi, arr); } } [MethodImpl(MethodImplOptions.NoInlining)] static bool Bench() { int[] buffer = new int[MAXNUM]; for (int j = 0; j < MAXNUM; ++j) { int temp = Random(MODULUS); if (temp < 0){ temp = (-temp); } buffer[j] = temp; } Quick(0, MAXNUM - 1, buffer); for (int j = 0; j < MAXNUM - 1; ++j) { if (buffer[j] > buffer[j+1]) { return false; } } return true; } static bool TestBase() { bool result = true; for (int i = 0; i < Iterations; i++) { result &= Bench(); } return result; } public static int Main() { bool result = TestBase(); return (result ? 100 : -1); } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/HardwareIntrinsics/X86/Sse2/Multiply_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="Multiply.cs" /> <Compile Include="TestTableSse2.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="Multiply.cs" /> <Compile Include="TestTableSse2.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/Interop/PInvoke/Array/MarshalArrayAsField/AsLPArray/AsLPArrayTest.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; class Test { [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeIntArraySeqStructByVal([In]S_INTArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeUIntArraySeqStructByVal([In]S_UINTArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeShortArraySeqStructByVal([In]S_SHORTArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeWordArraySeqStructByVal([In]S_WORDArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLong64ArraySeqStructByVal([In]S_LONG64Array_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeULong64ArraySeqStructByVal([In]S_ULONG64Array_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeDoubleArraySeqStructByVal([In]S_DOUBLEArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeFloatArraySeqStructByVal([In]S_FLOATArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeByteArraySeqStructByVal([In]S_BYTEArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeCharArraySeqStructByVal([In]S_CHARArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPSTRArraySeqStructByVal([In]S_LPSTRArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPCSTRArraySeqStructByVal([In]S_LPCSTRArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeBSTRArraySeqStructByVal([In]S_BSTRArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeStructArraySeqStructByVal([In]S_StructArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeIntArraySeqClassByVal([In]C_INTArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeUIntArraySeqClassByVal([In]C_UINTArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeShortArraySeqClassByVal([In]C_SHORTArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeWordArraySeqClassByVal([In]C_WORDArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLong64ArraySeqClassByVal([In]C_LONG64Array_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeULong64ArraySeqClassByVal([In]C_ULONG64Array_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeDoubleArraySeqClassByVal([In]C_DOUBLEArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeFloatArraySeqClassByVal([In]C_FLOATArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeByteArraySeqClassByVal([In]C_BYTEArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeCharArraySeqClassByVal([In]C_CHARArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPSTRArraySeqClassByVal([In]C_LPSTRArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPCSTRArraySeqClassByVal([In]C_LPCSTRArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeBSTRArraySeqClassByVal([In]C_BSTRArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeStructArraySeqClassByVal([In]C_StructArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeIntArrayExpStructByVal([In]S_INTArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeUIntArrayExpStructByVal([In]S_UINTArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeShortArrayExpStructByVal([In]S_SHORTArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeWordArrayExpStructByVal([In]S_WORDArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLong64ArrayExpStructByVal([In]S_LONG64Array_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeULong64ArrayExpStructByVal([In]S_ULONG64Array_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeDoubleArrayExpStructByVal([In]S_DOUBLEArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeFloatArrayExpStructByVal([In]S_FLOATArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeByteArrayExpStructByVal([In]S_BYTEArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeCharArrayExpStructByVal([In]S_CHARArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPSTRArrayExpStructByVal([In]S_LPSTRArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPCSTRArrayExpStructByVal([In]S_LPCSTRArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeBSTRArrayExpStructByVal([In]S_BSTRArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeStructArrayExpStructByVal([In]S_StructArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeIntArrayExpClassByVal([In]C_INTArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeUIntArrayExpClassByVal([In]C_UINTArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeShortArrayExpClassByVal([In]C_SHORTArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeWordArrayExpClassByVal([In]C_WORDArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLong64ArrayExpClassByVal([In]C_LONG64Array_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeULong64ArrayExpClassByVal([In]C_ULONG64Array_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeDoubleArrayExpClassByVal([In]C_DOUBLEArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeFloatArrayExpClassByVal([In]C_FLOATArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeByteArrayExpClassByVal([In]C_BYTEArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeCharArrayExpClassByVal([In]C_CHARArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPSTRArrayExpClassByVal([In]C_LPSTRArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPCSTRArrayExpClassByVal([In]C_LPCSTRArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeBSTRArrayExpClassByVal([In]C_BSTRArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeStructArrayExpClassByVal([In]C_StructArray_Exp c, [In]int size); #region Helper internal const int ARRAY_SIZE = 100; static T[] InitArray<T>(int size) { T[] array = new T[size]; for (int i = 0; i < array.Length; i++) array[i] = (T)Convert.ChangeType(i, typeof(T)); return array; } static TestStruct[] InitStructArray(int size) { TestStruct[] array = new TestStruct[size]; for (int i = 0; i < array.Length; i++) { array[i].x = i; array[i].d = i; array[i].l = i; array[i].str = i.ToString(); } return array; } static bool[] InitBoolArray(int size) { bool[] array = new bool[size]; for (int i = 0; i < array.Length; i++) { if (i % 2 == 0) array[i] = true; else array[i] = false; } return array; } #endregion static void RunTest1(string report) { Console.WriteLine(report); S_INTArray_Seq s1 = new S_INTArray_Seq(); s1.arr = InitArray<int>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeIntArraySeqStructByVal(s1, ARRAY_SIZE)); S_UINTArray_Seq s2 = new S_UINTArray_Seq(); s2.arr = InitArray<uint>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeUIntArraySeqStructByVal(s2, ARRAY_SIZE)); S_SHORTArray_Seq s3 = new S_SHORTArray_Seq(); s3.arr = InitArray<short>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeShortArraySeqStructByVal(s3, ARRAY_SIZE)); S_WORDArray_Seq s4 = new S_WORDArray_Seq(); s4.arr = InitArray<ushort>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeWordArraySeqStructByVal(s4, ARRAY_SIZE)); S_LONG64Array_Seq s5 = new S_LONG64Array_Seq(); s5.arr = InitArray<long>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLong64ArraySeqStructByVal(s5, ARRAY_SIZE)); S_ULONG64Array_Seq s6 = new S_ULONG64Array_Seq(); s6.arr = InitArray<ulong>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeULong64ArraySeqStructByVal(s6, ARRAY_SIZE)); S_DOUBLEArray_Seq s7 = new S_DOUBLEArray_Seq(); s7.arr = InitArray<double>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeDoubleArraySeqStructByVal(s7, ARRAY_SIZE)); S_FLOATArray_Seq s8 = new S_FLOATArray_Seq(); s8.arr = InitArray<float>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeFloatArraySeqStructByVal(s8, ARRAY_SIZE)); S_BYTEArray_Seq s9 = new S_BYTEArray_Seq(); s9.arr = InitArray<byte>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeByteArraySeqStructByVal(s9, ARRAY_SIZE)); S_CHARArray_Seq s10 = new S_CHARArray_Seq(); s10.arr = InitArray<char>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeCharArraySeqStructByVal(s10, ARRAY_SIZE)); S_LPSTRArray_Seq s11 = new S_LPSTRArray_Seq(); s11.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPSTRArraySeqStructByVal(s11, ARRAY_SIZE)); S_LPCSTRArray_Seq s12 = new S_LPCSTRArray_Seq(); s12.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPCSTRArraySeqStructByVal(s12, ARRAY_SIZE)); if (OperatingSystem.IsWindows()) { S_BSTRArray_Seq s13 = new S_BSTRArray_Seq(); s13.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeBSTRArraySeqStructByVal(s13, ARRAY_SIZE)); } S_StructArray_Seq s14 = new S_StructArray_Seq(); s14.arr = InitStructArray(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeStructArraySeqStructByVal(s14, ARRAY_SIZE)); } static void RunTest2(string report) { Console.WriteLine(report); C_INTArray_Seq c1 = new C_INTArray_Seq(); c1.arr = InitArray<int>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeIntArraySeqClassByVal(c1, ARRAY_SIZE)); C_UINTArray_Seq c2 = new C_UINTArray_Seq(); c2.arr = InitArray<uint>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeUIntArraySeqClassByVal(c2, ARRAY_SIZE)); C_SHORTArray_Seq c3 = new C_SHORTArray_Seq(); c3.arr = InitArray<short>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeShortArraySeqClassByVal(c3, ARRAY_SIZE)); C_WORDArray_Seq c4 = new C_WORDArray_Seq(); c4.arr = InitArray<ushort>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeWordArraySeqClassByVal(c4, ARRAY_SIZE)); C_LONG64Array_Seq c5 = new C_LONG64Array_Seq(); c5.arr = InitArray<long>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLong64ArraySeqClassByVal(c5, ARRAY_SIZE)); C_ULONG64Array_Seq c6 = new C_ULONG64Array_Seq(); c6.arr = InitArray<ulong>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeULong64ArraySeqClassByVal(c6, ARRAY_SIZE)); C_DOUBLEArray_Seq c7 = new C_DOUBLEArray_Seq(); c7.arr = InitArray<double>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeDoubleArraySeqClassByVal(c7, ARRAY_SIZE)); C_FLOATArray_Seq c8 = new C_FLOATArray_Seq(); c8.arr = InitArray<float>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeFloatArraySeqClassByVal(c8, ARRAY_SIZE)); C_BYTEArray_Seq c9 = new C_BYTEArray_Seq(); c9.arr = InitArray<byte>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeByteArraySeqClassByVal(c9, ARRAY_SIZE)); C_CHARArray_Seq c10 = new C_CHARArray_Seq(); c10.arr = InitArray<char>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeCharArraySeqClassByVal(c10, ARRAY_SIZE)); C_LPSTRArray_Seq c11 = new C_LPSTRArray_Seq(); c11.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPSTRArraySeqClassByVal(c11, ARRAY_SIZE)); C_LPCSTRArray_Seq c12 = new C_LPCSTRArray_Seq(); c12.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPCSTRArraySeqClassByVal(c12, ARRAY_SIZE)); if (OperatingSystem.IsWindows()) { C_BSTRArray_Seq c13 = new C_BSTRArray_Seq(); c13.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeBSTRArraySeqClassByVal(c13, ARRAY_SIZE)); } C_StructArray_Seq c14 = new C_StructArray_Seq(); c14.arr = InitStructArray(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeStructArraySeqClassByVal(c14, ARRAY_SIZE)); } static void RunTest3(string report) { Console.WriteLine(report); S_INTArray_Exp s1 = new S_INTArray_Exp(); s1.arr = InitArray<int>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeIntArrayExpStructByVal(s1, ARRAY_SIZE)); S_UINTArray_Exp s2 = new S_UINTArray_Exp(); s2.arr = InitArray<uint>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeUIntArrayExpStructByVal(s2, ARRAY_SIZE)); S_SHORTArray_Exp s3 = new S_SHORTArray_Exp(); s3.arr = InitArray<short>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeShortArrayExpStructByVal(s3, ARRAY_SIZE)); S_WORDArray_Exp s4 = new S_WORDArray_Exp(); s4.arr = InitArray<ushort>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeWordArrayExpStructByVal(s4, ARRAY_SIZE)); S_LONG64Array_Exp s5 = new S_LONG64Array_Exp(); s5.arr = InitArray<long>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLong64ArrayExpStructByVal(s5, ARRAY_SIZE)); S_ULONG64Array_Exp s6 = new S_ULONG64Array_Exp(); s6.arr = InitArray<ulong>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeULong64ArrayExpStructByVal(s6, ARRAY_SIZE)); S_DOUBLEArray_Exp s7 = new S_DOUBLEArray_Exp(); s7.arr = InitArray<double>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeDoubleArrayExpStructByVal(s7, ARRAY_SIZE)); S_FLOATArray_Exp s8 = new S_FLOATArray_Exp(); s8.arr = InitArray<float>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeFloatArrayExpStructByVal(s8, ARRAY_SIZE)); S_BYTEArray_Exp s9 = new S_BYTEArray_Exp(); s9.arr = InitArray<byte>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeByteArrayExpStructByVal(s9, ARRAY_SIZE)); S_CHARArray_Exp s10 = new S_CHARArray_Exp(); s10.arr = InitArray<char>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeCharArrayExpStructByVal(s10, ARRAY_SIZE)); S_LPSTRArray_Exp s11 = new S_LPSTRArray_Exp(); s11.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPSTRArrayExpStructByVal(s11, ARRAY_SIZE)); S_LPCSTRArray_Exp s12 = new S_LPCSTRArray_Exp(); s12.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPCSTRArrayExpStructByVal(s12, ARRAY_SIZE)); if (OperatingSystem.IsWindows()) { S_BSTRArray_Exp s13 = new S_BSTRArray_Exp(); s13.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeBSTRArrayExpStructByVal(s13, ARRAY_SIZE)); } S_StructArray_Exp s14 = new S_StructArray_Exp(); s14.arr = InitStructArray(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeStructArrayExpStructByVal(s14, ARRAY_SIZE)); } static void RunTest4(string report) { Console.WriteLine(report); C_INTArray_Exp c1 = new C_INTArray_Exp(); c1.arr = InitArray<int>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeIntArrayExpClassByVal(c1, ARRAY_SIZE)); C_UINTArray_Exp c2 = new C_UINTArray_Exp(); c2.arr = InitArray<uint>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeUIntArrayExpClassByVal(c2, ARRAY_SIZE)); C_SHORTArray_Exp c3 = new C_SHORTArray_Exp(); c3.arr = InitArray<short>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeShortArrayExpClassByVal(c3, ARRAY_SIZE)); C_WORDArray_Exp c4 = new C_WORDArray_Exp(); c4.arr = InitArray<ushort>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeWordArrayExpClassByVal(c4, ARRAY_SIZE)); C_LONG64Array_Exp c5 = new C_LONG64Array_Exp(); c5.arr = InitArray<long>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLong64ArrayExpClassByVal(c5, ARRAY_SIZE)); C_ULONG64Array_Exp c6 = new C_ULONG64Array_Exp(); c6.arr = InitArray<ulong>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeULong64ArrayExpClassByVal(c6, ARRAY_SIZE)); C_DOUBLEArray_Exp c7 = new C_DOUBLEArray_Exp(); c7.arr = InitArray<double>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeDoubleArrayExpClassByVal(c7, ARRAY_SIZE)); C_FLOATArray_Exp c8 = new C_FLOATArray_Exp(); c8.arr = InitArray<float>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeFloatArrayExpClassByVal(c8, ARRAY_SIZE)); C_BYTEArray_Exp c9 = new C_BYTEArray_Exp(); c9.arr = InitArray<byte>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeByteArrayExpClassByVal(c9, ARRAY_SIZE)); C_CHARArray_Exp c10 = new C_CHARArray_Exp(); c10.arr = InitArray<char>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeCharArrayExpClassByVal(c10, ARRAY_SIZE)); C_LPSTRArray_Exp c11 = new C_LPSTRArray_Exp(); c11.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPSTRArrayExpClassByVal(c11, ARRAY_SIZE)); C_LPCSTRArray_Exp c12 = new C_LPCSTRArray_Exp(); c12.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPCSTRArrayExpClassByVal(c12, ARRAY_SIZE)); if (OperatingSystem.IsWindows()) { C_BSTRArray_Exp c13 = new C_BSTRArray_Exp(); c13.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeBSTRArrayExpClassByVal(c13, ARRAY_SIZE)); } C_StructArray_Exp c14 = new C_StructArray_Exp(); c14.arr = InitStructArray(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeStructArrayExpClassByVal(c14, ARRAY_SIZE)); } static int Main(string[] args) { try { RunTest1("RunTest 1 : Marshal Array In Sequential Struct As LPArray. "); RunTest2("RunTest 2 : Marshal Array In Sequential Class As LPArray. "); if (OperatingSystem.IsWindows()) { RunTest3("RunTest 3 : Marshal Array In Explicit Struct As LPArray. "); } RunTest4("RunTest 4 : Marshal Array In Explicit Class As LPArray. "); Console.WriteLine("\nTest PASS."); return 100; } catch (Exception e) { Console.WriteLine($"\nTest FAIL: {e}"); return 101; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using Xunit; class Test { [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeIntArraySeqStructByVal([In]S_INTArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeUIntArraySeqStructByVal([In]S_UINTArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeShortArraySeqStructByVal([In]S_SHORTArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeWordArraySeqStructByVal([In]S_WORDArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLong64ArraySeqStructByVal([In]S_LONG64Array_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeULong64ArraySeqStructByVal([In]S_ULONG64Array_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeDoubleArraySeqStructByVal([In]S_DOUBLEArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeFloatArraySeqStructByVal([In]S_FLOATArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeByteArraySeqStructByVal([In]S_BYTEArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeCharArraySeqStructByVal([In]S_CHARArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPSTRArraySeqStructByVal([In]S_LPSTRArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPCSTRArraySeqStructByVal([In]S_LPCSTRArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeBSTRArraySeqStructByVal([In]S_BSTRArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeStructArraySeqStructByVal([In]S_StructArray_Seq s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeIntArraySeqClassByVal([In]C_INTArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeUIntArraySeqClassByVal([In]C_UINTArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeShortArraySeqClassByVal([In]C_SHORTArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeWordArraySeqClassByVal([In]C_WORDArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLong64ArraySeqClassByVal([In]C_LONG64Array_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeULong64ArraySeqClassByVal([In]C_ULONG64Array_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeDoubleArraySeqClassByVal([In]C_DOUBLEArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeFloatArraySeqClassByVal([In]C_FLOATArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeByteArraySeqClassByVal([In]C_BYTEArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeCharArraySeqClassByVal([In]C_CHARArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPSTRArraySeqClassByVal([In]C_LPSTRArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPCSTRArraySeqClassByVal([In]C_LPCSTRArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeBSTRArraySeqClassByVal([In]C_BSTRArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeStructArraySeqClassByVal([In]C_StructArray_Seq c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeIntArrayExpStructByVal([In]S_INTArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeUIntArrayExpStructByVal([In]S_UINTArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeShortArrayExpStructByVal([In]S_SHORTArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeWordArrayExpStructByVal([In]S_WORDArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLong64ArrayExpStructByVal([In]S_LONG64Array_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeULong64ArrayExpStructByVal([In]S_ULONG64Array_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeDoubleArrayExpStructByVal([In]S_DOUBLEArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeFloatArrayExpStructByVal([In]S_FLOATArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeByteArrayExpStructByVal([In]S_BYTEArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeCharArrayExpStructByVal([In]S_CHARArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPSTRArrayExpStructByVal([In]S_LPSTRArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPCSTRArrayExpStructByVal([In]S_LPCSTRArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeBSTRArrayExpStructByVal([In]S_BSTRArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeStructArrayExpStructByVal([In]S_StructArray_Exp s, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeIntArrayExpClassByVal([In]C_INTArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeUIntArrayExpClassByVal([In]C_UINTArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeShortArrayExpClassByVal([In]C_SHORTArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeWordArrayExpClassByVal([In]C_WORDArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLong64ArrayExpClassByVal([In]C_LONG64Array_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeULong64ArrayExpClassByVal([In]C_ULONG64Array_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeDoubleArrayExpClassByVal([In]C_DOUBLEArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeFloatArrayExpClassByVal([In]C_FLOATArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeByteArrayExpClassByVal([In]C_BYTEArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeCharArrayExpClassByVal([In]C_CHARArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPSTRArrayExpClassByVal([In]C_LPSTRArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeLPCSTRArrayExpClassByVal([In]C_LPCSTRArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeBSTRArrayExpClassByVal([In]C_BSTRArray_Exp c, [In]int size); [DllImport("MarshalArrayByValArrayNative", CallingConvention = CallingConvention.Cdecl)] static extern bool TakeStructArrayExpClassByVal([In]C_StructArray_Exp c, [In]int size); #region Helper internal const int ARRAY_SIZE = 100; static T[] InitArray<T>(int size) { T[] array = new T[size]; for (int i = 0; i < array.Length; i++) array[i] = (T)Convert.ChangeType(i, typeof(T)); return array; } static TestStruct[] InitStructArray(int size) { TestStruct[] array = new TestStruct[size]; for (int i = 0; i < array.Length; i++) { array[i].x = i; array[i].d = i; array[i].l = i; array[i].str = i.ToString(); } return array; } static bool[] InitBoolArray(int size) { bool[] array = new bool[size]; for (int i = 0; i < array.Length; i++) { if (i % 2 == 0) array[i] = true; else array[i] = false; } return array; } #endregion static void RunTest1(string report) { Console.WriteLine(report); S_INTArray_Seq s1 = new S_INTArray_Seq(); s1.arr = InitArray<int>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeIntArraySeqStructByVal(s1, ARRAY_SIZE)); S_UINTArray_Seq s2 = new S_UINTArray_Seq(); s2.arr = InitArray<uint>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeUIntArraySeqStructByVal(s2, ARRAY_SIZE)); S_SHORTArray_Seq s3 = new S_SHORTArray_Seq(); s3.arr = InitArray<short>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeShortArraySeqStructByVal(s3, ARRAY_SIZE)); S_WORDArray_Seq s4 = new S_WORDArray_Seq(); s4.arr = InitArray<ushort>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeWordArraySeqStructByVal(s4, ARRAY_SIZE)); S_LONG64Array_Seq s5 = new S_LONG64Array_Seq(); s5.arr = InitArray<long>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLong64ArraySeqStructByVal(s5, ARRAY_SIZE)); S_ULONG64Array_Seq s6 = new S_ULONG64Array_Seq(); s6.arr = InitArray<ulong>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeULong64ArraySeqStructByVal(s6, ARRAY_SIZE)); S_DOUBLEArray_Seq s7 = new S_DOUBLEArray_Seq(); s7.arr = InitArray<double>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeDoubleArraySeqStructByVal(s7, ARRAY_SIZE)); S_FLOATArray_Seq s8 = new S_FLOATArray_Seq(); s8.arr = InitArray<float>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeFloatArraySeqStructByVal(s8, ARRAY_SIZE)); S_BYTEArray_Seq s9 = new S_BYTEArray_Seq(); s9.arr = InitArray<byte>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeByteArraySeqStructByVal(s9, ARRAY_SIZE)); S_CHARArray_Seq s10 = new S_CHARArray_Seq(); s10.arr = InitArray<char>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeCharArraySeqStructByVal(s10, ARRAY_SIZE)); S_LPSTRArray_Seq s11 = new S_LPSTRArray_Seq(); s11.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPSTRArraySeqStructByVal(s11, ARRAY_SIZE)); S_LPCSTRArray_Seq s12 = new S_LPCSTRArray_Seq(); s12.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPCSTRArraySeqStructByVal(s12, ARRAY_SIZE)); if (OperatingSystem.IsWindows()) { S_BSTRArray_Seq s13 = new S_BSTRArray_Seq(); s13.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeBSTRArraySeqStructByVal(s13, ARRAY_SIZE)); } S_StructArray_Seq s14 = new S_StructArray_Seq(); s14.arr = InitStructArray(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeStructArraySeqStructByVal(s14, ARRAY_SIZE)); } static void RunTest2(string report) { Console.WriteLine(report); C_INTArray_Seq c1 = new C_INTArray_Seq(); c1.arr = InitArray<int>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeIntArraySeqClassByVal(c1, ARRAY_SIZE)); C_UINTArray_Seq c2 = new C_UINTArray_Seq(); c2.arr = InitArray<uint>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeUIntArraySeqClassByVal(c2, ARRAY_SIZE)); C_SHORTArray_Seq c3 = new C_SHORTArray_Seq(); c3.arr = InitArray<short>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeShortArraySeqClassByVal(c3, ARRAY_SIZE)); C_WORDArray_Seq c4 = new C_WORDArray_Seq(); c4.arr = InitArray<ushort>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeWordArraySeqClassByVal(c4, ARRAY_SIZE)); C_LONG64Array_Seq c5 = new C_LONG64Array_Seq(); c5.arr = InitArray<long>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLong64ArraySeqClassByVal(c5, ARRAY_SIZE)); C_ULONG64Array_Seq c6 = new C_ULONG64Array_Seq(); c6.arr = InitArray<ulong>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeULong64ArraySeqClassByVal(c6, ARRAY_SIZE)); C_DOUBLEArray_Seq c7 = new C_DOUBLEArray_Seq(); c7.arr = InitArray<double>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeDoubleArraySeqClassByVal(c7, ARRAY_SIZE)); C_FLOATArray_Seq c8 = new C_FLOATArray_Seq(); c8.arr = InitArray<float>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeFloatArraySeqClassByVal(c8, ARRAY_SIZE)); C_BYTEArray_Seq c9 = new C_BYTEArray_Seq(); c9.arr = InitArray<byte>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeByteArraySeqClassByVal(c9, ARRAY_SIZE)); C_CHARArray_Seq c10 = new C_CHARArray_Seq(); c10.arr = InitArray<char>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeCharArraySeqClassByVal(c10, ARRAY_SIZE)); C_LPSTRArray_Seq c11 = new C_LPSTRArray_Seq(); c11.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPSTRArraySeqClassByVal(c11, ARRAY_SIZE)); C_LPCSTRArray_Seq c12 = new C_LPCSTRArray_Seq(); c12.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPCSTRArraySeqClassByVal(c12, ARRAY_SIZE)); if (OperatingSystem.IsWindows()) { C_BSTRArray_Seq c13 = new C_BSTRArray_Seq(); c13.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeBSTRArraySeqClassByVal(c13, ARRAY_SIZE)); } C_StructArray_Seq c14 = new C_StructArray_Seq(); c14.arr = InitStructArray(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeStructArraySeqClassByVal(c14, ARRAY_SIZE)); } static void RunTest3(string report) { Console.WriteLine(report); S_INTArray_Exp s1 = new S_INTArray_Exp(); s1.arr = InitArray<int>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeIntArrayExpStructByVal(s1, ARRAY_SIZE)); S_UINTArray_Exp s2 = new S_UINTArray_Exp(); s2.arr = InitArray<uint>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeUIntArrayExpStructByVal(s2, ARRAY_SIZE)); S_SHORTArray_Exp s3 = new S_SHORTArray_Exp(); s3.arr = InitArray<short>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeShortArrayExpStructByVal(s3, ARRAY_SIZE)); S_WORDArray_Exp s4 = new S_WORDArray_Exp(); s4.arr = InitArray<ushort>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeWordArrayExpStructByVal(s4, ARRAY_SIZE)); S_LONG64Array_Exp s5 = new S_LONG64Array_Exp(); s5.arr = InitArray<long>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLong64ArrayExpStructByVal(s5, ARRAY_SIZE)); S_ULONG64Array_Exp s6 = new S_ULONG64Array_Exp(); s6.arr = InitArray<ulong>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeULong64ArrayExpStructByVal(s6, ARRAY_SIZE)); S_DOUBLEArray_Exp s7 = new S_DOUBLEArray_Exp(); s7.arr = InitArray<double>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeDoubleArrayExpStructByVal(s7, ARRAY_SIZE)); S_FLOATArray_Exp s8 = new S_FLOATArray_Exp(); s8.arr = InitArray<float>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeFloatArrayExpStructByVal(s8, ARRAY_SIZE)); S_BYTEArray_Exp s9 = new S_BYTEArray_Exp(); s9.arr = InitArray<byte>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeByteArrayExpStructByVal(s9, ARRAY_SIZE)); S_CHARArray_Exp s10 = new S_CHARArray_Exp(); s10.arr = InitArray<char>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeCharArrayExpStructByVal(s10, ARRAY_SIZE)); S_LPSTRArray_Exp s11 = new S_LPSTRArray_Exp(); s11.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPSTRArrayExpStructByVal(s11, ARRAY_SIZE)); S_LPCSTRArray_Exp s12 = new S_LPCSTRArray_Exp(); s12.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPCSTRArrayExpStructByVal(s12, ARRAY_SIZE)); if (OperatingSystem.IsWindows()) { S_BSTRArray_Exp s13 = new S_BSTRArray_Exp(); s13.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeBSTRArrayExpStructByVal(s13, ARRAY_SIZE)); } S_StructArray_Exp s14 = new S_StructArray_Exp(); s14.arr = InitStructArray(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeStructArrayExpStructByVal(s14, ARRAY_SIZE)); } static void RunTest4(string report) { Console.WriteLine(report); C_INTArray_Exp c1 = new C_INTArray_Exp(); c1.arr = InitArray<int>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeIntArrayExpClassByVal(c1, ARRAY_SIZE)); C_UINTArray_Exp c2 = new C_UINTArray_Exp(); c2.arr = InitArray<uint>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeUIntArrayExpClassByVal(c2, ARRAY_SIZE)); C_SHORTArray_Exp c3 = new C_SHORTArray_Exp(); c3.arr = InitArray<short>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeShortArrayExpClassByVal(c3, ARRAY_SIZE)); C_WORDArray_Exp c4 = new C_WORDArray_Exp(); c4.arr = InitArray<ushort>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeWordArrayExpClassByVal(c4, ARRAY_SIZE)); C_LONG64Array_Exp c5 = new C_LONG64Array_Exp(); c5.arr = InitArray<long>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLong64ArrayExpClassByVal(c5, ARRAY_SIZE)); C_ULONG64Array_Exp c6 = new C_ULONG64Array_Exp(); c6.arr = InitArray<ulong>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeULong64ArrayExpClassByVal(c6, ARRAY_SIZE)); C_DOUBLEArray_Exp c7 = new C_DOUBLEArray_Exp(); c7.arr = InitArray<double>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeDoubleArrayExpClassByVal(c7, ARRAY_SIZE)); C_FLOATArray_Exp c8 = new C_FLOATArray_Exp(); c8.arr = InitArray<float>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeFloatArrayExpClassByVal(c8, ARRAY_SIZE)); C_BYTEArray_Exp c9 = new C_BYTEArray_Exp(); c9.arr = InitArray<byte>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeByteArrayExpClassByVal(c9, ARRAY_SIZE)); C_CHARArray_Exp c10 = new C_CHARArray_Exp(); c10.arr = InitArray<char>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeCharArrayExpClassByVal(c10, ARRAY_SIZE)); C_LPSTRArray_Exp c11 = new C_LPSTRArray_Exp(); c11.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPSTRArrayExpClassByVal(c11, ARRAY_SIZE)); C_LPCSTRArray_Exp c12 = new C_LPCSTRArray_Exp(); c12.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeLPCSTRArrayExpClassByVal(c12, ARRAY_SIZE)); if (OperatingSystem.IsWindows()) { C_BSTRArray_Exp c13 = new C_BSTRArray_Exp(); c13.arr = InitArray<string>(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeBSTRArrayExpClassByVal(c13, ARRAY_SIZE)); } C_StructArray_Exp c14 = new C_StructArray_Exp(); c14.arr = InitStructArray(ARRAY_SIZE); Assert.Throws<TypeLoadException>(() => TakeStructArrayExpClassByVal(c14, ARRAY_SIZE)); } static int Main(string[] args) { try { RunTest1("RunTest 1 : Marshal Array In Sequential Struct As LPArray. "); RunTest2("RunTest 2 : Marshal Array In Sequential Class As LPArray. "); if (OperatingSystem.IsWindows()) { RunTest3("RunTest 3 : Marshal Array In Explicit Struct As LPArray. "); } RunTest4("RunTest 4 : Marshal Array In Explicit Class As LPArray. "); Console.WriteLine("\nTest PASS."); return 100; } catch (Exception e) { Console.WriteLine($"\nTest FAIL: {e}"); return 101; } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/CodeGenBringUpTests/LocallocCnstB5001_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="LocallocCnstB5001.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="LocallocCnstB5001.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/Loader/classloader/generics/Instantiation/Recursion/GenTypeItself.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GenTypeItself.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GenTypeItself.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.ServiceModel.Syndication/tests/System/ServiceModel/Syndication/SyndicationItemTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Runtime.Serialization; using System.Xml; using System.Xml.Linq; using Xunit; namespace System.ServiceModel.Syndication.Tests { public class SyndicationItemTests { [Fact] public void Ctor_Default() { var item = new SyndicationItem(); Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); Assert.Null(item.Content); Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Null(item.Id); Assert.Equal(default, item.LastUpdatedTime); Assert.Empty(item.Links); Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); Assert.Null(item.Title); } public static IEnumerable<object[]> Ctor_String_String_Uri_TestData() { yield return new object[] { null, null, null }; yield return new object[] { "", "", new Uri("http://microsoft.com") }; yield return new object[] { "title", "content", new Uri("/relative", UriKind.Relative) }; } [Theory] [MemberData(nameof(Ctor_String_String_Uri_TestData))] public void Ctor_String_String_Uri(string title, string content, Uri itemAlternateLink) { var item = new SyndicationItem(title, content, itemAlternateLink); Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); if (content == null) { Assert.Null(item.Content); } else { TextSyndicationContent textContent = Assert.IsType<TextSyndicationContent>(item.Content); Assert.Empty(textContent.AttributeExtensions); Assert.Equal(content, textContent.Text); Assert.Equal("text", textContent.Type); } Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Null(item.Id); Assert.Equal(default, item.LastUpdatedTime); if (itemAlternateLink == null) { Assert.Empty(item.Links); } else { SyndicationLink link = Assert.Single(item.Links); Assert.Empty(link.AttributeExtensions); Assert.Null(link.BaseUri); Assert.Empty(link.ElementExtensions); Assert.Equal(0, link.Length); Assert.Null(link.MediaType); Assert.Equal("alternate", link.RelationshipType); Assert.Null(link.Title); Assert.Equal(itemAlternateLink, link.Uri); } Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); if (title == null) { Assert.Null(item.Title); } else { Assert.Empty(item.Title.AttributeExtensions); Assert.Equal(title, item.Title.Text); Assert.Equal("text", item.Title.Type); } } public static IEnumerable<object[]> Ctor_String_String_Uri_String_DateTimeOffset_TestData() { yield return new object[] { null, null, null, null, default(DateTimeOffset) }; yield return new object[] { "", "", new Uri("http://microsoft.com"), "", DateTimeOffset.Now }; yield return new object[] { "title", "content", new Uri("/relative", UriKind.Relative), "id", DateTimeOffset.Now.AddDays(2) }; } [Theory] [MemberData(nameof(Ctor_String_String_Uri_String_DateTimeOffset_TestData))] public void Ctor_String_String_Uri_String_DateTimeOffset(string title, string content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime) { var item = new SyndicationItem(title, content, itemAlternateLink, id, lastUpdatedTime); Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); if (content == null) { Assert.Null(item.Content); } else { TextSyndicationContent textContent = Assert.IsType<TextSyndicationContent>(item.Content); Assert.Empty(textContent.AttributeExtensions); Assert.Equal(content, textContent.Text); Assert.Equal("text", textContent.Type); } Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Equal(id, item.Id); Assert.Equal(lastUpdatedTime, item.LastUpdatedTime); if (itemAlternateLink == null) { Assert.Empty(item.Links); } else { SyndicationLink link = Assert.Single(item.Links); Assert.Empty(link.AttributeExtensions); Assert.Null(link.BaseUri); Assert.Empty(link.ElementExtensions); Assert.Equal(0, link.Length); Assert.Null(link.MediaType); Assert.Equal("alternate", link.RelationshipType); Assert.Null(link.Title); Assert.Equal(itemAlternateLink, link.Uri); } Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); if (title == null) { Assert.Null(item.Title); } else { Assert.Empty(item.Title.AttributeExtensions); Assert.Equal(title, item.Title.Text); Assert.Equal("text", item.Title.Type); } } public static IEnumerable<object[]> Ctor_String_SyndicationContent_Uri_String_DateTimeOffset_TestData() { yield return new object[] { null, null, null, null, default(DateTimeOffset) }; yield return new object[] { "", new TextSyndicationContent("text"), new Uri("http://microsoft.com"), "", DateTimeOffset.Now }; yield return new object[] { "title", new TextSyndicationContent("text", TextSyndicationContentKind.XHtml), new Uri("/relative", UriKind.Relative), "id", DateTimeOffset.Now.AddDays(2) }; } [Theory] [MemberData(nameof(Ctor_String_SyndicationContent_Uri_String_DateTimeOffset_TestData))] public void Ctor_String_SyndicationContent_Uri_String_DateTimeOffset(string title, SyndicationContent content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime) { var item = new SyndicationItem(title, content, itemAlternateLink, id, lastUpdatedTime); Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); Assert.Equal(content, item.Content); Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Equal(id, item.Id); Assert.Equal(lastUpdatedTime, item.LastUpdatedTime); if (itemAlternateLink == null) { Assert.Empty(item.Links); } else { SyndicationLink link = Assert.Single(item.Links); Assert.Empty(link.AttributeExtensions); Assert.Null(link.BaseUri); Assert.Empty(link.ElementExtensions); Assert.Equal(0, link.Length); Assert.Null(link.MediaType); Assert.Equal("alternate", link.RelationshipType); Assert.Null(link.Title); Assert.Equal(itemAlternateLink, link.Uri); } Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); if (title == null) { Assert.Null(item.Title); } else { Assert.Empty(item.Title.AttributeExtensions); Assert.Equal(title, item.Title.Text); Assert.Equal("text", item.Title.Type); } } [Fact] public void Ctor_SyndicationItem_Full() { var original = new SyndicationItem("title", new TextSyndicationContent("content", TextSyndicationContentKind.Html), new Uri("http://microsoft.com"), "id", DateTimeOffset.MinValue.AddTicks(10)); original.AttributeExtensions.Add(new XmlQualifiedName("name"), "value"); original.Authors.Add(new SyndicationPerson("email", "author", "uri")); original.BaseUri = new Uri("http://category_baseuri.com"); original.Categories.Add(new SyndicationCategory("category")); original.Contributors.Add(new SyndicationPerson("name", "contributor", "uri")); original.Copyright = new TextSyndicationContent("copyright", TextSyndicationContentKind.Plaintext); original.ElementExtensions.Add(new ExtensionObject { Value = 10 }); original.PublishDate = DateTimeOffset.MinValue.AddTicks(11); original.SourceFeed = new SyndicationFeed("title", "description", new Uri("http://microsoft.com")); original.Summary = new TextSyndicationContent("summary", TextSyndicationContentKind.Html); var clone = new SyndicationItemSubclass(original); Assert.NotSame(clone.AttributeExtensions, original.AttributeExtensions); Assert.Equal(1, clone.AttributeExtensions.Count); Assert.Equal("value", clone.AttributeExtensions[new XmlQualifiedName("name")]); Assert.NotSame(clone.Authors, original.Authors); Assert.Equal(1, clone.Authors.Count); Assert.NotSame(original.Authors[0], clone.Authors[0]); Assert.Equal("author", clone.Authors[0].Name); Assert.Equal(new Uri("http://category_baseuri.com"), original.BaseUri); Assert.NotSame(clone.Categories, original.Categories); Assert.Equal(1, clone.Categories.Count); Assert.NotSame(original.Categories[0], clone.Categories[0]); Assert.Equal("category", clone.Categories[0].Name); Assert.NotSame(clone.Content, original.Content); Assert.Equal("content", Assert.IsType<TextSyndicationContent>(clone.Content).Text); Assert.NotSame(clone.Contributors, original.Contributors); Assert.Equal(1, clone.Contributors.Count); Assert.NotSame(original.Contributors[0], clone.Contributors[0]); Assert.Equal("contributor", clone.Contributors[0].Name); Assert.NotSame(clone.Copyright, original.Copyright); Assert.Equal("copyright", clone.Copyright.Text); Assert.NotSame(clone.ElementExtensions, original.ElementExtensions); Assert.Equal(1, clone.ElementExtensions.Count); Assert.Equal(10, clone.ElementExtensions[0].GetObject<ExtensionObject>().Value); Assert.Equal("id", original.Id); Assert.Equal(DateTimeOffset.MinValue.AddTicks(10), original.LastUpdatedTime); Assert.NotSame(clone.Links, original.Links); Assert.Equal(1, clone.Links.Count); Assert.NotSame(original.Links[0], clone.Links[0]); Assert.Equal(new Uri("http://microsoft.com"), clone.Links[0].Uri); Assert.Equal(DateTimeOffset.MinValue.AddTicks(11), original.PublishDate); Assert.NotSame(clone.SourceFeed, original.SourceFeed); Assert.Equal("title", clone.SourceFeed.Title.Text); Assert.NotSame(clone.Summary, original.Summary); Assert.Equal("summary", clone.Summary.Text); Assert.NotSame(clone.Title, original.Title); Assert.Equal("title", clone.Title.Text); } [Fact] public void Ctor_SyndicationItem_Empty() { var original = new SyndicationItem(); var clone = new SyndicationItemSubclass(original); Assert.Empty(clone.AttributeExtensions); Assert.Empty(clone.Authors); Assert.Null(clone.BaseUri); Assert.Empty(clone.Categories); Assert.Null(clone.Content); Assert.Null(clone.Copyright); Assert.Empty(clone.ElementExtensions); Assert.Null(clone.Id); Assert.Equal(default, clone.LastUpdatedTime); Assert.Empty(clone.Links); Assert.Equal(default, clone.PublishDate); Assert.Null(clone.SourceFeed); Assert.Null(clone.Summary); Assert.Null(clone.Title); } [Fact] public void Ctor_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => new SyndicationItemSubclass(null)); } [Fact] public void AddPermalink_ValidPermalink_AddsToLinks() { var permalink = new Uri("http://microsoft.com"); var item = new SyndicationItem(); item.AddPermalink(permalink); SyndicationLink link = Assert.Single(item.Links); Assert.Empty(link.AttributeExtensions); Assert.Null(link.BaseUri); Assert.Empty(link.ElementExtensions); Assert.Equal(0, link.Length); Assert.Null(link.MediaType); Assert.Equal("alternate", link.RelationshipType); Assert.Null(link.Title); Assert.Equal(permalink, link.Uri); } [Fact] public void AddPermalink_NullPermalink_ThrowsArgumentNullException() { var item = new SyndicationItem(); AssertExtensions.Throws<ArgumentNullException>("permalink", () => item.AddPermalink(null)); } [Fact] public void AddPermalink_RelativePermalink_ThrowsInvalidOperationException() { var permalink = new Uri("/microsoft", UriKind.Relative); var item = new SyndicationItem(); Assert.Throws<InvalidOperationException>(() => item.AddPermalink(permalink)); } [Fact] public void Load_NullReader_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("reader", () => SyndicationItem.Load(null)); AssertExtensions.Throws<ArgumentNullException>("reader", () => SyndicationItem.Load<SyndicationItem>(null)); } [Fact] public void Clone_Full_ReturnsExpected() { var original = new SyndicationItem("title", new TextSyndicationContent("content", TextSyndicationContentKind.Html), new Uri("http://microsoft.com"), "id", DateTimeOffset.MinValue.AddTicks(10)); original.AttributeExtensions.Add(new XmlQualifiedName("name"), "value"); original.Authors.Add(new SyndicationPerson("email", "author", "uri")); original.BaseUri = new Uri("http://category_baseuri.com"); original.Categories.Add(new SyndicationCategory("category")); original.Contributors.Add(new SyndicationPerson("name", "contributor", "uri")); original.Copyright = new TextSyndicationContent("copyright", TextSyndicationContentKind.Plaintext); original.ElementExtensions.Add(new ExtensionObject { Value = 10 }); original.PublishDate = DateTimeOffset.MinValue.AddTicks(11); original.SourceFeed = new SyndicationFeed("title", "description", new Uri("http://microsoft.com")); original.Summary = new TextSyndicationContent("summary", TextSyndicationContentKind.Html); SyndicationItem clone = original.Clone(); Assert.NotSame(clone.AttributeExtensions, original.AttributeExtensions); Assert.Equal(1, clone.AttributeExtensions.Count); Assert.Equal("value", clone.AttributeExtensions[new XmlQualifiedName("name")]); Assert.NotSame(clone.Authors, original.Authors); Assert.Equal(1, clone.Authors.Count); Assert.NotSame(original.Authors[0], clone.Authors[0]); Assert.Equal("author", clone.Authors[0].Name); Assert.Equal(new Uri("http://category_baseuri.com"), original.BaseUri); Assert.NotSame(clone.Categories, original.Categories); Assert.Equal(1, clone.Categories.Count); Assert.NotSame(original.Categories[0], clone.Categories[0]); Assert.Equal("category", clone.Categories[0].Name); Assert.NotSame(clone.Content, original.Content); Assert.Equal("content", Assert.IsType<TextSyndicationContent>(clone.Content).Text); Assert.NotSame(clone.Contributors, original.Contributors); Assert.Equal(1, clone.Contributors.Count); Assert.NotSame(original.Contributors[0], clone.Contributors[0]); Assert.Equal("contributor", clone.Contributors[0].Name); Assert.NotSame(clone.Copyright, original.Copyright); Assert.Equal("copyright", clone.Copyright.Text); Assert.NotSame(clone.ElementExtensions, original.ElementExtensions); Assert.Equal(1, clone.ElementExtensions.Count); Assert.Equal(10, clone.ElementExtensions[0].GetObject<ExtensionObject>().Value); Assert.Equal("id", original.Id); Assert.Equal(DateTimeOffset.MinValue.AddTicks(10), original.LastUpdatedTime); Assert.NotSame(clone.Links, original.Links); Assert.Equal(1, clone.Links.Count); Assert.NotSame(original.Links[0], clone.Links[0]); Assert.Equal(new Uri("http://microsoft.com"), clone.Links[0].Uri); Assert.Equal(DateTimeOffset.MinValue.AddTicks(11), original.PublishDate); Assert.NotSame(clone.SourceFeed, original.SourceFeed); Assert.Equal("title", clone.SourceFeed.Title.Text); Assert.NotSame(clone.Summary, original.Summary); Assert.Equal("summary", clone.Summary.Text); Assert.NotSame(clone.Title, original.Title); Assert.Equal("title", clone.Title.Text); } [Fact] public void Clone_Empty_ReturnsExpected() { var original = new SyndicationItem(); SyndicationItem clone = original.Clone(); Assert.Empty(clone.AttributeExtensions); Assert.Empty(clone.Authors); Assert.Null(clone.BaseUri); Assert.Empty(clone.Categories); Assert.Null(clone.Content); Assert.Null(clone.Copyright); Assert.Empty(clone.ElementExtensions); Assert.Null(clone.Id); Assert.Equal(default, clone.LastUpdatedTime); Assert.Empty(clone.Links); Assert.Equal(default, clone.PublishDate); Assert.Null(clone.SourceFeed); Assert.Null(clone.Summary); Assert.Null(clone.Title); } [Fact] public void GetAtom10Formatter_Invoke_ReturnsExpected() { var item = new SyndicationItem(); Atom10ItemFormatter formatter = Assert.IsType<Atom10ItemFormatter>(item.GetAtom10Formatter()); Assert.Same(item, formatter.Item); Assert.True(formatter.PreserveAttributeExtensions); Assert.True(formatter.PreserveElementExtensions); Assert.Equal("Atom10", formatter.Version); } [Theory] [InlineData(true)] [InlineData(false)] public void GetRss20Formatter_Invoke_ReturnsExpected(bool serializeExtensionsAsAtom) { var item = new SyndicationItem(); Rss20ItemFormatter formatter = Assert.IsType<Rss20ItemFormatter>(item.GetRss20Formatter(serializeExtensionsAsAtom)); Assert.Same(item, formatter.Item); Assert.True(formatter.PreserveAttributeExtensions); Assert.True(formatter.PreserveElementExtensions); Assert.Equal(serializeExtensionsAsAtom, formatter.SerializeExtensionsAsAtom); Assert.Equal("Rss20", formatter.Version); } [Fact] public void CreateCategory_Invoke_ReturnsExpected() { var item = new SyndicationItemSubclass(); SyndicationCategory category = item.CreateCategoryEntryPoint(); Assert.Empty(category.AttributeExtensions); Assert.Empty(category.ElementExtensions); Assert.Null(category.Name); Assert.Null(category.Scheme); Assert.Null(category.Label); } [Fact] public void CreateLink_Invoke_ReturnsExpected() { var item = new SyndicationItemSubclass(); SyndicationLink link = item.CreateLinkEntryPoint(); Assert.Empty(link.AttributeExtensions); Assert.Null(link.BaseUri); Assert.Empty(link.ElementExtensions); Assert.Equal(0, link.Length); Assert.Null(link.MediaType); Assert.Null(link.RelationshipType); Assert.Null(link.Title); Assert.Null(link.Uri); } [Fact] public void CreatePerson_Invoke_ReturnsExpected() { var item = new SyndicationItemSubclass(); SyndicationPerson person = item.CreatePersonEntryPoint(); Assert.Empty(person.AttributeExtensions); Assert.Empty(person.ElementExtensions); Assert.Null(person.Email); Assert.Null(person.Name); Assert.Null(person.Uri); } [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 item = new SyndicationItemSubclass(); Assert.False(item.TryParseAttributeEntryPoint(name, ns, value, version)); } public static IEnumerable<object[]> TryParseContent_TestData() { yield return new object[] { null, null, null }; yield return new object[] { new XElement("name").CreateReader(), "", "" }; yield return new object[] { new XElement("name").CreateReader(), "contentType", "version" }; } [Theory] [MemberData(nameof(TryParseContent_TestData))] public void TryParseContent_Invoke_ReturnsFalse(XmlReader reader, string contentType, string version) { var item = new SyndicationItemSubclass(); Assert.False(item.TryParseContentEntryPoint(reader, contentType, version, out SyndicationContent content)); Assert.Null(content); } 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 item = new SyndicationItemSubclass(); Assert.False(item.TryParseElementEntryPoint(reader, version)); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("version")] public void WriteAttributeExtensions_Invoke_ReturnsExpected(string version) { var item = new SyndicationItemSubclass(); CompareHelper.AssertEqualWriteOutput("", writer => item.WriteAttributeExtensionsEntryPoint(writer, version)); item.AttributeExtensions.Add(new XmlQualifiedName("name1"), "value"); item.AttributeExtensions.Add(new XmlQualifiedName("name2", "namespace"), ""); item.AttributeExtensions.Add(new XmlQualifiedName("name3"), null); CompareHelper.AssertEqualWriteOutput(@"name1=""value"" d0p1:name2="""" name3=""""", writer => item.WriteAttributeExtensionsEntryPoint(writer, "version")); } [Fact] public void WriteAttributeExtensions_NullWriter_ThrowsArgumentNullException() { var item = new SyndicationItemSubclass(); AssertExtensions.Throws<ArgumentNullException>("writer", () => item.WriteAttributeExtensionsEntryPoint(null, "version")); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("version")] public void WriteElementExtensions_Invoke_ReturnsExpected(string version) { var item = new SyndicationItemSubclass(); CompareHelper.AssertEqualWriteOutput("", writer => item.WriteElementExtensionsEntryPoint(writer, version)); item.ElementExtensions.Add(new ExtensionObject { Value = 10 }); item.ElementExtensions.Add(new ExtensionObject { Value = 11 }); CompareHelper.AssertEqualWriteOutput( @"<SyndicationItemTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </SyndicationItemTests.ExtensionObject> <SyndicationItemTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>11</Value> </SyndicationItemTests.ExtensionObject>", writer => item.WriteElementExtensionsEntryPoint(writer, version)); } [Fact] public void WriteElementExtensions_NullWriter_ThrowsArgumentNullException() { var item = new SyndicationItemSubclass(); AssertExtensions.Throws<ArgumentNullException>("writer", () => item.WriteElementExtensionsEntryPoint(null, "version")); } private class SyndicationItemSubclass : SyndicationItem { public SyndicationItemSubclass() : base() { } public SyndicationItemSubclass(SyndicationItem source) : base(source) { } public SyndicationCategory CreateCategoryEntryPoint() => CreateCategory(); public SyndicationLink CreateLinkEntryPoint() => CreateLink(); public SyndicationPerson CreatePersonEntryPoint() => CreatePerson(); public bool TryParseAttributeEntryPoint(string name, string ns, string value, string version) => TryParseAttribute(name, ns, value, version); public bool TryParseContentEntryPoint(XmlReader reader, string contentType, string version, out SyndicationContent content) { return TryParseContent(reader, contentType, version, out content); } 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] private 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.Runtime.Serialization; using System.Xml; using System.Xml.Linq; using Xunit; namespace System.ServiceModel.Syndication.Tests { public class SyndicationItemTests { [Fact] public void Ctor_Default() { var item = new SyndicationItem(); Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); Assert.Null(item.Content); Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Null(item.Id); Assert.Equal(default, item.LastUpdatedTime); Assert.Empty(item.Links); Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); Assert.Null(item.Title); } public static IEnumerable<object[]> Ctor_String_String_Uri_TestData() { yield return new object[] { null, null, null }; yield return new object[] { "", "", new Uri("http://microsoft.com") }; yield return new object[] { "title", "content", new Uri("/relative", UriKind.Relative) }; } [Theory] [MemberData(nameof(Ctor_String_String_Uri_TestData))] public void Ctor_String_String_Uri(string title, string content, Uri itemAlternateLink) { var item = new SyndicationItem(title, content, itemAlternateLink); Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); if (content == null) { Assert.Null(item.Content); } else { TextSyndicationContent textContent = Assert.IsType<TextSyndicationContent>(item.Content); Assert.Empty(textContent.AttributeExtensions); Assert.Equal(content, textContent.Text); Assert.Equal("text", textContent.Type); } Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Null(item.Id); Assert.Equal(default, item.LastUpdatedTime); if (itemAlternateLink == null) { Assert.Empty(item.Links); } else { SyndicationLink link = Assert.Single(item.Links); Assert.Empty(link.AttributeExtensions); Assert.Null(link.BaseUri); Assert.Empty(link.ElementExtensions); Assert.Equal(0, link.Length); Assert.Null(link.MediaType); Assert.Equal("alternate", link.RelationshipType); Assert.Null(link.Title); Assert.Equal(itemAlternateLink, link.Uri); } Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); if (title == null) { Assert.Null(item.Title); } else { Assert.Empty(item.Title.AttributeExtensions); Assert.Equal(title, item.Title.Text); Assert.Equal("text", item.Title.Type); } } public static IEnumerable<object[]> Ctor_String_String_Uri_String_DateTimeOffset_TestData() { yield return new object[] { null, null, null, null, default(DateTimeOffset) }; yield return new object[] { "", "", new Uri("http://microsoft.com"), "", DateTimeOffset.Now }; yield return new object[] { "title", "content", new Uri("/relative", UriKind.Relative), "id", DateTimeOffset.Now.AddDays(2) }; } [Theory] [MemberData(nameof(Ctor_String_String_Uri_String_DateTimeOffset_TestData))] public void Ctor_String_String_Uri_String_DateTimeOffset(string title, string content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime) { var item = new SyndicationItem(title, content, itemAlternateLink, id, lastUpdatedTime); Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); if (content == null) { Assert.Null(item.Content); } else { TextSyndicationContent textContent = Assert.IsType<TextSyndicationContent>(item.Content); Assert.Empty(textContent.AttributeExtensions); Assert.Equal(content, textContent.Text); Assert.Equal("text", textContent.Type); } Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Equal(id, item.Id); Assert.Equal(lastUpdatedTime, item.LastUpdatedTime); if (itemAlternateLink == null) { Assert.Empty(item.Links); } else { SyndicationLink link = Assert.Single(item.Links); Assert.Empty(link.AttributeExtensions); Assert.Null(link.BaseUri); Assert.Empty(link.ElementExtensions); Assert.Equal(0, link.Length); Assert.Null(link.MediaType); Assert.Equal("alternate", link.RelationshipType); Assert.Null(link.Title); Assert.Equal(itemAlternateLink, link.Uri); } Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); if (title == null) { Assert.Null(item.Title); } else { Assert.Empty(item.Title.AttributeExtensions); Assert.Equal(title, item.Title.Text); Assert.Equal("text", item.Title.Type); } } public static IEnumerable<object[]> Ctor_String_SyndicationContent_Uri_String_DateTimeOffset_TestData() { yield return new object[] { null, null, null, null, default(DateTimeOffset) }; yield return new object[] { "", new TextSyndicationContent("text"), new Uri("http://microsoft.com"), "", DateTimeOffset.Now }; yield return new object[] { "title", new TextSyndicationContent("text", TextSyndicationContentKind.XHtml), new Uri("/relative", UriKind.Relative), "id", DateTimeOffset.Now.AddDays(2) }; } [Theory] [MemberData(nameof(Ctor_String_SyndicationContent_Uri_String_DateTimeOffset_TestData))] public void Ctor_String_SyndicationContent_Uri_String_DateTimeOffset(string title, SyndicationContent content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime) { var item = new SyndicationItem(title, content, itemAlternateLink, id, lastUpdatedTime); Assert.Empty(item.AttributeExtensions); Assert.Empty(item.Authors); Assert.Null(item.BaseUri); Assert.Empty(item.Categories); Assert.Equal(content, item.Content); Assert.Null(item.Copyright); Assert.Empty(item.ElementExtensions); Assert.Equal(id, item.Id); Assert.Equal(lastUpdatedTime, item.LastUpdatedTime); if (itemAlternateLink == null) { Assert.Empty(item.Links); } else { SyndicationLink link = Assert.Single(item.Links); Assert.Empty(link.AttributeExtensions); Assert.Null(link.BaseUri); Assert.Empty(link.ElementExtensions); Assert.Equal(0, link.Length); Assert.Null(link.MediaType); Assert.Equal("alternate", link.RelationshipType); Assert.Null(link.Title); Assert.Equal(itemAlternateLink, link.Uri); } Assert.Equal(default, item.PublishDate); Assert.Null(item.SourceFeed); Assert.Null(item.Summary); if (title == null) { Assert.Null(item.Title); } else { Assert.Empty(item.Title.AttributeExtensions); Assert.Equal(title, item.Title.Text); Assert.Equal("text", item.Title.Type); } } [Fact] public void Ctor_SyndicationItem_Full() { var original = new SyndicationItem("title", new TextSyndicationContent("content", TextSyndicationContentKind.Html), new Uri("http://microsoft.com"), "id", DateTimeOffset.MinValue.AddTicks(10)); original.AttributeExtensions.Add(new XmlQualifiedName("name"), "value"); original.Authors.Add(new SyndicationPerson("email", "author", "uri")); original.BaseUri = new Uri("http://category_baseuri.com"); original.Categories.Add(new SyndicationCategory("category")); original.Contributors.Add(new SyndicationPerson("name", "contributor", "uri")); original.Copyright = new TextSyndicationContent("copyright", TextSyndicationContentKind.Plaintext); original.ElementExtensions.Add(new ExtensionObject { Value = 10 }); original.PublishDate = DateTimeOffset.MinValue.AddTicks(11); original.SourceFeed = new SyndicationFeed("title", "description", new Uri("http://microsoft.com")); original.Summary = new TextSyndicationContent("summary", TextSyndicationContentKind.Html); var clone = new SyndicationItemSubclass(original); Assert.NotSame(clone.AttributeExtensions, original.AttributeExtensions); Assert.Equal(1, clone.AttributeExtensions.Count); Assert.Equal("value", clone.AttributeExtensions[new XmlQualifiedName("name")]); Assert.NotSame(clone.Authors, original.Authors); Assert.Equal(1, clone.Authors.Count); Assert.NotSame(original.Authors[0], clone.Authors[0]); Assert.Equal("author", clone.Authors[0].Name); Assert.Equal(new Uri("http://category_baseuri.com"), original.BaseUri); Assert.NotSame(clone.Categories, original.Categories); Assert.Equal(1, clone.Categories.Count); Assert.NotSame(original.Categories[0], clone.Categories[0]); Assert.Equal("category", clone.Categories[0].Name); Assert.NotSame(clone.Content, original.Content); Assert.Equal("content", Assert.IsType<TextSyndicationContent>(clone.Content).Text); Assert.NotSame(clone.Contributors, original.Contributors); Assert.Equal(1, clone.Contributors.Count); Assert.NotSame(original.Contributors[0], clone.Contributors[0]); Assert.Equal("contributor", clone.Contributors[0].Name); Assert.NotSame(clone.Copyright, original.Copyright); Assert.Equal("copyright", clone.Copyright.Text); Assert.NotSame(clone.ElementExtensions, original.ElementExtensions); Assert.Equal(1, clone.ElementExtensions.Count); Assert.Equal(10, clone.ElementExtensions[0].GetObject<ExtensionObject>().Value); Assert.Equal("id", original.Id); Assert.Equal(DateTimeOffset.MinValue.AddTicks(10), original.LastUpdatedTime); Assert.NotSame(clone.Links, original.Links); Assert.Equal(1, clone.Links.Count); Assert.NotSame(original.Links[0], clone.Links[0]); Assert.Equal(new Uri("http://microsoft.com"), clone.Links[0].Uri); Assert.Equal(DateTimeOffset.MinValue.AddTicks(11), original.PublishDate); Assert.NotSame(clone.SourceFeed, original.SourceFeed); Assert.Equal("title", clone.SourceFeed.Title.Text); Assert.NotSame(clone.Summary, original.Summary); Assert.Equal("summary", clone.Summary.Text); Assert.NotSame(clone.Title, original.Title); Assert.Equal("title", clone.Title.Text); } [Fact] public void Ctor_SyndicationItem_Empty() { var original = new SyndicationItem(); var clone = new SyndicationItemSubclass(original); Assert.Empty(clone.AttributeExtensions); Assert.Empty(clone.Authors); Assert.Null(clone.BaseUri); Assert.Empty(clone.Categories); Assert.Null(clone.Content); Assert.Null(clone.Copyright); Assert.Empty(clone.ElementExtensions); Assert.Null(clone.Id); Assert.Equal(default, clone.LastUpdatedTime); Assert.Empty(clone.Links); Assert.Equal(default, clone.PublishDate); Assert.Null(clone.SourceFeed); Assert.Null(clone.Summary); Assert.Null(clone.Title); } [Fact] public void Ctor_NullSource_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => new SyndicationItemSubclass(null)); } [Fact] public void AddPermalink_ValidPermalink_AddsToLinks() { var permalink = new Uri("http://microsoft.com"); var item = new SyndicationItem(); item.AddPermalink(permalink); SyndicationLink link = Assert.Single(item.Links); Assert.Empty(link.AttributeExtensions); Assert.Null(link.BaseUri); Assert.Empty(link.ElementExtensions); Assert.Equal(0, link.Length); Assert.Null(link.MediaType); Assert.Equal("alternate", link.RelationshipType); Assert.Null(link.Title); Assert.Equal(permalink, link.Uri); } [Fact] public void AddPermalink_NullPermalink_ThrowsArgumentNullException() { var item = new SyndicationItem(); AssertExtensions.Throws<ArgumentNullException>("permalink", () => item.AddPermalink(null)); } [Fact] public void AddPermalink_RelativePermalink_ThrowsInvalidOperationException() { var permalink = new Uri("/microsoft", UriKind.Relative); var item = new SyndicationItem(); Assert.Throws<InvalidOperationException>(() => item.AddPermalink(permalink)); } [Fact] public void Load_NullReader_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("reader", () => SyndicationItem.Load(null)); AssertExtensions.Throws<ArgumentNullException>("reader", () => SyndicationItem.Load<SyndicationItem>(null)); } [Fact] public void Clone_Full_ReturnsExpected() { var original = new SyndicationItem("title", new TextSyndicationContent("content", TextSyndicationContentKind.Html), new Uri("http://microsoft.com"), "id", DateTimeOffset.MinValue.AddTicks(10)); original.AttributeExtensions.Add(new XmlQualifiedName("name"), "value"); original.Authors.Add(new SyndicationPerson("email", "author", "uri")); original.BaseUri = new Uri("http://category_baseuri.com"); original.Categories.Add(new SyndicationCategory("category")); original.Contributors.Add(new SyndicationPerson("name", "contributor", "uri")); original.Copyright = new TextSyndicationContent("copyright", TextSyndicationContentKind.Plaintext); original.ElementExtensions.Add(new ExtensionObject { Value = 10 }); original.PublishDate = DateTimeOffset.MinValue.AddTicks(11); original.SourceFeed = new SyndicationFeed("title", "description", new Uri("http://microsoft.com")); original.Summary = new TextSyndicationContent("summary", TextSyndicationContentKind.Html); SyndicationItem clone = original.Clone(); Assert.NotSame(clone.AttributeExtensions, original.AttributeExtensions); Assert.Equal(1, clone.AttributeExtensions.Count); Assert.Equal("value", clone.AttributeExtensions[new XmlQualifiedName("name")]); Assert.NotSame(clone.Authors, original.Authors); Assert.Equal(1, clone.Authors.Count); Assert.NotSame(original.Authors[0], clone.Authors[0]); Assert.Equal("author", clone.Authors[0].Name); Assert.Equal(new Uri("http://category_baseuri.com"), original.BaseUri); Assert.NotSame(clone.Categories, original.Categories); Assert.Equal(1, clone.Categories.Count); Assert.NotSame(original.Categories[0], clone.Categories[0]); Assert.Equal("category", clone.Categories[0].Name); Assert.NotSame(clone.Content, original.Content); Assert.Equal("content", Assert.IsType<TextSyndicationContent>(clone.Content).Text); Assert.NotSame(clone.Contributors, original.Contributors); Assert.Equal(1, clone.Contributors.Count); Assert.NotSame(original.Contributors[0], clone.Contributors[0]); Assert.Equal("contributor", clone.Contributors[0].Name); Assert.NotSame(clone.Copyright, original.Copyright); Assert.Equal("copyright", clone.Copyright.Text); Assert.NotSame(clone.ElementExtensions, original.ElementExtensions); Assert.Equal(1, clone.ElementExtensions.Count); Assert.Equal(10, clone.ElementExtensions[0].GetObject<ExtensionObject>().Value); Assert.Equal("id", original.Id); Assert.Equal(DateTimeOffset.MinValue.AddTicks(10), original.LastUpdatedTime); Assert.NotSame(clone.Links, original.Links); Assert.Equal(1, clone.Links.Count); Assert.NotSame(original.Links[0], clone.Links[0]); Assert.Equal(new Uri("http://microsoft.com"), clone.Links[0].Uri); Assert.Equal(DateTimeOffset.MinValue.AddTicks(11), original.PublishDate); Assert.NotSame(clone.SourceFeed, original.SourceFeed); Assert.Equal("title", clone.SourceFeed.Title.Text); Assert.NotSame(clone.Summary, original.Summary); Assert.Equal("summary", clone.Summary.Text); Assert.NotSame(clone.Title, original.Title); Assert.Equal("title", clone.Title.Text); } [Fact] public void Clone_Empty_ReturnsExpected() { var original = new SyndicationItem(); SyndicationItem clone = original.Clone(); Assert.Empty(clone.AttributeExtensions); Assert.Empty(clone.Authors); Assert.Null(clone.BaseUri); Assert.Empty(clone.Categories); Assert.Null(clone.Content); Assert.Null(clone.Copyright); Assert.Empty(clone.ElementExtensions); Assert.Null(clone.Id); Assert.Equal(default, clone.LastUpdatedTime); Assert.Empty(clone.Links); Assert.Equal(default, clone.PublishDate); Assert.Null(clone.SourceFeed); Assert.Null(clone.Summary); Assert.Null(clone.Title); } [Fact] public void GetAtom10Formatter_Invoke_ReturnsExpected() { var item = new SyndicationItem(); Atom10ItemFormatter formatter = Assert.IsType<Atom10ItemFormatter>(item.GetAtom10Formatter()); Assert.Same(item, formatter.Item); Assert.True(formatter.PreserveAttributeExtensions); Assert.True(formatter.PreserveElementExtensions); Assert.Equal("Atom10", formatter.Version); } [Theory] [InlineData(true)] [InlineData(false)] public void GetRss20Formatter_Invoke_ReturnsExpected(bool serializeExtensionsAsAtom) { var item = new SyndicationItem(); Rss20ItemFormatter formatter = Assert.IsType<Rss20ItemFormatter>(item.GetRss20Formatter(serializeExtensionsAsAtom)); Assert.Same(item, formatter.Item); Assert.True(formatter.PreserveAttributeExtensions); Assert.True(formatter.PreserveElementExtensions); Assert.Equal(serializeExtensionsAsAtom, formatter.SerializeExtensionsAsAtom); Assert.Equal("Rss20", formatter.Version); } [Fact] public void CreateCategory_Invoke_ReturnsExpected() { var item = new SyndicationItemSubclass(); SyndicationCategory category = item.CreateCategoryEntryPoint(); Assert.Empty(category.AttributeExtensions); Assert.Empty(category.ElementExtensions); Assert.Null(category.Name); Assert.Null(category.Scheme); Assert.Null(category.Label); } [Fact] public void CreateLink_Invoke_ReturnsExpected() { var item = new SyndicationItemSubclass(); SyndicationLink link = item.CreateLinkEntryPoint(); Assert.Empty(link.AttributeExtensions); Assert.Null(link.BaseUri); Assert.Empty(link.ElementExtensions); Assert.Equal(0, link.Length); Assert.Null(link.MediaType); Assert.Null(link.RelationshipType); Assert.Null(link.Title); Assert.Null(link.Uri); } [Fact] public void CreatePerson_Invoke_ReturnsExpected() { var item = new SyndicationItemSubclass(); SyndicationPerson person = item.CreatePersonEntryPoint(); Assert.Empty(person.AttributeExtensions); Assert.Empty(person.ElementExtensions); Assert.Null(person.Email); Assert.Null(person.Name); Assert.Null(person.Uri); } [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 item = new SyndicationItemSubclass(); Assert.False(item.TryParseAttributeEntryPoint(name, ns, value, version)); } public static IEnumerable<object[]> TryParseContent_TestData() { yield return new object[] { null, null, null }; yield return new object[] { new XElement("name").CreateReader(), "", "" }; yield return new object[] { new XElement("name").CreateReader(), "contentType", "version" }; } [Theory] [MemberData(nameof(TryParseContent_TestData))] public void TryParseContent_Invoke_ReturnsFalse(XmlReader reader, string contentType, string version) { var item = new SyndicationItemSubclass(); Assert.False(item.TryParseContentEntryPoint(reader, contentType, version, out SyndicationContent content)); Assert.Null(content); } 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 item = new SyndicationItemSubclass(); Assert.False(item.TryParseElementEntryPoint(reader, version)); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("version")] public void WriteAttributeExtensions_Invoke_ReturnsExpected(string version) { var item = new SyndicationItemSubclass(); CompareHelper.AssertEqualWriteOutput("", writer => item.WriteAttributeExtensionsEntryPoint(writer, version)); item.AttributeExtensions.Add(new XmlQualifiedName("name1"), "value"); item.AttributeExtensions.Add(new XmlQualifiedName("name2", "namespace"), ""); item.AttributeExtensions.Add(new XmlQualifiedName("name3"), null); CompareHelper.AssertEqualWriteOutput(@"name1=""value"" d0p1:name2="""" name3=""""", writer => item.WriteAttributeExtensionsEntryPoint(writer, "version")); } [Fact] public void WriteAttributeExtensions_NullWriter_ThrowsArgumentNullException() { var item = new SyndicationItemSubclass(); AssertExtensions.Throws<ArgumentNullException>("writer", () => item.WriteAttributeExtensionsEntryPoint(null, "version")); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("version")] public void WriteElementExtensions_Invoke_ReturnsExpected(string version) { var item = new SyndicationItemSubclass(); CompareHelper.AssertEqualWriteOutput("", writer => item.WriteElementExtensionsEntryPoint(writer, version)); item.ElementExtensions.Add(new ExtensionObject { Value = 10 }); item.ElementExtensions.Add(new ExtensionObject { Value = 11 }); CompareHelper.AssertEqualWriteOutput( @"<SyndicationItemTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>10</Value> </SyndicationItemTests.ExtensionObject> <SyndicationItemTests.ExtensionObject xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/System.ServiceModel.Syndication.Tests""> <Value>11</Value> </SyndicationItemTests.ExtensionObject>", writer => item.WriteElementExtensionsEntryPoint(writer, version)); } [Fact] public void WriteElementExtensions_NullWriter_ThrowsArgumentNullException() { var item = new SyndicationItemSubclass(); AssertExtensions.Throws<ArgumentNullException>("writer", () => item.WriteElementExtensionsEntryPoint(null, "version")); } private class SyndicationItemSubclass : SyndicationItem { public SyndicationItemSubclass() : base() { } public SyndicationItemSubclass(SyndicationItem source) : base(source) { } public SyndicationCategory CreateCategoryEntryPoint() => CreateCategory(); public SyndicationLink CreateLinkEntryPoint() => CreateLink(); public SyndicationPerson CreatePersonEntryPoint() => CreatePerson(); public bool TryParseAttributeEntryPoint(string name, string ns, string value, string version) => TryParseAttribute(name, ns, value, version); public bool TryParseContentEntryPoint(XmlReader reader, string contentType, string version, out SyndicationContent content) { return TryParseContent(reader, contentType, version, out content); } 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] private class ExtensionObject { [DataMember] public int Value { get; set; } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/jit64/hfa/main/testC/hfa_nd1C_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="hfa_testC.cs" /> <ProjectReference Include="..\dll\common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f64_managed.csproj" /> <CMakeProjectReference Include="..\dll\CMakeLists.txt" /> <ProjectReference Include="..\dll\hfa_nested_f64_common.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="hfa_testC.cs" /> <ProjectReference Include="..\dll\common.csproj" /> <ProjectReference Include="..\dll\hfa_nested_f64_managed.csproj" /> <CMakeProjectReference Include="..\dll\CMakeLists.txt" /> <ProjectReference Include="..\dll\hfa_nested_f64_common.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Directed/coverage/oldtests/33objref_cs_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="33objref.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="33objref.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Security.AccessControl/tests/Ace/Ace.Custom.Tests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.Security.AccessControl.Tests { public class CustomAce_Tests : GenericAce_Tests { private static object[] CustomAce_CreateTestData(int intType, int intFlags, int opaqueLength, int offset) { byte[] opaque = new byte[opaqueLength]; AceType type = (AceType)intType; AceFlags flags = (AceFlags)intFlags; CustomAce ace = new CustomAce(type, flags, opaque); Assert.Equal(type, ace.AceType); Assert.Equal(flags, ace.AceFlags); Assert.Equal(opaque, ace.GetOpaque()); byte[] binaryForm = new byte[ace.BinaryLength + offset]; binaryForm[offset + 0] = (byte)type; binaryForm[offset + 1] = (byte)flags; binaryForm[offset + 2] = (byte)(ace.BinaryLength >> 0); binaryForm[offset + 3] = (byte)(ace.BinaryLength >> 8); opaque.CopyTo(binaryForm, 4 + offset); return new object[] { ace, binaryForm, offset }; } public static IEnumerable<object[]> CustomAce_TestObjects() { yield return CustomAce_CreateTestData(19, 0, 4, 0); yield return CustomAce_CreateTestData(18, 1, 8, 0); yield return CustomAce_CreateTestData(17, 1, 4, 0); } [Fact] public void CustomAce_Constructor_Invalid() { Assert.Throws<ArgumentOutOfRangeException>(() => new CustomAce((AceType)16, (AceFlags)15, new byte[1])); Assert.Throws<ArgumentOutOfRangeException>(() => new CustomAce((AceType)19, (AceFlags)1, new byte[1])); Assert.Throws<ArgumentOutOfRangeException>(() => new CustomAce((AceType)0, (AceFlags)2, new byte[4])); foreach (AceType type in Enum.GetValues(typeof(AceType))) { Assert.Throws<ArgumentOutOfRangeException>(() => new CustomAce(type, (AceFlags)1, new byte[4])); } } [Fact] public void CustomAce_CreateBinaryForm_Invalid() { GenericAce ace = new CustomAce((AceType)19, (AceFlags)0, new byte[4]); AssertExtensions.Throws<ArgumentNullException>("binaryForm", () => CustomAce.CreateFromBinaryForm(null, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => CustomAce.CreateFromBinaryForm(new byte[1], -1)); AssertExtensions.Throws<ArgumentException>("binaryForm", () => CustomAce.CreateFromBinaryForm(new byte[ace.BinaryLength + 1], 2)); AssertExtensions.Throws<ArgumentException>("binaryForm", () => CustomAce.CreateFromBinaryForm(new byte[ace.BinaryLength], 1)); } [Fact] public void CustomAce_GetBinaryForm_Invalid() { GenericAce ace = new CustomAce((AceType)19, (AceFlags)0, new byte[4]); AssertExtensions.Throws<ArgumentNullException>("binaryForm", () => ace.GetBinaryForm(null, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => ace.GetBinaryForm(new byte[1], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("binaryForm", () => ace.GetBinaryForm(new byte[ace.BinaryLength + 1], 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("binaryForm", () => ace.GetBinaryForm(new byte[ace.BinaryLength], 1)); } [Theory] [MemberData(nameof(CustomAce_TestObjects))] public void CustomAce_GetBinaryForm(GenericAce testAce, byte[] expectedBinaryForm, int testOffset) { byte[] resultBinaryForm = new byte[testAce.BinaryLength + testOffset]; testAce.GetBinaryForm(resultBinaryForm, testOffset); GenericAce_VerifyBinaryForms(expectedBinaryForm, resultBinaryForm, testOffset); } [Theory] [MemberData(nameof(CustomAce_TestObjects))] public void CustomAce_CreateFromBinaryForm(GenericAce expectedAce, byte[] testBinaryForm, int testOffset) { GenericAce resultAce = CustomAce.CreateFromBinaryForm(testBinaryForm, testOffset); GenericAce_VerifyAces(expectedAce, resultAce); } } }
// 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.Security.AccessControl.Tests { public class CustomAce_Tests : GenericAce_Tests { private static object[] CustomAce_CreateTestData(int intType, int intFlags, int opaqueLength, int offset) { byte[] opaque = new byte[opaqueLength]; AceType type = (AceType)intType; AceFlags flags = (AceFlags)intFlags; CustomAce ace = new CustomAce(type, flags, opaque); Assert.Equal(type, ace.AceType); Assert.Equal(flags, ace.AceFlags); Assert.Equal(opaque, ace.GetOpaque()); byte[] binaryForm = new byte[ace.BinaryLength + offset]; binaryForm[offset + 0] = (byte)type; binaryForm[offset + 1] = (byte)flags; binaryForm[offset + 2] = (byte)(ace.BinaryLength >> 0); binaryForm[offset + 3] = (byte)(ace.BinaryLength >> 8); opaque.CopyTo(binaryForm, 4 + offset); return new object[] { ace, binaryForm, offset }; } public static IEnumerable<object[]> CustomAce_TestObjects() { yield return CustomAce_CreateTestData(19, 0, 4, 0); yield return CustomAce_CreateTestData(18, 1, 8, 0); yield return CustomAce_CreateTestData(17, 1, 4, 0); } [Fact] public void CustomAce_Constructor_Invalid() { Assert.Throws<ArgumentOutOfRangeException>(() => new CustomAce((AceType)16, (AceFlags)15, new byte[1])); Assert.Throws<ArgumentOutOfRangeException>(() => new CustomAce((AceType)19, (AceFlags)1, new byte[1])); Assert.Throws<ArgumentOutOfRangeException>(() => new CustomAce((AceType)0, (AceFlags)2, new byte[4])); foreach (AceType type in Enum.GetValues(typeof(AceType))) { Assert.Throws<ArgumentOutOfRangeException>(() => new CustomAce(type, (AceFlags)1, new byte[4])); } } [Fact] public void CustomAce_CreateBinaryForm_Invalid() { GenericAce ace = new CustomAce((AceType)19, (AceFlags)0, new byte[4]); AssertExtensions.Throws<ArgumentNullException>("binaryForm", () => CustomAce.CreateFromBinaryForm(null, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => CustomAce.CreateFromBinaryForm(new byte[1], -1)); AssertExtensions.Throws<ArgumentException>("binaryForm", () => CustomAce.CreateFromBinaryForm(new byte[ace.BinaryLength + 1], 2)); AssertExtensions.Throws<ArgumentException>("binaryForm", () => CustomAce.CreateFromBinaryForm(new byte[ace.BinaryLength], 1)); } [Fact] public void CustomAce_GetBinaryForm_Invalid() { GenericAce ace = new CustomAce((AceType)19, (AceFlags)0, new byte[4]); AssertExtensions.Throws<ArgumentNullException>("binaryForm", () => ace.GetBinaryForm(null, 1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => ace.GetBinaryForm(new byte[1], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("binaryForm", () => ace.GetBinaryForm(new byte[ace.BinaryLength + 1], 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("binaryForm", () => ace.GetBinaryForm(new byte[ace.BinaryLength], 1)); } [Theory] [MemberData(nameof(CustomAce_TestObjects))] public void CustomAce_GetBinaryForm(GenericAce testAce, byte[] expectedBinaryForm, int testOffset) { byte[] resultBinaryForm = new byte[testAce.BinaryLength + testOffset]; testAce.GetBinaryForm(resultBinaryForm, testOffset); GenericAce_VerifyBinaryForms(expectedBinaryForm, resultBinaryForm, testOffset); } [Theory] [MemberData(nameof(CustomAce_TestObjects))] public void CustomAce_CreateFromBinaryForm(GenericAce expectedAce, byte[] testBinaryForm, int testOffset) { GenericAce resultAce = CustomAce.CreateFromBinaryForm(testBinaryForm, testOffset); GenericAce_VerifyAces(expectedAce, resultAce); } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.SymbolStore; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using CultureInfo = System.Globalization.CultureInfo; namespace System.Reflection.Emit { public sealed class MethodBuilder : MethodInfo { #region Private Data Members // Identity internal string m_strName; // The name of the method private int m_token; // The token of this method private readonly ModuleBuilder m_module; [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] internal TypeBuilder m_containingType; // IL private int[]? m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups. private byte[]? m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise. internal LocalSymInfo? m_localSymInfo; // keep track debugging local information internal ILGenerator? m_ilGenerator; // Null if not used. private byte[]? m_ubBody; // The IL for the method private ExceptionHandler[]? m_exceptions; // Exception handlers or null if there are none. private const int DefaultMaxStack = 16; // Flags internal bool m_bIsBaked; private bool m_fInitLocals; // indicating if the method stack frame will be zero initialized or not. // Attributes private readonly MethodAttributes m_iAttributes; private readonly CallingConventions m_callingConvention; private MethodImplAttributes m_dwMethodImplFlags; // Parameters private SignatureHelper? m_signature; internal Type[]? m_parameterTypes; private Type m_returnType; private Type[]? m_returnTypeRequiredCustomModifiers; private Type[]? m_returnTypeOptionalCustomModifiers; private Type[][]? m_parameterTypeRequiredCustomModifiers; private Type[][]? m_parameterTypeOptionalCustomModifiers; // Generics private GenericTypeParameterBuilder[]? m_inst; private bool m_bIsGenMethDef; #endregion #region Constructor internal MethodBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers, ModuleBuilder mod, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TypeBuilder type) { ArgumentException.ThrowIfNullOrEmpty(name); if (name[0] == '\0') throw new ArgumentException(SR.Argument_IllegalName, nameof(name)); ArgumentNullException.ThrowIfNull(mod); if (parameterTypes != null) { foreach (Type t in parameterTypes) { ArgumentNullException.ThrowIfNull(t, nameof(parameterTypes)); } } m_strName = name; m_module = mod; m_containingType = type; m_returnType = returnType ?? typeof(void); if ((attributes & MethodAttributes.Static) == 0) { // turn on the has this calling convention callingConvention |= CallingConventions.HasThis; } else if ((attributes & MethodAttributes.Virtual) != 0) { // On an interface, the rule is slighlty different if (((attributes & MethodAttributes.Abstract) == 0)) throw new ArgumentException(SR.Arg_NoStaticVirtual); } m_callingConvention = callingConvention; if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length); } else { m_parameterTypes = null; } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; // m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention, // returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, // parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); m_iAttributes = attributes; m_bIsBaked = false; m_fInitLocals = true; m_localSymInfo = new LocalSymInfo(); m_ubBody = null; m_ilGenerator = null; // Default is managed IL. Manged IL has bit flag 0x0020 set off m_dwMethodImplFlags = MethodImplAttributes.IL; } #endregion #region Internal Members internal void CreateMethodBodyHelper(ILGenerator il!!) { // Sets the IL of the method. An ILGenerator is passed as an argument and the method // queries this instance to get all of the information which it needs. __ExceptionInfo[] excp; int counter = 0; int[] filterAddrs; int[] catchAddrs; int[] catchEndAddrs; Type[] catchClass; int[] type; int numCatch; int start, end; ModuleBuilder dynMod = (ModuleBuilder)m_module; m_containingType.ThrowIfCreated(); if (m_bIsBaked) { throw new InvalidOperationException(SR.InvalidOperation_MethodHasBody); } if (il.m_methodBuilder != this && il.m_methodBuilder != null) { // you don't need to call DefineBody when you get your ILGenerator // through MethodBuilder::GetILGenerator. // throw new InvalidOperationException(SR.InvalidOperation_BadILGeneratorUsage); } ThrowIfShouldNotHaveBody(); if (il.m_ScopeTree.m_iOpenScopeCount != 0) { // There are still unclosed local scope throw new InvalidOperationException(SR.InvalidOperation_OpenLocalVariableScope); } m_ubBody = il.BakeByteArray(); m_mdMethodFixups = il.GetTokenFixups(); // Okay, now the fun part. Calculate all of the exceptions. excp = il.GetExceptions()!; int numExceptions = CalculateNumberOfExceptions(excp); if (numExceptions > 0) { m_exceptions = new ExceptionHandler[numExceptions]; for (int i = 0; i < excp.Length; i++) { filterAddrs = excp[i].GetFilterAddresses(); catchAddrs = excp[i].GetCatchAddresses(); catchEndAddrs = excp[i].GetCatchEndAddresses(); catchClass = excp[i].GetCatchClass(); numCatch = excp[i].GetNumberOfCatches(); start = excp[i].GetStartAddress(); end = excp[i].GetEndAddress(); type = excp[i].GetExceptionTypes(); for (int j = 0; j < numCatch; j++) { int tkExceptionClass = 0; if (catchClass[j] != null) { tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]); } switch (type[j]) { case __ExceptionInfo.None: case __ExceptionInfo.Fault: case __ExceptionInfo.Filter: m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass); break; case __ExceptionInfo.Finally: m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass); break; } } } } m_bIsBaked = true; } // This is only called from TypeBuilder.CreateType after the method has been created internal void ReleaseBakedStructures() { if (!m_bIsBaked) { // We don't need to do anything here if we didn't baked the method body return; } m_ubBody = null; m_localSymInfo = null; m_mdMethodFixups = null; m_localSignature = null; m_exceptions = null; } internal override Type[] GetParameterTypes() => m_parameterTypes ??= Type.EmptyTypes; internal static Type? GetMethodBaseReturnType(MethodBase? method) { if (method is MethodInfo mi) { return mi.ReturnType; } else if (method is ConstructorInfo ci) { return ci.GetReturnType(); } else { Debug.Fail("We should never get here!"); return null; } } internal void SetToken(int token) { m_token = token; } internal byte[]? GetBody() { // Returns the il bytes of this method. // This il is not valid until somebody has called BakeByteArray return m_ubBody; } internal int[]? GetTokenFixups() { return m_mdMethodFixups; } internal SignatureHelper GetMethodSignature() { m_parameterTypes ??= Type.EmptyTypes; m_signature = SignatureHelper.GetMethodSigHelper(m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0, m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers, m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers); return m_signature; } // Returns a buffer whose initial signatureLength bytes contain encoded local signature. internal byte[] GetLocalSignature(out int signatureLength) { if (m_localSignature != null) { signatureLength = m_localSignature.Length; return m_localSignature; } if (m_ilGenerator != null) { if (m_ilGenerator.m_localCount != 0) { // If user is using ILGenerator::DeclareLocal, then get local signaturefrom there. return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength); } } return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength); } internal int GetMaxStack() { if (m_ilGenerator != null) { return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount; } else { // this is the case when client provide an array of IL byte stream rather than going through ILGenerator. return DefaultMaxStack; } } internal ExceptionHandler[]? GetExceptionHandlers() { return m_exceptions; } internal int ExceptionHandlerCount => m_exceptions != null ? m_exceptions.Length : 0; internal static int CalculateNumberOfExceptions(__ExceptionInfo[]? excp) { int num = 0; if (excp == null) { return 0; } for (int i = 0; i < excp.Length; i++) { num += excp[i].GetNumberOfCatches(); } return num; } internal bool IsTypeCreated() { return m_containingType != null && m_containingType.IsCreated(); } [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] internal TypeBuilder GetTypeBuilder() { return m_containingType; } internal ModuleBuilder GetModuleBuilder() { return m_module; } #endregion #region Object Overrides public override bool Equals(object? obj) { if (!(obj is MethodBuilder)) { return false; } if (!m_strName.Equals(((MethodBuilder)obj).m_strName)) { return false; } if (m_iAttributes != (((MethodBuilder)obj).m_iAttributes)) { return false; } SignatureHelper thatSig = ((MethodBuilder)obj).GetMethodSignature(); if (thatSig.Equals(GetMethodSignature())) { return true; } return false; } public override int GetHashCode() { return m_strName.GetHashCode(); } public override string ToString() { StringBuilder sb = new StringBuilder(1000); sb.Append("Name: ").Append(m_strName).AppendLine(" "); sb.Append("Attributes: ").Append((int)m_iAttributes).AppendLine(); sb.Append("Method Signature: ").Append(GetMethodSignature()).AppendLine(); sb.AppendLine(); return sb.ToString(); } #endregion #region MemberInfo Overrides public override string Name => m_strName; public override int MetadataToken => GetToken(); public override Module Module => m_containingType.Module; public override Type? DeclaringType { get { if (m_containingType.m_isHiddenGlobalType) return null; return m_containingType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes => new EmptyCAHolder(); public override Type? ReflectedType => DeclaringType; #endregion #region MethodBase Overrides public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_dwMethodImplFlags; } public override MethodAttributes Attributes => m_iAttributes; public override CallingConventions CallingConvention => m_callingConvention; public override RuntimeMethodHandle MethodHandle => throw new NotSupportedException(SR.NotSupported_DynamicModule); public override bool IsSecurityCritical => true; public override bool IsSecuritySafeCritical => false; public override bool IsSecurityTransparent => false; #endregion #region MethodInfo Overrides public override MethodInfo GetBaseDefinition() { return this; } public override Type ReturnType => m_returnType; public override ParameterInfo[] GetParameters() { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new NotSupportedException(SR.InvalidOperation_TypeNotCreated); MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes!)!; return rmi.GetParameters(); } public override ParameterInfo ReturnParameter { get { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new InvalidOperationException(SR.InvalidOperation_TypeNotCreated); MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes!)!; return rmi.ReturnParameter; } } #endregion #region ICustomAttributeProvider Implementation public override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } #endregion #region Generic Members public override bool IsGenericMethodDefinition => m_bIsGenMethDef; public override bool ContainsGenericParameters => throw new NotSupportedException(); public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return this; } public override bool IsGenericMethod => m_inst != null; public override Type[] GetGenericArguments() => m_inst ?? Type.EmptyTypes; [RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")] [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public override MethodInfo MakeGenericMethod(params Type[] typeArguments) { return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments); } public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names!!) { if (names.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(names)); if (m_inst != null) throw new InvalidOperationException(SR.InvalidOperation_GenericParametersAlreadySet); for (int i = 0; i < names.Length; i++) ArgumentNullException.ThrowIfNull(names[i], nameof(names)); if (m_token != 0) throw new InvalidOperationException(SR.InvalidOperation_MethodBuilderBaked); m_bIsGenMethDef = true; m_inst = new GenericTypeParameterBuilder[names.Length]; for (int i = 0; i < names.Length; i++) m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this)); return m_inst; } internal void ThrowIfGeneric() { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException(); } #endregion #region Public Members private int GetToken() { // We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498 // we only "tokenize" a method when requested. But the order in which the methods are tokenized // didn't change: the same order the MethodBuilders are constructed. The recursion introduced // will overflow the stack when there are many methods on the same type (10000 in my experiment). // The change also introduced race conditions. Before the code change GetToken is called from // the MethodBuilder .ctor which is protected by lock(ModuleBuilder.SyncRoot). Now it // could be called more than once on the the same method introducing duplicate (invalid) tokens. // I don't fully understand this change. So I will keep the logic and only fix the recursion and // the race condition. if (m_token != 0) { return m_token; } MethodBuilder? currentMethod = null; int currentToken = 0; int i; // We need to lock here to prevent a method from being "tokenized" twice. // We don't need to synchronize this with Type.DefineMethod because it only appends newly // constructed MethodBuilders to the end of m_listMethods lock (m_containingType.m_listMethods!) { if (m_token != 0) { return m_token; } // If m_tkMethod is still 0 when we obtain the lock, m_lastTokenizedMethod must be smaller // than the index of the current method. for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; ++i) { currentMethod = m_containingType.m_listMethods[i]; currentToken = currentMethod.GetTokenNoLock(); if (currentMethod == this) break; } m_containingType.m_lastTokenizedMethod = i; } Debug.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods"); Debug.Assert(currentToken != 0, "The token should not be 0"); return currentToken; } private int GetTokenNoLock() { Debug.Assert(m_token == 0, "m_token should not have been initialized"); byte[] sigBytes = GetMethodSignature().InternalGetSignature(out int sigLength); ModuleBuilder module = m_module; int token = TypeBuilder.DefineMethod(new QCallModule(ref module), m_containingType.MetadataToken, m_strName, sigBytes, sigLength, Attributes); m_token = token; if (m_inst != null) foreach (GenericTypeParameterBuilder tb in m_inst) if (!tb.m_type.IsCreated()) tb.m_type.CreateType(); TypeBuilder.SetMethodImpl(new QCallModule(ref module), token, m_dwMethodImplFlags); return m_token; } public void SetParameters(params Type[] parameterTypes) { AssemblyBuilder.CheckContext(parameterTypes); SetSignature(null, null, null, parameterTypes, null, null); } public void SetReturnType(Type? returnType) { AssemblyBuilder.CheckContext(returnType); SetSignature(returnType, null, null, null, null, null); } public void SetSignature( Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { // We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked. // But we cannot because that would be a breaking change from V2. if (m_token != 0) return; AssemblyBuilder.CheckContext(returnType); AssemblyBuilder.CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); AssemblyBuilder.CheckContext(parameterTypeRequiredCustomModifiers); AssemblyBuilder.CheckContext(parameterTypeOptionalCustomModifiers); ThrowIfGeneric(); if (returnType != null) { m_returnType = returnType; } if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length); } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; } public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string? strParamName) { if (position < 0) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); ThrowIfGeneric(); m_containingType.ThrowIfCreated(); if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length)) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); attributes &= ~ParameterAttributes.ReservedMask; return new ParameterBuilder(this, position, attributes, strParamName); } public void SetImplementationFlags(MethodImplAttributes attributes) { ThrowIfGeneric(); m_containingType.ThrowIfCreated(); m_dwMethodImplFlags = attributes; m_canBeRuntimeImpl = true; ModuleBuilder module = m_module; TypeBuilder.SetMethodImpl(new QCallModule(ref module), MetadataToken, attributes); } public ILGenerator GetILGenerator() { ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); return m_ilGenerator ??= new ILGenerator(this); } public ILGenerator GetILGenerator(int size) { ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); return m_ilGenerator ??= new ILGenerator(this, size); } private void ThrowIfShouldNotHaveBody() { if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL || (m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 || (m_iAttributes & MethodAttributes.PinvokeImpl) != 0 || m_isDllImport) { // cannot attach method body if methodimpl is marked not marked as managed IL // throw new InvalidOperationException(SR.InvalidOperation_ShouldNotHaveMethodBody); } } public bool InitLocals { // Property is set to true if user wishes to have zero initialized stack frame for this method. Default to false. get { ThrowIfGeneric(); return m_fInitLocals; } set { ThrowIfGeneric(); m_fInitLocals = value; } } internal Module GetModule() { return GetModuleBuilder(); } public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) { ThrowIfGeneric(); TypeBuilder.DefineCustomAttribute(m_module, MetadataToken, ((ModuleBuilder)m_module).GetConstructorToken(con), binaryAttribute); if (IsKnownCA(con)) ParseCA(con); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!) { ThrowIfGeneric(); customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataToken); if (IsKnownCA(customBuilder.m_con)) ParseCA(customBuilder.m_con); } // this method should return true for any and every ca that requires more work // than just setting the ca private static bool IsKnownCA(ConstructorInfo con) { Type? caType = con.DeclaringType; return caType == typeof(MethodImplAttribute) || caType == typeof(DllImportAttribute); } private void ParseCA(ConstructorInfo con) { Type? caType = con.DeclaringType; if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) { // dig through the blob looking for the MethodImplAttributes flag // that must be in the MethodCodeType field // for now we simply set a flag that relaxes the check when saving and // allows this method to have no body when any kind of MethodImplAttribute is present m_canBeRuntimeImpl = true; } else if (caType == typeof(DllImportAttribute)) { m_canBeRuntimeImpl = true; m_isDllImport = true; } } internal bool m_canBeRuntimeImpl; internal bool m_isDllImport; #endregion } internal sealed class LocalSymInfo { // This class tracks the local variable's debugging information // and namespace information with a given active lexical scope. #region Internal Data Members internal string[] m_strName = null!; // All these arrys initialized in helper method internal byte[][] m_ubSignature = null!; internal int[] m_iLocalSlot = null!; internal int[] m_iStartOffset = null!; internal int[] m_iEndOffset = null!; internal int m_iLocalSymCount; // how many entries in the arrays are occupied internal string[] m_namespace = null!; internal int m_iNameSpaceCount; internal const int InitialSize = 16; #endregion #region Constructor internal LocalSymInfo() { // initialize data variables m_iLocalSymCount = 0; m_iNameSpaceCount = 0; } #endregion #region Private Members private void EnsureCapacityNamespace() { if (m_iNameSpaceCount == 0) { m_namespace = new string[InitialSize]; } else if (m_iNameSpaceCount == m_namespace.Length) { string[] strTemp = new string[checked(m_iNameSpaceCount * 2)]; Array.Copy(m_namespace, strTemp, m_iNameSpaceCount); m_namespace = strTemp; } } private void EnsureCapacity() { if (m_iLocalSymCount == 0) { // First time. Allocate the arrays. m_strName = new string[InitialSize]; m_ubSignature = new byte[InitialSize][]; m_iLocalSlot = new int[InitialSize]; m_iStartOffset = new int[InitialSize]; m_iEndOffset = new int[InitialSize]; } else if (m_iLocalSymCount == m_strName.Length) { // the arrays are full. Enlarge the arrays // why aren't we just using lists here? int newSize = checked(m_iLocalSymCount * 2); int[] temp = new int[newSize]; Array.Copy(m_iLocalSlot, temp, m_iLocalSymCount); m_iLocalSlot = temp; temp = new int[newSize]; Array.Copy(m_iStartOffset, temp, m_iLocalSymCount); m_iStartOffset = temp; temp = new int[newSize]; Array.Copy(m_iEndOffset, temp, m_iLocalSymCount); m_iEndOffset = temp; string[] strTemp = new string[newSize]; Array.Copy(m_strName, strTemp, m_iLocalSymCount); m_strName = strTemp; byte[][] ubTemp = new byte[newSize][]; Array.Copy(m_ubSignature, ubTemp, m_iLocalSymCount); m_ubSignature = ubTemp; } } #endregion #region Internal Members internal void AddLocalSymInfo(string strName, byte[] signature, int slot, int startOffset, int endOffset) { // make sure that arrays are large enough to hold addition info EnsureCapacity(); m_iStartOffset[m_iLocalSymCount] = startOffset; m_iEndOffset[m_iLocalSymCount] = endOffset; m_iLocalSlot[m_iLocalSymCount] = slot; m_strName[m_iLocalSymCount] = strName; m_ubSignature[m_iLocalSymCount] = signature; checked { m_iLocalSymCount++; } } internal void AddUsingNamespace(string strNamespace) { EnsureCapacityNamespace(); m_namespace[m_iNameSpaceCount] = strNamespace; checked { m_iNameSpaceCount++; } } #endregion } /// <summary> /// Describes exception handler in a method body. /// </summary> [StructLayout(LayoutKind.Sequential)] internal readonly struct ExceptionHandler : IEquatable<ExceptionHandler> { // Keep in sync with unmanged structure. internal readonly int m_exceptionClass; internal readonly int m_tryStartOffset; internal readonly int m_tryEndOffset; internal readonly int m_filterOffset; internal readonly int m_handlerStartOffset; internal readonly int m_handlerEndOffset; internal readonly ExceptionHandlingClauseOptions m_kind; #region Constructors internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset, int kind, int exceptionTypeToken) { Debug.Assert(tryStartOffset >= 0); Debug.Assert(tryEndOffset >= 0); Debug.Assert(filterOffset >= 0); Debug.Assert(handlerStartOffset >= 0); Debug.Assert(handlerEndOffset >= 0); Debug.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind)); Debug.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0); m_tryStartOffset = tryStartOffset; m_tryEndOffset = tryEndOffset; m_filterOffset = filterOffset; m_handlerStartOffset = handlerStartOffset; m_handlerEndOffset = handlerEndOffset; m_kind = (ExceptionHandlingClauseOptions)kind; m_exceptionClass = exceptionTypeToken; } private static bool IsValidKind(ExceptionHandlingClauseOptions kind) { switch (kind) { case ExceptionHandlingClauseOptions.Clause: case ExceptionHandlingClauseOptions.Filter: case ExceptionHandlingClauseOptions.Finally: case ExceptionHandlingClauseOptions.Fault: return true; default: return false; } } #endregion #region Equality public override int GetHashCode() { return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind; } public override bool Equals(object? obj) { return obj is ExceptionHandler && Equals((ExceptionHandler)obj); } public bool Equals(ExceptionHandler other) { return other.m_exceptionClass == m_exceptionClass && other.m_tryStartOffset == m_tryStartOffset && other.m_tryEndOffset == m_tryEndOffset && other.m_filterOffset == m_filterOffset && other.m_handlerStartOffset == m_handlerStartOffset && other.m_handlerEndOffset == m_handlerEndOffset && other.m_kind == m_kind; } public static bool operator ==(ExceptionHandler left, ExceptionHandler right) => left.Equals(right); public static bool operator !=(ExceptionHandler left, ExceptionHandler right) => !left.Equals(right); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.SymbolStore; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using CultureInfo = System.Globalization.CultureInfo; namespace System.Reflection.Emit { public sealed class MethodBuilder : MethodInfo { #region Private Data Members // Identity internal string m_strName; // The name of the method private int m_token; // The token of this method private readonly ModuleBuilder m_module; [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] internal TypeBuilder m_containingType; // IL private int[]? m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups. private byte[]? m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise. internal LocalSymInfo? m_localSymInfo; // keep track debugging local information internal ILGenerator? m_ilGenerator; // Null if not used. private byte[]? m_ubBody; // The IL for the method private ExceptionHandler[]? m_exceptions; // Exception handlers or null if there are none. private const int DefaultMaxStack = 16; // Flags internal bool m_bIsBaked; private bool m_fInitLocals; // indicating if the method stack frame will be zero initialized or not. // Attributes private readonly MethodAttributes m_iAttributes; private readonly CallingConventions m_callingConvention; private MethodImplAttributes m_dwMethodImplFlags; // Parameters private SignatureHelper? m_signature; internal Type[]? m_parameterTypes; private Type m_returnType; private Type[]? m_returnTypeRequiredCustomModifiers; private Type[]? m_returnTypeOptionalCustomModifiers; private Type[][]? m_parameterTypeRequiredCustomModifiers; private Type[][]? m_parameterTypeOptionalCustomModifiers; // Generics private GenericTypeParameterBuilder[]? m_inst; private bool m_bIsGenMethDef; #endregion #region Constructor internal MethodBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers, ModuleBuilder mod, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TypeBuilder type) { ArgumentException.ThrowIfNullOrEmpty(name); if (name[0] == '\0') throw new ArgumentException(SR.Argument_IllegalName, nameof(name)); ArgumentNullException.ThrowIfNull(mod); if (parameterTypes != null) { foreach (Type t in parameterTypes) { ArgumentNullException.ThrowIfNull(t, nameof(parameterTypes)); } } m_strName = name; m_module = mod; m_containingType = type; m_returnType = returnType ?? typeof(void); if ((attributes & MethodAttributes.Static) == 0) { // turn on the has this calling convention callingConvention |= CallingConventions.HasThis; } else if ((attributes & MethodAttributes.Virtual) != 0) { // On an interface, the rule is slighlty different if (((attributes & MethodAttributes.Abstract) == 0)) throw new ArgumentException(SR.Arg_NoStaticVirtual); } m_callingConvention = callingConvention; if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length); } else { m_parameterTypes = null; } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; // m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention, // returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, // parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); m_iAttributes = attributes; m_bIsBaked = false; m_fInitLocals = true; m_localSymInfo = new LocalSymInfo(); m_ubBody = null; m_ilGenerator = null; // Default is managed IL. Manged IL has bit flag 0x0020 set off m_dwMethodImplFlags = MethodImplAttributes.IL; } #endregion #region Internal Members internal void CreateMethodBodyHelper(ILGenerator il!!) { // Sets the IL of the method. An ILGenerator is passed as an argument and the method // queries this instance to get all of the information which it needs. __ExceptionInfo[] excp; int counter = 0; int[] filterAddrs; int[] catchAddrs; int[] catchEndAddrs; Type[] catchClass; int[] type; int numCatch; int start, end; ModuleBuilder dynMod = (ModuleBuilder)m_module; m_containingType.ThrowIfCreated(); if (m_bIsBaked) { throw new InvalidOperationException(SR.InvalidOperation_MethodHasBody); } if (il.m_methodBuilder != this && il.m_methodBuilder != null) { // you don't need to call DefineBody when you get your ILGenerator // through MethodBuilder::GetILGenerator. // throw new InvalidOperationException(SR.InvalidOperation_BadILGeneratorUsage); } ThrowIfShouldNotHaveBody(); if (il.m_ScopeTree.m_iOpenScopeCount != 0) { // There are still unclosed local scope throw new InvalidOperationException(SR.InvalidOperation_OpenLocalVariableScope); } m_ubBody = il.BakeByteArray(); m_mdMethodFixups = il.GetTokenFixups(); // Okay, now the fun part. Calculate all of the exceptions. excp = il.GetExceptions()!; int numExceptions = CalculateNumberOfExceptions(excp); if (numExceptions > 0) { m_exceptions = new ExceptionHandler[numExceptions]; for (int i = 0; i < excp.Length; i++) { filterAddrs = excp[i].GetFilterAddresses(); catchAddrs = excp[i].GetCatchAddresses(); catchEndAddrs = excp[i].GetCatchEndAddresses(); catchClass = excp[i].GetCatchClass(); numCatch = excp[i].GetNumberOfCatches(); start = excp[i].GetStartAddress(); end = excp[i].GetEndAddress(); type = excp[i].GetExceptionTypes(); for (int j = 0; j < numCatch; j++) { int tkExceptionClass = 0; if (catchClass[j] != null) { tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]); } switch (type[j]) { case __ExceptionInfo.None: case __ExceptionInfo.Fault: case __ExceptionInfo.Filter: m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass); break; case __ExceptionInfo.Finally: m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass); break; } } } } m_bIsBaked = true; } // This is only called from TypeBuilder.CreateType after the method has been created internal void ReleaseBakedStructures() { if (!m_bIsBaked) { // We don't need to do anything here if we didn't baked the method body return; } m_ubBody = null; m_localSymInfo = null; m_mdMethodFixups = null; m_localSignature = null; m_exceptions = null; } internal override Type[] GetParameterTypes() => m_parameterTypes ??= Type.EmptyTypes; internal static Type? GetMethodBaseReturnType(MethodBase? method) { if (method is MethodInfo mi) { return mi.ReturnType; } else if (method is ConstructorInfo ci) { return ci.GetReturnType(); } else { Debug.Fail("We should never get here!"); return null; } } internal void SetToken(int token) { m_token = token; } internal byte[]? GetBody() { // Returns the il bytes of this method. // This il is not valid until somebody has called BakeByteArray return m_ubBody; } internal int[]? GetTokenFixups() { return m_mdMethodFixups; } internal SignatureHelper GetMethodSignature() { m_parameterTypes ??= Type.EmptyTypes; m_signature = SignatureHelper.GetMethodSigHelper(m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0, m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers, m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers); return m_signature; } // Returns a buffer whose initial signatureLength bytes contain encoded local signature. internal byte[] GetLocalSignature(out int signatureLength) { if (m_localSignature != null) { signatureLength = m_localSignature.Length; return m_localSignature; } if (m_ilGenerator != null) { if (m_ilGenerator.m_localCount != 0) { // If user is using ILGenerator::DeclareLocal, then get local signaturefrom there. return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength); } } return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength); } internal int GetMaxStack() { if (m_ilGenerator != null) { return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount; } else { // this is the case when client provide an array of IL byte stream rather than going through ILGenerator. return DefaultMaxStack; } } internal ExceptionHandler[]? GetExceptionHandlers() { return m_exceptions; } internal int ExceptionHandlerCount => m_exceptions != null ? m_exceptions.Length : 0; internal static int CalculateNumberOfExceptions(__ExceptionInfo[]? excp) { int num = 0; if (excp == null) { return 0; } for (int i = 0; i < excp.Length; i++) { num += excp[i].GetNumberOfCatches(); } return num; } internal bool IsTypeCreated() { return m_containingType != null && m_containingType.IsCreated(); } [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] internal TypeBuilder GetTypeBuilder() { return m_containingType; } internal ModuleBuilder GetModuleBuilder() { return m_module; } #endregion #region Object Overrides public override bool Equals(object? obj) { if (!(obj is MethodBuilder)) { return false; } if (!m_strName.Equals(((MethodBuilder)obj).m_strName)) { return false; } if (m_iAttributes != (((MethodBuilder)obj).m_iAttributes)) { return false; } SignatureHelper thatSig = ((MethodBuilder)obj).GetMethodSignature(); if (thatSig.Equals(GetMethodSignature())) { return true; } return false; } public override int GetHashCode() { return m_strName.GetHashCode(); } public override string ToString() { StringBuilder sb = new StringBuilder(1000); sb.Append("Name: ").Append(m_strName).AppendLine(" "); sb.Append("Attributes: ").Append((int)m_iAttributes).AppendLine(); sb.Append("Method Signature: ").Append(GetMethodSignature()).AppendLine(); sb.AppendLine(); return sb.ToString(); } #endregion #region MemberInfo Overrides public override string Name => m_strName; public override int MetadataToken => GetToken(); public override Module Module => m_containingType.Module; public override Type? DeclaringType { get { if (m_containingType.m_isHiddenGlobalType) return null; return m_containingType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes => new EmptyCAHolder(); public override Type? ReflectedType => DeclaringType; #endregion #region MethodBase Overrides public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_dwMethodImplFlags; } public override MethodAttributes Attributes => m_iAttributes; public override CallingConventions CallingConvention => m_callingConvention; public override RuntimeMethodHandle MethodHandle => throw new NotSupportedException(SR.NotSupported_DynamicModule); public override bool IsSecurityCritical => true; public override bool IsSecuritySafeCritical => false; public override bool IsSecurityTransparent => false; #endregion #region MethodInfo Overrides public override MethodInfo GetBaseDefinition() { return this; } public override Type ReturnType => m_returnType; public override ParameterInfo[] GetParameters() { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new NotSupportedException(SR.InvalidOperation_TypeNotCreated); MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes!)!; return rmi.GetParameters(); } public override ParameterInfo ReturnParameter { get { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new InvalidOperationException(SR.InvalidOperation_TypeNotCreated); MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes!)!; return rmi.ReturnParameter; } } #endregion #region ICustomAttributeProvider Implementation public override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } #endregion #region Generic Members public override bool IsGenericMethodDefinition => m_bIsGenMethDef; public override bool ContainsGenericParameters => throw new NotSupportedException(); public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return this; } public override bool IsGenericMethod => m_inst != null; public override Type[] GetGenericArguments() => m_inst ?? Type.EmptyTypes; [RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")] [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public override MethodInfo MakeGenericMethod(params Type[] typeArguments) { return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments); } public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names!!) { if (names.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(names)); if (m_inst != null) throw new InvalidOperationException(SR.InvalidOperation_GenericParametersAlreadySet); for (int i = 0; i < names.Length; i++) ArgumentNullException.ThrowIfNull(names[i], nameof(names)); if (m_token != 0) throw new InvalidOperationException(SR.InvalidOperation_MethodBuilderBaked); m_bIsGenMethDef = true; m_inst = new GenericTypeParameterBuilder[names.Length]; for (int i = 0; i < names.Length; i++) m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this)); return m_inst; } internal void ThrowIfGeneric() { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException(); } #endregion #region Public Members private int GetToken() { // We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498 // we only "tokenize" a method when requested. But the order in which the methods are tokenized // didn't change: the same order the MethodBuilders are constructed. The recursion introduced // will overflow the stack when there are many methods on the same type (10000 in my experiment). // The change also introduced race conditions. Before the code change GetToken is called from // the MethodBuilder .ctor which is protected by lock(ModuleBuilder.SyncRoot). Now it // could be called more than once on the the same method introducing duplicate (invalid) tokens. // I don't fully understand this change. So I will keep the logic and only fix the recursion and // the race condition. if (m_token != 0) { return m_token; } MethodBuilder? currentMethod = null; int currentToken = 0; int i; // We need to lock here to prevent a method from being "tokenized" twice. // We don't need to synchronize this with Type.DefineMethod because it only appends newly // constructed MethodBuilders to the end of m_listMethods lock (m_containingType.m_listMethods!) { if (m_token != 0) { return m_token; } // If m_tkMethod is still 0 when we obtain the lock, m_lastTokenizedMethod must be smaller // than the index of the current method. for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; ++i) { currentMethod = m_containingType.m_listMethods[i]; currentToken = currentMethod.GetTokenNoLock(); if (currentMethod == this) break; } m_containingType.m_lastTokenizedMethod = i; } Debug.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods"); Debug.Assert(currentToken != 0, "The token should not be 0"); return currentToken; } private int GetTokenNoLock() { Debug.Assert(m_token == 0, "m_token should not have been initialized"); byte[] sigBytes = GetMethodSignature().InternalGetSignature(out int sigLength); ModuleBuilder module = m_module; int token = TypeBuilder.DefineMethod(new QCallModule(ref module), m_containingType.MetadataToken, m_strName, sigBytes, sigLength, Attributes); m_token = token; if (m_inst != null) foreach (GenericTypeParameterBuilder tb in m_inst) if (!tb.m_type.IsCreated()) tb.m_type.CreateType(); TypeBuilder.SetMethodImpl(new QCallModule(ref module), token, m_dwMethodImplFlags); return m_token; } public void SetParameters(params Type[] parameterTypes) { AssemblyBuilder.CheckContext(parameterTypes); SetSignature(null, null, null, parameterTypes, null, null); } public void SetReturnType(Type? returnType) { AssemblyBuilder.CheckContext(returnType); SetSignature(returnType, null, null, null, null, null); } public void SetSignature( Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { // We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked. // But we cannot because that would be a breaking change from V2. if (m_token != 0) return; AssemblyBuilder.CheckContext(returnType); AssemblyBuilder.CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); AssemblyBuilder.CheckContext(parameterTypeRequiredCustomModifiers); AssemblyBuilder.CheckContext(parameterTypeOptionalCustomModifiers); ThrowIfGeneric(); if (returnType != null) { m_returnType = returnType; } if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length); } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; } public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string? strParamName) { if (position < 0) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); ThrowIfGeneric(); m_containingType.ThrowIfCreated(); if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length)) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); attributes &= ~ParameterAttributes.ReservedMask; return new ParameterBuilder(this, position, attributes, strParamName); } public void SetImplementationFlags(MethodImplAttributes attributes) { ThrowIfGeneric(); m_containingType.ThrowIfCreated(); m_dwMethodImplFlags = attributes; m_canBeRuntimeImpl = true; ModuleBuilder module = m_module; TypeBuilder.SetMethodImpl(new QCallModule(ref module), MetadataToken, attributes); } public ILGenerator GetILGenerator() { ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); return m_ilGenerator ??= new ILGenerator(this); } public ILGenerator GetILGenerator(int size) { ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); return m_ilGenerator ??= new ILGenerator(this, size); } private void ThrowIfShouldNotHaveBody() { if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL || (m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 || (m_iAttributes & MethodAttributes.PinvokeImpl) != 0 || m_isDllImport) { // cannot attach method body if methodimpl is marked not marked as managed IL // throw new InvalidOperationException(SR.InvalidOperation_ShouldNotHaveMethodBody); } } public bool InitLocals { // Property is set to true if user wishes to have zero initialized stack frame for this method. Default to false. get { ThrowIfGeneric(); return m_fInitLocals; } set { ThrowIfGeneric(); m_fInitLocals = value; } } internal Module GetModule() { return GetModuleBuilder(); } public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!) { ThrowIfGeneric(); TypeBuilder.DefineCustomAttribute(m_module, MetadataToken, ((ModuleBuilder)m_module).GetConstructorToken(con), binaryAttribute); if (IsKnownCA(con)) ParseCA(con); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!) { ThrowIfGeneric(); customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataToken); if (IsKnownCA(customBuilder.m_con)) ParseCA(customBuilder.m_con); } // this method should return true for any and every ca that requires more work // than just setting the ca private static bool IsKnownCA(ConstructorInfo con) { Type? caType = con.DeclaringType; return caType == typeof(MethodImplAttribute) || caType == typeof(DllImportAttribute); } private void ParseCA(ConstructorInfo con) { Type? caType = con.DeclaringType; if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) { // dig through the blob looking for the MethodImplAttributes flag // that must be in the MethodCodeType field // for now we simply set a flag that relaxes the check when saving and // allows this method to have no body when any kind of MethodImplAttribute is present m_canBeRuntimeImpl = true; } else if (caType == typeof(DllImportAttribute)) { m_canBeRuntimeImpl = true; m_isDllImport = true; } } internal bool m_canBeRuntimeImpl; internal bool m_isDllImport; #endregion } internal sealed class LocalSymInfo { // This class tracks the local variable's debugging information // and namespace information with a given active lexical scope. #region Internal Data Members internal string[] m_strName = null!; // All these arrys initialized in helper method internal byte[][] m_ubSignature = null!; internal int[] m_iLocalSlot = null!; internal int[] m_iStartOffset = null!; internal int[] m_iEndOffset = null!; internal int m_iLocalSymCount; // how many entries in the arrays are occupied internal string[] m_namespace = null!; internal int m_iNameSpaceCount; internal const int InitialSize = 16; #endregion #region Constructor internal LocalSymInfo() { // initialize data variables m_iLocalSymCount = 0; m_iNameSpaceCount = 0; } #endregion #region Private Members private void EnsureCapacityNamespace() { if (m_iNameSpaceCount == 0) { m_namespace = new string[InitialSize]; } else if (m_iNameSpaceCount == m_namespace.Length) { string[] strTemp = new string[checked(m_iNameSpaceCount * 2)]; Array.Copy(m_namespace, strTemp, m_iNameSpaceCount); m_namespace = strTemp; } } private void EnsureCapacity() { if (m_iLocalSymCount == 0) { // First time. Allocate the arrays. m_strName = new string[InitialSize]; m_ubSignature = new byte[InitialSize][]; m_iLocalSlot = new int[InitialSize]; m_iStartOffset = new int[InitialSize]; m_iEndOffset = new int[InitialSize]; } else if (m_iLocalSymCount == m_strName.Length) { // the arrays are full. Enlarge the arrays // why aren't we just using lists here? int newSize = checked(m_iLocalSymCount * 2); int[] temp = new int[newSize]; Array.Copy(m_iLocalSlot, temp, m_iLocalSymCount); m_iLocalSlot = temp; temp = new int[newSize]; Array.Copy(m_iStartOffset, temp, m_iLocalSymCount); m_iStartOffset = temp; temp = new int[newSize]; Array.Copy(m_iEndOffset, temp, m_iLocalSymCount); m_iEndOffset = temp; string[] strTemp = new string[newSize]; Array.Copy(m_strName, strTemp, m_iLocalSymCount); m_strName = strTemp; byte[][] ubTemp = new byte[newSize][]; Array.Copy(m_ubSignature, ubTemp, m_iLocalSymCount); m_ubSignature = ubTemp; } } #endregion #region Internal Members internal void AddLocalSymInfo(string strName, byte[] signature, int slot, int startOffset, int endOffset) { // make sure that arrays are large enough to hold addition info EnsureCapacity(); m_iStartOffset[m_iLocalSymCount] = startOffset; m_iEndOffset[m_iLocalSymCount] = endOffset; m_iLocalSlot[m_iLocalSymCount] = slot; m_strName[m_iLocalSymCount] = strName; m_ubSignature[m_iLocalSymCount] = signature; checked { m_iLocalSymCount++; } } internal void AddUsingNamespace(string strNamespace) { EnsureCapacityNamespace(); m_namespace[m_iNameSpaceCount] = strNamespace; checked { m_iNameSpaceCount++; } } #endregion } /// <summary> /// Describes exception handler in a method body. /// </summary> [StructLayout(LayoutKind.Sequential)] internal readonly struct ExceptionHandler : IEquatable<ExceptionHandler> { // Keep in sync with unmanged structure. internal readonly int m_exceptionClass; internal readonly int m_tryStartOffset; internal readonly int m_tryEndOffset; internal readonly int m_filterOffset; internal readonly int m_handlerStartOffset; internal readonly int m_handlerEndOffset; internal readonly ExceptionHandlingClauseOptions m_kind; #region Constructors internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset, int kind, int exceptionTypeToken) { Debug.Assert(tryStartOffset >= 0); Debug.Assert(tryEndOffset >= 0); Debug.Assert(filterOffset >= 0); Debug.Assert(handlerStartOffset >= 0); Debug.Assert(handlerEndOffset >= 0); Debug.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind)); Debug.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0); m_tryStartOffset = tryStartOffset; m_tryEndOffset = tryEndOffset; m_filterOffset = filterOffset; m_handlerStartOffset = handlerStartOffset; m_handlerEndOffset = handlerEndOffset; m_kind = (ExceptionHandlingClauseOptions)kind; m_exceptionClass = exceptionTypeToken; } private static bool IsValidKind(ExceptionHandlingClauseOptions kind) { switch (kind) { case ExceptionHandlingClauseOptions.Clause: case ExceptionHandlingClauseOptions.Filter: case ExceptionHandlingClauseOptions.Finally: case ExceptionHandlingClauseOptions.Fault: return true; default: return false; } } #endregion #region Equality public override int GetHashCode() { return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind; } public override bool Equals(object? obj) { return obj is ExceptionHandler && Equals((ExceptionHandler)obj); } public bool Equals(ExceptionHandler other) { return other.m_exceptionClass == m_exceptionClass && other.m_tryStartOffset == m_tryStartOffset && other.m_tryEndOffset == m_tryEndOffset && other.m_filterOffset == m_filterOffset && other.m_handlerStartOffset == m_handlerStartOffset && other.m_handlerEndOffset == m_handlerEndOffset && other.m_kind == m_kind; } public static bool operator ==(ExceptionHandler left, ExceptionHandler right) => left.Equals(right); public static bool operator !=(ExceptionHandler left, ExceptionHandler right) => !left.Equals(right); #endregion } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/Microsoft.Win32.Registry/tests/RegistryTestsBase.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 Xunit; namespace Microsoft.Win32.RegistryTests { public abstract class RegistryTestsBase : IDisposable { protected string TestRegistryKeyName { get; private set; } protected RegistryKey TestRegistryKey { get; private set; } protected RegistryTestsBase() { // Create a unique name for this test class TestRegistryKeyName = CreateUniqueKeyName(); // Cleanup the key in case a previous run of this test crashed and left // the key behind. The key name is specific enough to corefx that we don't // need to worry about it being a real key on the user's system used // for another purpose. RemoveKeyIfExists(TestRegistryKeyName); // Then create the key. TestRegistryKey = Registry.CurrentUser.CreateSubKey(TestRegistryKeyName, true); Assert.NotNull(TestRegistryKey); } public void Dispose() { TestRegistryKey.Dispose(); RemoveKeyIfExists(TestRegistryKeyName); } private static void RemoveKeyIfExists(string keyName) { RegistryKey rk = Registry.CurrentUser; if (rk.OpenSubKey(keyName) != null) { rk.DeleteSubKeyTree(keyName); Assert.Null(rk.OpenSubKey(keyName)); } } private string CreateUniqueKeyName() { // Create a name to use for this class of tests. The name includes: // - A "corefxtest" prefix to help make it clear to anyone looking at the registry // that these keys are test-only and can be deleted, in case the tests crash and // we end up leaving some keys behind. // - The name of this test class, so as to avoid problems with tests on different test // classes running concurrently return "corefxtest_" + GetType().Name; } public static readonly object[][] TestRegistrySubKeyNames = { new object[] { @"Foo", @"Foo" }, new object[] { @"Foo\Bar", @"Foo\Bar" }, // Multiple/trailing slashes should be removed. new object[] { @"Foo", @"Foo\" }, new object[] { @"Foo", @"Foo\\" }, new object[] { @"Foo", @"Foo\\\" }, new object[] { @"Foo", @"Foo\\\\" }, new object[] { @"Foo\Bar", @"Foo\\Bar" }, new object[] { @"Foo\Bar", @"Foo\\\Bar" }, new object[] { @"Foo\Bar", @"Foo\\\\Bar" }, new object[] { @"Foo\Bar", @"Foo\Bar\" }, new object[] { @"Foo\Bar", @"Foo\Bar\\" }, new object[] { @"Foo\Bar", @"Foo\Bar\\\" }, new object[] { @"Foo\Bar", @"Foo\\Bar\" }, new object[] { @"Foo\Bar", @"Foo\\Bar\\" }, new object[] { @"Foo\Bar", @"Foo\\Bar\\\" }, new object[] { @"Foo\Bar", @"Foo\\\Bar\\\" }, new object[] { @"Foo\Bar", @"Foo\\\\Bar\\\\" }, // The name fix-up implementation uses a mark-and-sweep approach. // If there are multiple slashes, any extra slash chars will be // replaced with a marker char ('\uffff'), and then all '\uffff' // chars will be removed, including any pre-existing '\uffff' chars. InsertMarkerChar(@"Foo", @"{0}Foo\\"), InsertMarkerChar(@"Foo", @"Foo{0}\\"), InsertMarkerChar(@"Foo", @"Foo\\{0}"), InsertMarkerChar(@"Foo", @"Fo{0}o\\"), InsertMarkerChar(@"Foo", @"{0}Fo{0}o{0}\\{0}"), InsertMarkerChar(@"Foo", @"{0}Foo\\\"), InsertMarkerChar(@"Foo", @"Foo{0}\\\"), InsertMarkerChar(@"Foo", @"Foo\\\{0}"), InsertMarkerChar(@"Foo", @"Fo{0}o\\\"), InsertMarkerChar(@"Foo", @"{0}Fo{0}o{0}\\\{0}"), InsertMarkerChar(@"Foo\Bar", @"{0}Foo\\Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo{0}\\Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo\\{0}Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo\\Bar{0}"), InsertMarkerChar(@"Foo\Bar", @"Fo{0}o\\Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo\\B{0}ar"), InsertMarkerChar(@"Foo\Bar", @"Fo{0}o\\B{0}ar"), InsertMarkerChar(@"Foo\Bar", @"{0}Fo{0}o{0}\\{0}B{0}ar{0}"), InsertMarkerChar(@"Foo\Bar", @"{0}Foo\\\Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo{0}\\\Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo\\\{0}Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo\\\Bar{0}"), InsertMarkerChar(@"Foo\Bar", @"Fo{0}o\\\Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo\\\B{0}ar"), InsertMarkerChar(@"Foo\Bar", @"Fo{0}o\\\B{0}ar"), InsertMarkerChar(@"Foo\Bar", @"{0}Fo{0}o{0}\\\{0}B{0}ar{0}"), InsertMarkerChar(@"Foo\Bar", @"{0}Foo\Bar\\"), InsertMarkerChar(@"Foo\Bar", @"Foo{0}\Bar\\"), InsertMarkerChar(@"Foo\Bar", @"Foo\{0}Bar\\"), InsertMarkerChar(@"Foo\Bar", @"Foo\Bar{0}\\"), InsertMarkerChar(@"Foo\Bar", @"Foo\Bar\\{0}"), InsertMarkerChar(@"Foo\Bar", @"Fo{0}o\B{0}ar\\"), InsertMarkerChar(@"Foo\Bar", @"{0}Fo{0}o{0}\{0}B{0}ar{0}\\{0}"), // If there aren't multiple slashes, any '\uffff' chars should remain. InsertMarkerChar(@"{0}Foo"), InsertMarkerChar(@"Foo{0}"), InsertMarkerChar(@"Fo{0}o"), InsertMarkerChar(@"{0}Fo{0}o{0}"), InsertMarkerChar(@"{0}Foo\"), InsertMarkerChar(@"Foo{0}\"), InsertMarkerChar(@"Fo{0}o\"), InsertMarkerChar(@"{0}Fo{0}o{0}\"), InsertMarkerChar(@"{0}Foo\Bar"), InsertMarkerChar(@"Foo{0}\Bar"), InsertMarkerChar(@"Foo\{0}Bar"), InsertMarkerChar(@"Foo\Bar{0}"), InsertMarkerChar(@"Fo{0}o\Bar"), InsertMarkerChar(@"Foo\B{0}ar"), InsertMarkerChar(@"Fo{0}o\B{0}ar"), InsertMarkerChar(@"{0}Fo{0}o{0}\{0}B{0}ar{0}"), InsertMarkerChar(@"{0}Foo\Bar\"), InsertMarkerChar(@"Foo{0}\Bar\"), InsertMarkerChar(@"Foo\{0}Bar\"), InsertMarkerChar(@"Foo\Bar{0}\"), InsertMarkerChar(@"Fo{0}o\Bar\"), InsertMarkerChar(@"Foo\B{0}ar\"), InsertMarkerChar(@"Fo{0}o\B{0}ar\"), InsertMarkerChar(@"{0}Fo{0}o{0}\{0}B{0}ar{0}\"), }; private const char MarkerChar = '\uffff'; private static object[] InsertMarkerChar(string expected, string format) { string result = string.Format(format, MarkerChar); return new object[] { expected, result }; } private static object[] InsertMarkerChar(string format) { string result = string.Format(format, MarkerChar); string expected = result.TrimEnd('\\'); return new object[] { expected, result }; } protected void CreateTestRegistrySubKey(string expected) { Assert.Equal(0, TestRegistryKey.SubKeyCount); using (RegistryKey key = TestRegistryKey.CreateSubKey(expected)) { Assert.NotNull(key); Assert.Equal(1, TestRegistryKey.SubKeyCount); Assert.Equal(TestRegistryKey.Name + @"\" + expected, key.Name); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Xunit; namespace Microsoft.Win32.RegistryTests { public abstract class RegistryTestsBase : IDisposable { protected string TestRegistryKeyName { get; private set; } protected RegistryKey TestRegistryKey { get; private set; } protected RegistryTestsBase() { // Create a unique name for this test class TestRegistryKeyName = CreateUniqueKeyName(); // Cleanup the key in case a previous run of this test crashed and left // the key behind. The key name is specific enough to corefx that we don't // need to worry about it being a real key on the user's system used // for another purpose. RemoveKeyIfExists(TestRegistryKeyName); // Then create the key. TestRegistryKey = Registry.CurrentUser.CreateSubKey(TestRegistryKeyName, true); Assert.NotNull(TestRegistryKey); } public void Dispose() { TestRegistryKey.Dispose(); RemoveKeyIfExists(TestRegistryKeyName); } private static void RemoveKeyIfExists(string keyName) { RegistryKey rk = Registry.CurrentUser; if (rk.OpenSubKey(keyName) != null) { rk.DeleteSubKeyTree(keyName); Assert.Null(rk.OpenSubKey(keyName)); } } private string CreateUniqueKeyName() { // Create a name to use for this class of tests. The name includes: // - A "corefxtest" prefix to help make it clear to anyone looking at the registry // that these keys are test-only and can be deleted, in case the tests crash and // we end up leaving some keys behind. // - The name of this test class, so as to avoid problems with tests on different test // classes running concurrently return "corefxtest_" + GetType().Name; } public static readonly object[][] TestRegistrySubKeyNames = { new object[] { @"Foo", @"Foo" }, new object[] { @"Foo\Bar", @"Foo\Bar" }, // Multiple/trailing slashes should be removed. new object[] { @"Foo", @"Foo\" }, new object[] { @"Foo", @"Foo\\" }, new object[] { @"Foo", @"Foo\\\" }, new object[] { @"Foo", @"Foo\\\\" }, new object[] { @"Foo\Bar", @"Foo\\Bar" }, new object[] { @"Foo\Bar", @"Foo\\\Bar" }, new object[] { @"Foo\Bar", @"Foo\\\\Bar" }, new object[] { @"Foo\Bar", @"Foo\Bar\" }, new object[] { @"Foo\Bar", @"Foo\Bar\\" }, new object[] { @"Foo\Bar", @"Foo\Bar\\\" }, new object[] { @"Foo\Bar", @"Foo\\Bar\" }, new object[] { @"Foo\Bar", @"Foo\\Bar\\" }, new object[] { @"Foo\Bar", @"Foo\\Bar\\\" }, new object[] { @"Foo\Bar", @"Foo\\\Bar\\\" }, new object[] { @"Foo\Bar", @"Foo\\\\Bar\\\\" }, // The name fix-up implementation uses a mark-and-sweep approach. // If there are multiple slashes, any extra slash chars will be // replaced with a marker char ('\uffff'), and then all '\uffff' // chars will be removed, including any pre-existing '\uffff' chars. InsertMarkerChar(@"Foo", @"{0}Foo\\"), InsertMarkerChar(@"Foo", @"Foo{0}\\"), InsertMarkerChar(@"Foo", @"Foo\\{0}"), InsertMarkerChar(@"Foo", @"Fo{0}o\\"), InsertMarkerChar(@"Foo", @"{0}Fo{0}o{0}\\{0}"), InsertMarkerChar(@"Foo", @"{0}Foo\\\"), InsertMarkerChar(@"Foo", @"Foo{0}\\\"), InsertMarkerChar(@"Foo", @"Foo\\\{0}"), InsertMarkerChar(@"Foo", @"Fo{0}o\\\"), InsertMarkerChar(@"Foo", @"{0}Fo{0}o{0}\\\{0}"), InsertMarkerChar(@"Foo\Bar", @"{0}Foo\\Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo{0}\\Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo\\{0}Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo\\Bar{0}"), InsertMarkerChar(@"Foo\Bar", @"Fo{0}o\\Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo\\B{0}ar"), InsertMarkerChar(@"Foo\Bar", @"Fo{0}o\\B{0}ar"), InsertMarkerChar(@"Foo\Bar", @"{0}Fo{0}o{0}\\{0}B{0}ar{0}"), InsertMarkerChar(@"Foo\Bar", @"{0}Foo\\\Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo{0}\\\Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo\\\{0}Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo\\\Bar{0}"), InsertMarkerChar(@"Foo\Bar", @"Fo{0}o\\\Bar"), InsertMarkerChar(@"Foo\Bar", @"Foo\\\B{0}ar"), InsertMarkerChar(@"Foo\Bar", @"Fo{0}o\\\B{0}ar"), InsertMarkerChar(@"Foo\Bar", @"{0}Fo{0}o{0}\\\{0}B{0}ar{0}"), InsertMarkerChar(@"Foo\Bar", @"{0}Foo\Bar\\"), InsertMarkerChar(@"Foo\Bar", @"Foo{0}\Bar\\"), InsertMarkerChar(@"Foo\Bar", @"Foo\{0}Bar\\"), InsertMarkerChar(@"Foo\Bar", @"Foo\Bar{0}\\"), InsertMarkerChar(@"Foo\Bar", @"Foo\Bar\\{0}"), InsertMarkerChar(@"Foo\Bar", @"Fo{0}o\B{0}ar\\"), InsertMarkerChar(@"Foo\Bar", @"{0}Fo{0}o{0}\{0}B{0}ar{0}\\{0}"), // If there aren't multiple slashes, any '\uffff' chars should remain. InsertMarkerChar(@"{0}Foo"), InsertMarkerChar(@"Foo{0}"), InsertMarkerChar(@"Fo{0}o"), InsertMarkerChar(@"{0}Fo{0}o{0}"), InsertMarkerChar(@"{0}Foo\"), InsertMarkerChar(@"Foo{0}\"), InsertMarkerChar(@"Fo{0}o\"), InsertMarkerChar(@"{0}Fo{0}o{0}\"), InsertMarkerChar(@"{0}Foo\Bar"), InsertMarkerChar(@"Foo{0}\Bar"), InsertMarkerChar(@"Foo\{0}Bar"), InsertMarkerChar(@"Foo\Bar{0}"), InsertMarkerChar(@"Fo{0}o\Bar"), InsertMarkerChar(@"Foo\B{0}ar"), InsertMarkerChar(@"Fo{0}o\B{0}ar"), InsertMarkerChar(@"{0}Fo{0}o{0}\{0}B{0}ar{0}"), InsertMarkerChar(@"{0}Foo\Bar\"), InsertMarkerChar(@"Foo{0}\Bar\"), InsertMarkerChar(@"Foo\{0}Bar\"), InsertMarkerChar(@"Foo\Bar{0}\"), InsertMarkerChar(@"Fo{0}o\Bar\"), InsertMarkerChar(@"Foo\B{0}ar\"), InsertMarkerChar(@"Fo{0}o\B{0}ar\"), InsertMarkerChar(@"{0}Fo{0}o{0}\{0}B{0}ar{0}\"), }; private const char MarkerChar = '\uffff'; private static object[] InsertMarkerChar(string expected, string format) { string result = string.Format(format, MarkerChar); return new object[] { expected, result }; } private static object[] InsertMarkerChar(string format) { string result = string.Format(format, MarkerChar); string expected = result.TrimEnd('\\'); return new object[] { expected, result }; } protected void CreateTestRegistrySubKey(string expected) { Assert.Equal(0, TestRegistryKey.SubKeyCount); using (RegistryKey key = TestRegistryKey.CreateSubKey(expected)) { Assert.NotNull(key); Assert.Equal(1, TestRegistryKey.SubKeyCount); Assert.Equal(TestRegistryKey.Name + @"\" + expected, key.Name); } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="throwinfinallyrecursive_20.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="throwinfinallyrecursive_20.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/HardwareIntrinsics/General/Vector256/Max.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; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void MaxInt32() { var test = new VectorBinaryOpTest__MaxInt32(); // 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__MaxInt32 { 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 != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public 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(VectorBinaryOpTest__MaxInt32 testClass) { var result = Vector256.Max(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__MaxInt32() { 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 VectorBinaryOpTest__MaxInt32() { 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, new Int32[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Max( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<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 method = typeof(Vector256).GetMethod(nameof(Vector256.Max), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Max), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int32)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Max( _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<Vector256<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Vector256.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__MaxInt32(); var result = Vector256.Max(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 = Vector256.Max(_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 = Vector256.Max(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(Vector256<Int32> op1, Vector256<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<Vector256<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<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] > right[0]) ? left[0] : right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] > right[i]) ? left[i] : right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Max)}<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: ({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 MaxInt32() { var test = new VectorBinaryOpTest__MaxInt32(); // 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__MaxInt32 { 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 != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public 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(VectorBinaryOpTest__MaxInt32 testClass) { var result = Vector256.Max(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__MaxInt32() { 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 VectorBinaryOpTest__MaxInt32() { 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, new Int32[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Max( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<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 method = typeof(Vector256).GetMethod(nameof(Vector256.Max), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Max), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int32)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Max( _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<Vector256<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Vector256.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__MaxInt32(); var result = Vector256.Max(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 = Vector256.Max(_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 = Vector256.Max(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(Vector256<Int32> op1, Vector256<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<Vector256<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<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] > right[0]) ? left[0] : right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] > right[i]) ? left[i] : right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Max)}<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: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/Microsoft.Extensions.Caching.Memory/src/Microsoft.Extensions.Caching.Memory.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <Nullable>enable</Nullable> <EnableDefaultItems>true</EnableDefaultItems> <!-- Use targeting pack references instead of granular ones in the project file. --> <DisableImplicitAssemblyReferences>false</DisableImplicitAssemblyReferences> <IsPackable>true</IsPackable> <PackageDescription>In-memory cache implementation of Microsoft.Extensions.Caching.Memory.IMemoryCache.</PackageDescription> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Caching.Abstractions\src\Microsoft.Extensions.Caching.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.DependencyInjection.Abstractions\src\Microsoft.Extensions.DependencyInjection.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging.Abstractions\src\Microsoft.Extensions.Logging.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Options\src\Microsoft.Extensions.Options.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Primitives\src\Microsoft.Extensions.Primitives.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'"> <PackageReference Include="System.ValueTuple" Version="$(SystemValueTupleVersion)" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <Nullable>enable</Nullable> <EnableDefaultItems>true</EnableDefaultItems> <!-- Use targeting pack references instead of granular ones in the project file. --> <DisableImplicitAssemblyReferences>false</DisableImplicitAssemblyReferences> <IsPackable>true</IsPackable> <PackageDescription>In-memory cache implementation of Microsoft.Extensions.Caching.Memory.IMemoryCache.</PackageDescription> </PropertyGroup> <ItemGroup> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Caching.Abstractions\src\Microsoft.Extensions.Caching.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.DependencyInjection.Abstractions\src\Microsoft.Extensions.DependencyInjection.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging.Abstractions\src\Microsoft.Extensions.Logging.Abstractions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Options\src\Microsoft.Extensions.Options.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Primitives\src\Microsoft.Extensions.Primitives.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'"> <PackageReference Include="System.ValueTuple" Version="$(SystemValueTupleVersion)" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.DirectoryServices.AccountManagement/tests/PrincipalContextTests.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.Runtime.InteropServices; using Xunit; namespace System.DirectoryServices.AccountManagement.Tests { public class PrincipalContextTests { [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore), nameof(PlatformDetection.IsNotWindowsIoTCore))] [ActiveIssue("https://github.com/dotnet/runtime/issues/34442", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public void Ctor_ContextType() { var context = new PrincipalContext(ContextType.Machine); Assert.Equal(ContextType.Machine, context.ContextType); Assert.Null(context.Name); Assert.Null(context.Container); Assert.Null(context.UserName); Assert.Equal(ContextOptions.Negotiate, context.Options); Assert.NotNull(context.ConnectedServer); Assert.Equal(Environment.MachineName, context.ConnectedServer); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] [InlineData(ContextType.Machine, null)] [InlineData(ContextType.Machine, "")] [InlineData(ContextType.Machine, "\0")] [InlineData(ContextType.Machine, "name")] public void Ctor_ContextType_Name(ContextType contextType, string name) { var context = new PrincipalContext(contextType, name); Assert.Equal(contextType, context.ContextType); Assert.Equal(name, context.Name); Assert.Null(context.Container); Assert.Null(context.UserName); Assert.Equal(ContextOptions.Negotiate, context.Options); if (name != null) { Assert.Throws<COMException>(() => context.ConnectedServer); } else { Assert.NotNull(context.ConnectedServer); Assert.Equal(Environment.MachineName, context.ConnectedServer); } } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] [InlineData(ContextType.Machine, null, null)] [InlineData(ContextType.Machine, "", null)] [InlineData(ContextType.Machine, "\0", null)] [InlineData(ContextType.Machine, "name", null)] public void Ctor_ContextType_Name_Container(ContextType contextType, string name, string container) { var context = new PrincipalContext(contextType, name, container); Assert.Equal(contextType, context.ContextType); Assert.Equal(name, context.Name); Assert.Equal(container, context.Container); Assert.Null(context.UserName); Assert.Equal(ContextOptions.Negotiate, context.Options); if (name != null) { Assert.Throws<COMException>(() => context.ConnectedServer); } else { Assert.NotNull(context.ConnectedServer); Assert.Equal(Environment.MachineName, context.ConnectedServer); } } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] [InlineData(ContextType.Machine, null, null, ContextOptions.Negotiate)] [InlineData(ContextType.Machine, "", null, ContextOptions.Negotiate)] [InlineData(ContextType.Machine, "\0", null, ContextOptions.Negotiate)] [InlineData(ContextType.Machine, "name", null, ContextOptions.Negotiate)] public void Ctor_ContextType_Name_Container_Options(ContextType contextType, string name, string container, ContextOptions options) { var context = new PrincipalContext(contextType, name, container, options); Assert.Equal(contextType, context.ContextType); Assert.Equal(name, context.Name); Assert.Equal(container, context.Container); Assert.Null(context.UserName); Assert.Equal(ContextOptions.Negotiate, context.Options); if (name != null) { Assert.Throws<COMException>(() => context.ConnectedServer); } else { Assert.NotNull(context.ConnectedServer); Assert.Equal(Environment.MachineName, context.ConnectedServer); } } [ActiveIssue("https://github.com/dotnet/runtime/issues/23448")] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] [InlineData(ContextType.Machine, null, "userName", "password")] [InlineData(ContextType.Machine, "", "", "")] [InlineData(ContextType.Machine, "\0", "userName", "")] [InlineData(ContextType.Machine, "name", "\0", "\0")] public void Ctor_ContextType_Name_UserName_Password(ContextType contextType, string name, string userName, string password) { var context = new PrincipalContext(contextType, name, userName, password); Assert.Equal(contextType, context.ContextType); Assert.Equal(name, context.Name); Assert.Null(context.Container); Assert.Equal(userName, context.UserName); Assert.Equal(ContextOptions.Negotiate, context.Options); if (name != null) { Assert.Throws<COMException>(() => context.ConnectedServer); } else { Assert.Throws<Exception>(() => context.ConnectedServer); } } [ActiveIssue("https://github.com/dotnet/runtime/issues/23448")] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] [InlineData(ContextType.Machine, null, null, "userName", "password")] [InlineData(ContextType.Machine, "", null, "", "")] [InlineData(ContextType.Machine, "\0", null, "userName", "")] [InlineData(ContextType.Machine, "name", null, "\0", "\0")] public void Ctor_ContextType_Name_Container_UserName_Password(ContextType contextType, string name, string container, string userName, string password) { var context = new PrincipalContext(contextType, name, container, userName, password); Assert.Equal(contextType, context.ContextType); Assert.Equal(name, context.Name); Assert.Equal(container, context.Container); Assert.Equal(userName, context.UserName); Assert.Equal(ContextOptions.Negotiate, context.Options); if (name != null) { Assert.Throws<COMException>(() => context.ConnectedServer); } else { Assert.Throws<Exception>(() => context.ConnectedServer); } } [Theory] [InlineData(ContextType.Machine - 1)] [InlineData(ContextType.ApplicationDirectory + 1)] public void Ctor_InvalidContexType_ThrowsInvalidEnumArgumentException(ContextType contextType) { AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType)); AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType, "name")); AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType, "name", "container")); AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType, "name", "container", ContextOptions.Negotiate)); AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType, "name", "userName", "password")); AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType, "name", "container", "userName", "password")); AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType, "name", "container", ContextOptions.Negotiate, "userName", "password")); } [Fact] public void Ctor_DomainContextType_ThrowsPrincipalServerDownException() { if (!PlatformDetection.IsDomainJoinedMachine) { // The machine is not connected to a domain. we expect PrincipalContext(ContextType.Domain) to throw Assert.Throws<PrincipalServerDownException>(() => new PrincipalContext(ContextType.Domain)); } } [Fact] public void Ctor_ActiveDirectoryContextTypeWithoutNameAndContainer_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory)); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory, "name", "")); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory, "name", null)); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory, "name")); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory, "name", "userName", "password")); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory, "name", "", "userName", "password")); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory, "name", null, "userName", "password")); } [Theory] [InlineData((ContextOptions)(-1))] [InlineData((ContextOptions)int.MaxValue)] public void Ctor_InvalidOptions_ThrowsInvalidEnumArgumentException(ContextOptions options) { AssertExtensions.Throws<InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.Machine, "name", null, options)); AssertExtensions.Throws<InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.Domain, "name", null, options)); AssertExtensions.Throws<InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.ApplicationDirectory, "name", "container", options)); AssertExtensions.Throws<InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.Machine, "name", null, options, "userName", "password")); AssertExtensions.Throws<InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.Domain, "name", null, options, "userName", "password")); AssertExtensions.Throws<InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.ApplicationDirectory, "name", "container", options, "userName", "password")); } [Theory] [InlineData(ContextType.Machine, ContextOptions.Sealing)] [InlineData(ContextType.Machine, ContextOptions.SecureSocketLayer)] [InlineData(ContextType.Machine, ContextOptions.ServerBind)] [InlineData(ContextType.Machine, ContextOptions.Signing)] [InlineData(ContextType.Machine, ContextOptions.SimpleBind)] [InlineData(ContextType.ApplicationDirectory, ContextOptions.Negotiate)] [InlineData(ContextType.Domain, ContextOptions.Negotiate | ContextOptions.SimpleBind | ContextOptions.Signing)] public void Ctor_MachineAndNonNegotiateContextOptions_ThrowsArgumentException(ContextType contextType, ContextOptions options) { AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(contextType, "name", null, options)); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(contextType, "name", null, options, "userName", "password")); } [Fact] public void Ctor_MachineContextTypeWithContainer_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.Machine, "name", "container")); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.Machine, "name", "container", "userName", "password")); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.Machine, "name", "container", ContextOptions.Negotiate, "userName", "password")); } [Theory] [InlineData(null, "password")] [InlineData("userName", null)] public void Ctor_InconsistentUserNameAndPassword_ThrowsArgumentException(string userName, string password) { AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.Machine, "name", userName, password)); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.Machine, "name", null, userName, password)); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.Machine, "name", null, ContextOptions.Negotiate, userName, password)); } [Fact] public void ConnectedServer_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.ConnectedServer); } [Fact] public void Container_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.Container); } [Fact] public void ContextType_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.ContextType); } [Fact] public void Name_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.Name); } [Fact] public void Options_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.Options); } [Fact] public void UserName_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.UserName); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore), nameof(PlatformDetection.IsNotWindowsIoTCore))] [ActiveIssue("https://github.com/dotnet/runtime/issues/34442", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] [InlineData(null, null, true)] [InlineData("", "", false)] public void ValidateCredentials_Invoke_ReturnsExpected(string userName, string password, bool expected) { var context = new PrincipalContext(ContextType.Machine); Assert.Equal(expected, context.ValidateCredentials(userName, password)); Assert.Equal(expected, context.ValidateCredentials(userName, password, ContextOptions.Negotiate)); } [ActiveIssue("https://github.com/dotnet/runtime/issues/23448")] [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] public void ValidateCredentials_InvalidUserName_ThrowsException() { var context = new PrincipalContext(ContextType.Machine); Assert.Throws<Exception>(() => context.ValidateCredentials("\0", "password")); } [ActiveIssue("https://github.com/dotnet/runtime/issues/23448")] [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] public void ValidateCredentials_IncorrectUserNamePassword_ThrowsException() { var context = new PrincipalContext(ContextType.Machine); Assert.Throws<Exception>(() => context.ValidateCredentials("userName", "password")); } [Theory] [InlineData(null, "password")] [InlineData("userName", null)] public void ValidateCredentials_InvalidUsernamePasswordCombo_ThrowsArgumentException(string userName, string password) { var context = new PrincipalContext(ContextType.Machine); AssertExtensions.Throws<ArgumentException>(null, () => context.ValidateCredentials(userName, password)); AssertExtensions.Throws<ArgumentException>(null, () => context.ValidateCredentials(userName, password, ContextOptions.Negotiate)); } [Theory] [InlineData(ContextOptions.Sealing)] [InlineData(ContextOptions.SecureSocketLayer)] [InlineData(ContextOptions.ServerBind)] [InlineData(ContextOptions.Signing)] [InlineData(ContextOptions.SimpleBind)] public void ValidateCredentials_InvalidOptions_ThrowsArgumentException(ContextOptions options) { var context = new PrincipalContext(ContextType.Machine); AssertExtensions.Throws<ArgumentException>(null, () => context.ValidateCredentials("userName", "password", options)); } [Fact] public void ValidateCredentials_Disposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.ValidateCredentials(null, null)); Assert.Throws<ObjectDisposedException>(() => context.ValidateCredentials(null, null, ContextOptions.Negotiate)); } } }
// 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.Runtime.InteropServices; using Xunit; namespace System.DirectoryServices.AccountManagement.Tests { public class PrincipalContextTests { [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore), nameof(PlatformDetection.IsNotWindowsIoTCore))] [ActiveIssue("https://github.com/dotnet/runtime/issues/34442", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] public void Ctor_ContextType() { var context = new PrincipalContext(ContextType.Machine); Assert.Equal(ContextType.Machine, context.ContextType); Assert.Null(context.Name); Assert.Null(context.Container); Assert.Null(context.UserName); Assert.Equal(ContextOptions.Negotiate, context.Options); Assert.NotNull(context.ConnectedServer); Assert.Equal(Environment.MachineName, context.ConnectedServer); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] [InlineData(ContextType.Machine, null)] [InlineData(ContextType.Machine, "")] [InlineData(ContextType.Machine, "\0")] [InlineData(ContextType.Machine, "name")] public void Ctor_ContextType_Name(ContextType contextType, string name) { var context = new PrincipalContext(contextType, name); Assert.Equal(contextType, context.ContextType); Assert.Equal(name, context.Name); Assert.Null(context.Container); Assert.Null(context.UserName); Assert.Equal(ContextOptions.Negotiate, context.Options); if (name != null) { Assert.Throws<COMException>(() => context.ConnectedServer); } else { Assert.NotNull(context.ConnectedServer); Assert.Equal(Environment.MachineName, context.ConnectedServer); } } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] [InlineData(ContextType.Machine, null, null)] [InlineData(ContextType.Machine, "", null)] [InlineData(ContextType.Machine, "\0", null)] [InlineData(ContextType.Machine, "name", null)] public void Ctor_ContextType_Name_Container(ContextType contextType, string name, string container) { var context = new PrincipalContext(contextType, name, container); Assert.Equal(contextType, context.ContextType); Assert.Equal(name, context.Name); Assert.Equal(container, context.Container); Assert.Null(context.UserName); Assert.Equal(ContextOptions.Negotiate, context.Options); if (name != null) { Assert.Throws<COMException>(() => context.ConnectedServer); } else { Assert.NotNull(context.ConnectedServer); Assert.Equal(Environment.MachineName, context.ConnectedServer); } } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] [InlineData(ContextType.Machine, null, null, ContextOptions.Negotiate)] [InlineData(ContextType.Machine, "", null, ContextOptions.Negotiate)] [InlineData(ContextType.Machine, "\0", null, ContextOptions.Negotiate)] [InlineData(ContextType.Machine, "name", null, ContextOptions.Negotiate)] public void Ctor_ContextType_Name_Container_Options(ContextType contextType, string name, string container, ContextOptions options) { var context = new PrincipalContext(contextType, name, container, options); Assert.Equal(contextType, context.ContextType); Assert.Equal(name, context.Name); Assert.Equal(container, context.Container); Assert.Null(context.UserName); Assert.Equal(ContextOptions.Negotiate, context.Options); if (name != null) { Assert.Throws<COMException>(() => context.ConnectedServer); } else { Assert.NotNull(context.ConnectedServer); Assert.Equal(Environment.MachineName, context.ConnectedServer); } } [ActiveIssue("https://github.com/dotnet/runtime/issues/23448")] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] [InlineData(ContextType.Machine, null, "userName", "password")] [InlineData(ContextType.Machine, "", "", "")] [InlineData(ContextType.Machine, "\0", "userName", "")] [InlineData(ContextType.Machine, "name", "\0", "\0")] public void Ctor_ContextType_Name_UserName_Password(ContextType contextType, string name, string userName, string password) { var context = new PrincipalContext(contextType, name, userName, password); Assert.Equal(contextType, context.ContextType); Assert.Equal(name, context.Name); Assert.Null(context.Container); Assert.Equal(userName, context.UserName); Assert.Equal(ContextOptions.Negotiate, context.Options); if (name != null) { Assert.Throws<COMException>(() => context.ConnectedServer); } else { Assert.Throws<Exception>(() => context.ConnectedServer); } } [ActiveIssue("https://github.com/dotnet/runtime/issues/23448")] [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] [InlineData(ContextType.Machine, null, null, "userName", "password")] [InlineData(ContextType.Machine, "", null, "", "")] [InlineData(ContextType.Machine, "\0", null, "userName", "")] [InlineData(ContextType.Machine, "name", null, "\0", "\0")] public void Ctor_ContextType_Name_Container_UserName_Password(ContextType contextType, string name, string container, string userName, string password) { var context = new PrincipalContext(contextType, name, container, userName, password); Assert.Equal(contextType, context.ContextType); Assert.Equal(name, context.Name); Assert.Equal(container, context.Container); Assert.Equal(userName, context.UserName); Assert.Equal(ContextOptions.Negotiate, context.Options); if (name != null) { Assert.Throws<COMException>(() => context.ConnectedServer); } else { Assert.Throws<Exception>(() => context.ConnectedServer); } } [Theory] [InlineData(ContextType.Machine - 1)] [InlineData(ContextType.ApplicationDirectory + 1)] public void Ctor_InvalidContexType_ThrowsInvalidEnumArgumentException(ContextType contextType) { AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType)); AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType, "name")); AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType, "name", "container")); AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType, "name", "container", ContextOptions.Negotiate)); AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType, "name", "userName", "password")); AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType, "name", "container", "userName", "password")); AssertExtensions.Throws<InvalidEnumArgumentException>("contextType", () => new PrincipalContext(contextType, "name", "container", ContextOptions.Negotiate, "userName", "password")); } [Fact] public void Ctor_DomainContextType_ThrowsPrincipalServerDownException() { if (!PlatformDetection.IsDomainJoinedMachine) { // The machine is not connected to a domain. we expect PrincipalContext(ContextType.Domain) to throw Assert.Throws<PrincipalServerDownException>(() => new PrincipalContext(ContextType.Domain)); } } [Fact] public void Ctor_ActiveDirectoryContextTypeWithoutNameAndContainer_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory)); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory, "name", "")); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory, "name", null)); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory, "name")); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory, "name", "userName", "password")); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory, "name", "", "userName", "password")); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.ApplicationDirectory, "name", null, "userName", "password")); } [Theory] [InlineData((ContextOptions)(-1))] [InlineData((ContextOptions)int.MaxValue)] public void Ctor_InvalidOptions_ThrowsInvalidEnumArgumentException(ContextOptions options) { AssertExtensions.Throws<InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.Machine, "name", null, options)); AssertExtensions.Throws<InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.Domain, "name", null, options)); AssertExtensions.Throws<InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.ApplicationDirectory, "name", "container", options)); AssertExtensions.Throws<InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.Machine, "name", null, options, "userName", "password")); AssertExtensions.Throws<InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.Domain, "name", null, options, "userName", "password")); AssertExtensions.Throws<InvalidEnumArgumentException>("options", () => new PrincipalContext(ContextType.ApplicationDirectory, "name", "container", options, "userName", "password")); } [Theory] [InlineData(ContextType.Machine, ContextOptions.Sealing)] [InlineData(ContextType.Machine, ContextOptions.SecureSocketLayer)] [InlineData(ContextType.Machine, ContextOptions.ServerBind)] [InlineData(ContextType.Machine, ContextOptions.Signing)] [InlineData(ContextType.Machine, ContextOptions.SimpleBind)] [InlineData(ContextType.ApplicationDirectory, ContextOptions.Negotiate)] [InlineData(ContextType.Domain, ContextOptions.Negotiate | ContextOptions.SimpleBind | ContextOptions.Signing)] public void Ctor_MachineAndNonNegotiateContextOptions_ThrowsArgumentException(ContextType contextType, ContextOptions options) { AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(contextType, "name", null, options)); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(contextType, "name", null, options, "userName", "password")); } [Fact] public void Ctor_MachineContextTypeWithContainer_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.Machine, "name", "container")); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.Machine, "name", "container", "userName", "password")); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.Machine, "name", "container", ContextOptions.Negotiate, "userName", "password")); } [Theory] [InlineData(null, "password")] [InlineData("userName", null)] public void Ctor_InconsistentUserNameAndPassword_ThrowsArgumentException(string userName, string password) { AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.Machine, "name", userName, password)); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.Machine, "name", null, userName, password)); AssertExtensions.Throws<ArgumentException>(null, () => new PrincipalContext(ContextType.Machine, "name", null, ContextOptions.Negotiate, userName, password)); } [Fact] public void ConnectedServer_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.ConnectedServer); } [Fact] public void Container_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.Container); } [Fact] public void ContextType_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.ContextType); } [Fact] public void Name_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.Name); } [Fact] public void Options_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.Options); } [Fact] public void UserName_GetWhenDisposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.UserName); } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore), nameof(PlatformDetection.IsNotWindowsIoTCore))] [ActiveIssue("https://github.com/dotnet/runtime/issues/34442", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] [InlineData(null, null, true)] [InlineData("", "", false)] public void ValidateCredentials_Invoke_ReturnsExpected(string userName, string password, bool expected) { var context = new PrincipalContext(ContextType.Machine); Assert.Equal(expected, context.ValidateCredentials(userName, password)); Assert.Equal(expected, context.ValidateCredentials(userName, password, ContextOptions.Negotiate)); } [ActiveIssue("https://github.com/dotnet/runtime/issues/23448")] [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] public void ValidateCredentials_InvalidUserName_ThrowsException() { var context = new PrincipalContext(ContextType.Machine); Assert.Throws<Exception>(() => context.ValidateCredentials("\0", "password")); } [ActiveIssue("https://github.com/dotnet/runtime/issues/23448")] [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoNorServerCore))] [OuterLoop("Takes too long on domain joined machines")] public void ValidateCredentials_IncorrectUserNamePassword_ThrowsException() { var context = new PrincipalContext(ContextType.Machine); Assert.Throws<Exception>(() => context.ValidateCredentials("userName", "password")); } [Theory] [InlineData(null, "password")] [InlineData("userName", null)] public void ValidateCredentials_InvalidUsernamePasswordCombo_ThrowsArgumentException(string userName, string password) { var context = new PrincipalContext(ContextType.Machine); AssertExtensions.Throws<ArgumentException>(null, () => context.ValidateCredentials(userName, password)); AssertExtensions.Throws<ArgumentException>(null, () => context.ValidateCredentials(userName, password, ContextOptions.Negotiate)); } [Theory] [InlineData(ContextOptions.Sealing)] [InlineData(ContextOptions.SecureSocketLayer)] [InlineData(ContextOptions.ServerBind)] [InlineData(ContextOptions.Signing)] [InlineData(ContextOptions.SimpleBind)] public void ValidateCredentials_InvalidOptions_ThrowsArgumentException(ContextOptions options) { var context = new PrincipalContext(ContextType.Machine); AssertExtensions.Throws<ArgumentException>(null, () => context.ValidateCredentials("userName", "password", options)); } [Fact] public void ValidateCredentials_Disposed_ThrowsObjectDisposedException() { var context = new PrincipalContext(ContextType.Machine); context.Dispose(); Assert.Throws<ObjectDisposedException>(() => context.ValidateCredentials(null, null)); Assert.Throws<ObjectDisposedException>(() => context.ValidateCredentials(null, null, ContextOptions.Negotiate)); } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/Common/src/Extensions/EmptyDisposable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.Extensions.FileProviders { internal sealed class EmptyDisposable : IDisposable { public static EmptyDisposable Instance { get; } = new EmptyDisposable(); private EmptyDisposable() { } public void 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; namespace Microsoft.Extensions.FileProviders { internal sealed class EmptyDisposable : IDisposable { public static EmptyDisposable Instance { get; } = new EmptyDisposable(); private EmptyDisposable() { } public void Dispose() { } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/coreclr/gc/gcconfig.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "common.h" #include "gcenv.h" #include "gc.h" #define BOOL_CONFIG(name, unused_private_key, unused_public_key, default, unused_doc) \ bool GCConfig::Get##name() { return s_##name; } \ bool GCConfig::s_##name = default; #define INT_CONFIG(name, unused_private_key, unused_public_key, default, unused_doc) \ int64_t GCConfig::Get##name() { return s_##name; } \ int64_t GCConfig::s_##name = default; // String configs are not cached because 1) they are rare and // not on hot paths and 2) they involve transfers of ownership // of EE-allocated strings, which is potentially complicated. #define STRING_CONFIG(name, private_key, public_key, unused_doc) \ GCConfigStringHolder GCConfig::Get##name() \ { \ const char* resultStr = nullptr; \ GCToEEInterface::GetStringConfigValue(private_key, public_key, &resultStr); \ return GCConfigStringHolder(resultStr); \ } GC_CONFIGURATION_KEYS #undef BOOL_CONFIG #undef INT_CONFIG #undef STRING_CONFIG void GCConfig::Initialize() { #define BOOL_CONFIG(name, private_key, public_key, default, unused_doc) \ GCToEEInterface::GetBooleanConfigValue(private_key, public_key, &s_##name); #define INT_CONFIG(name, private_key, public_key, default, unused_doc) \ GCToEEInterface::GetIntConfigValue(private_key, public_key, &s_##name); #define STRING_CONFIG(unused_name, unused_private_key, unused_public_key, unused_doc) GC_CONFIGURATION_KEYS #undef BOOL_CONFIG #undef INT_CONFIG #undef STRING_CONFIG } // Parse an integer index or range of two indices separated by '-'. // Updates the config_string to point to the first character after the parsed part bool ParseIndexOrRange(const char** config_string, size_t* start_index, size_t* end_index) { char* number_end; size_t start = strtoul(*config_string, &number_end, 10); if (number_end == *config_string) { // No number found, invalid format return false; } size_t end = start; if (*number_end == '-') { char* range_end_start = number_end + 1; end = strtoul(range_end_start, &number_end, 10); if (number_end == range_end_start) { // No number found, invalid format return false; } } *start_index = start; *end_index = end; *config_string = number_end; return true; } bool ParseGCHeapAffinitizeRanges(const char* cpu_index_ranges, AffinitySet* config_affinity_set) { bool success = true; // Unix: // The cpu index ranges is a comma separated list of indices or ranges of indices (e.g. 1-5). // Example 1,3,5,7-9,12 // Windows: // The cpu index ranges is a comma separated list of group-annotated indices or ranges of indices. // The group number always prefixes index or range and is followed by colon. // Example 0:1,0:3,0:5,1:7-9,1:12 if (cpu_index_ranges != NULL) { const char* number_end = cpu_index_ranges; do { size_t start_index, end_index; if (!GCToOSInterface::ParseGCHeapAffinitizeRangesEntry(&cpu_index_ranges, &start_index, &end_index)) { break; } if ((start_index >= MAX_SUPPORTED_CPUS) || (end_index >= MAX_SUPPORTED_CPUS) || (end_index < start_index)) { // Invalid CPU index values or range break; } for (size_t i = start_index; i <= end_index; i++) { config_affinity_set->Add(i); } number_end = cpu_index_ranges; cpu_index_ranges++; } while (*number_end == ','); success = (*number_end == '\0'); } return success; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "common.h" #include "gcenv.h" #include "gc.h" #define BOOL_CONFIG(name, unused_private_key, unused_public_key, default, unused_doc) \ bool GCConfig::Get##name() { return s_##name; } \ bool GCConfig::s_##name = default; #define INT_CONFIG(name, unused_private_key, unused_public_key, default, unused_doc) \ int64_t GCConfig::Get##name() { return s_##name; } \ int64_t GCConfig::s_##name = default; // String configs are not cached because 1) they are rare and // not on hot paths and 2) they involve transfers of ownership // of EE-allocated strings, which is potentially complicated. #define STRING_CONFIG(name, private_key, public_key, unused_doc) \ GCConfigStringHolder GCConfig::Get##name() \ { \ const char* resultStr = nullptr; \ GCToEEInterface::GetStringConfigValue(private_key, public_key, &resultStr); \ return GCConfigStringHolder(resultStr); \ } GC_CONFIGURATION_KEYS #undef BOOL_CONFIG #undef INT_CONFIG #undef STRING_CONFIG void GCConfig::Initialize() { #define BOOL_CONFIG(name, private_key, public_key, default, unused_doc) \ GCToEEInterface::GetBooleanConfigValue(private_key, public_key, &s_##name); #define INT_CONFIG(name, private_key, public_key, default, unused_doc) \ GCToEEInterface::GetIntConfigValue(private_key, public_key, &s_##name); #define STRING_CONFIG(unused_name, unused_private_key, unused_public_key, unused_doc) GC_CONFIGURATION_KEYS #undef BOOL_CONFIG #undef INT_CONFIG #undef STRING_CONFIG } // Parse an integer index or range of two indices separated by '-'. // Updates the config_string to point to the first character after the parsed part bool ParseIndexOrRange(const char** config_string, size_t* start_index, size_t* end_index) { char* number_end; size_t start = strtoul(*config_string, &number_end, 10); if (number_end == *config_string) { // No number found, invalid format return false; } size_t end = start; if (*number_end == '-') { char* range_end_start = number_end + 1; end = strtoul(range_end_start, &number_end, 10); if (number_end == range_end_start) { // No number found, invalid format return false; } } *start_index = start; *end_index = end; *config_string = number_end; return true; } bool ParseGCHeapAffinitizeRanges(const char* cpu_index_ranges, AffinitySet* config_affinity_set) { bool success = true; // Unix: // The cpu index ranges is a comma separated list of indices or ranges of indices (e.g. 1-5). // Example 1,3,5,7-9,12 // Windows: // The cpu index ranges is a comma separated list of group-annotated indices or ranges of indices. // The group number always prefixes index or range and is followed by colon. // Example 0:1,0:3,0:5,1:7-9,1:12 if (cpu_index_ranges != NULL) { const char* number_end = cpu_index_ranges; do { size_t start_index, end_index; if (!GCToOSInterface::ParseGCHeapAffinitizeRangesEntry(&cpu_index_ranges, &start_index, &end_index)) { break; } if ((start_index >= MAX_SUPPORTED_CPUS) || (end_index >= MAX_SUPPORTED_CPUS) || (end_index < start_index)) { // Invalid CPU index values or range break; } for (size_t i = start_index; i <= end_index; i++) { config_affinity_set->Add(i); } number_end = cpu_index_ranges; cpu_index_ranges++; } while (*number_end == ','); success = (*number_end == '\0'); } return success; }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/jit64/valuetypes/nullable/castclass/castclass/castclass001.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="castclass001.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="castclass001.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyDoublingWideningSaturateLowerBySelectedScalar.Vector64.Int32.Vector128.Int32.3.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3 testClass) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly byte Imm = 3; private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector64<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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.MultiplyDoublingWideningSaturateLowerBySelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( _clsVar1, _clsVar2, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(pClsVar2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(test._fld1, test._fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(test._fld1, test._fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&test._fld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> firstOp, Vector128<Int32> secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyDoublingWideningSaturate(firstOp[i], secondOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar)}<Int64>(Vector64<Int32>, Vector128<Int32>, 3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3 testClass) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly byte Imm = 3; private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector64<Int32> _fld1; private Vector128<Int32> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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.MultiplyDoublingWideningSaturateLowerBySelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( _clsVar1, _clsVar2, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(pClsVar2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(op1, op2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(test._fld1, test._fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__MultiplyDoublingWideningSaturateLowerBySelectedScalar_Vector64_Int32_Vector128_Int32_3(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(_fld1, _fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) { var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar(test._fld1, test._fld2, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar( AdvSimd.LoadVector64((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&test._fld2)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> firstOp, Vector128<Int32> secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyDoublingWideningSaturate(firstOp[i], secondOp[Imm]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyDoublingWideningSaturateLowerBySelectedScalar)}<Int64>(Vector64<Int32>, Vector128<Int32>, 3): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/HardwareIntrinsics/General/Vector256/Xor.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\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 XorUInt16() { var test = new VectorBinaryOpTest__XorUInt16(); // 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__XorUInt16 { 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, UInt16[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); 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<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<UInt16> _fld1; public Vector256<UInt16> _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<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__XorUInt16 testClass) { var result = Vector256.Xor(_fld1, _fld2); 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<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector256<UInt16> _clsVar1; private static Vector256<UInt16> _clsVar2; private Vector256<UInt16> _fld1; private Vector256<UInt16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__XorUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); } public VectorBinaryOpTest__XorUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Xor( Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt16>>(_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(Vector256).GetMethod(nameof(Vector256.Xor), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Xor), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Xor( _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<Vector256<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr); var result = Vector256.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__XorUInt16(); var result = Vector256.Xor(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 = Vector256.Xor(_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 = Vector256.Xor(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(Vector256<UInt16> op1, Vector256<UInt16> op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (ushort)(left[0] ^ right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (ushort)(left[i] ^ right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Xor)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {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 XorUInt16() { var test = new VectorBinaryOpTest__XorUInt16(); // 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__XorUInt16 { 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, UInt16[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); 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<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<UInt16> _fld1; public Vector256<UInt16> _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<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__XorUInt16 testClass) { var result = Vector256.Xor(_fld1, _fld2); 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<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector256<UInt16> _clsVar1; private static Vector256<UInt16> _clsVar2; private Vector256<UInt16> _fld1; private Vector256<UInt16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__XorUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); } public VectorBinaryOpTest__XorUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Xor( Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt16>>(_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(Vector256).GetMethod(nameof(Vector256.Xor), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Xor), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Xor( _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<Vector256<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr); var result = Vector256.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__XorUInt16(); var result = Vector256.Xor(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 = Vector256.Xor(_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 = Vector256.Xor(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(Vector256<UInt16> op1, Vector256<UInt16> op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (ushort)(left[0] ^ right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (ushort)(left[i] ^ right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Xor)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {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,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Diagnostics.Debug/tests/XunitAssemblyAttributes.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; // Debug tests can conflict with each other since they all share the same output logger (due to the design of Debug). [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; // Debug tests can conflict with each other since they all share the same output logger (due to the design of Debug). [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)]
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/Loader/classloader/generics/Variance/IL/IsInst003.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="IsInst003.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="Lib.ilproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="IsInst003.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="Lib.ilproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/JIT/Intrinsics/MathFloorDouble_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <DebugType>None</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="MathFloorDouble.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <DebugType>None</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="MathFloorDouble.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/FlushResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.IO.Pipelines { /// <summary>Result returned by <see cref="System.IO.Pipelines.PipeWriter.FlushAsync(System.Threading.CancellationToken)" /> call.</summary> public struct FlushResult { internal ResultFlags _resultFlags; /// <summary>Initializes a new instance of <see cref="System.IO.Pipelines.FlushResult" /> struct setting the <see cref="System.IO.Pipelines.FlushResult.IsCanceled" /> and <see cref="System.IO.Pipelines.FlushResult.IsCompleted" /> flags.</summary> /// <param name="isCanceled"><see langword="true" /> to indicate the current <see cref="System.IO.Pipelines.PipeWriter.FlushAsync(System.Threading.CancellationToken)" /> operation that produced this <see cref="System.IO.Pipelines.FlushResult" /> was canceled by <see cref="System.IO.Pipelines.PipeWriter.CancelPendingFlush" />; otherwise, <see langword="false" />.</param> /// <param name="isCompleted"><see langword="true" /> to indicate the reader is no longer reading data written to the <see cref="System.IO.Pipelines.PipeWriter" />.</param> public FlushResult(bool isCanceled, bool isCompleted) { _resultFlags = ResultFlags.None; if (isCanceled) { _resultFlags |= ResultFlags.Canceled; } if (isCompleted) { _resultFlags |= ResultFlags.Completed; } } /// <summary>Gets a value that indicates whether the current <see cref="System.IO.Pipelines.PipeWriter.FlushAsync(System.Threading.CancellationToken)" /> operation was canceled by <see cref="System.IO.Pipelines.PipeWriter.CancelPendingFlush" />.</summary> /// <value><see langword="true" /> if the current <see cref="System.IO.Pipelines.PipeWriter.FlushAsync(System.Threading.CancellationToken)" /> operation was canceled by <see cref="System.IO.Pipelines.PipeWriter.CancelPendingFlush" />; otherwise, <see langword="false" />.</value> public bool IsCanceled => (_resultFlags & ResultFlags.Canceled) != 0; /// <summary>Gets a value that indicates the reader is no longer reading data written to the <see cref="System.IO.Pipelines.PipeWriter" />.</summary> /// <value><see langword="true" /> if the reader is no longer reading data written to the <see cref="System.IO.Pipelines.PipeWriter" />; otherwise, <see langword="false" />.</value> public bool IsCompleted => (_resultFlags & ResultFlags.Completed) != 0; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.IO.Pipelines { /// <summary>Result returned by <see cref="System.IO.Pipelines.PipeWriter.FlushAsync(System.Threading.CancellationToken)" /> call.</summary> public struct FlushResult { internal ResultFlags _resultFlags; /// <summary>Initializes a new instance of <see cref="System.IO.Pipelines.FlushResult" /> struct setting the <see cref="System.IO.Pipelines.FlushResult.IsCanceled" /> and <see cref="System.IO.Pipelines.FlushResult.IsCompleted" /> flags.</summary> /// <param name="isCanceled"><see langword="true" /> to indicate the current <see cref="System.IO.Pipelines.PipeWriter.FlushAsync(System.Threading.CancellationToken)" /> operation that produced this <see cref="System.IO.Pipelines.FlushResult" /> was canceled by <see cref="System.IO.Pipelines.PipeWriter.CancelPendingFlush" />; otherwise, <see langword="false" />.</param> /// <param name="isCompleted"><see langword="true" /> to indicate the reader is no longer reading data written to the <see cref="System.IO.Pipelines.PipeWriter" />.</param> public FlushResult(bool isCanceled, bool isCompleted) { _resultFlags = ResultFlags.None; if (isCanceled) { _resultFlags |= ResultFlags.Canceled; } if (isCompleted) { _resultFlags |= ResultFlags.Completed; } } /// <summary>Gets a value that indicates whether the current <see cref="System.IO.Pipelines.PipeWriter.FlushAsync(System.Threading.CancellationToken)" /> operation was canceled by <see cref="System.IO.Pipelines.PipeWriter.CancelPendingFlush" />.</summary> /// <value><see langword="true" /> if the current <see cref="System.IO.Pipelines.PipeWriter.FlushAsync(System.Threading.CancellationToken)" /> operation was canceled by <see cref="System.IO.Pipelines.PipeWriter.CancelPendingFlush" />; otherwise, <see langword="false" />.</value> public bool IsCanceled => (_resultFlags & ResultFlags.Canceled) != 0; /// <summary>Gets a value that indicates the reader is no longer reading data written to the <see cref="System.IO.Pipelines.PipeWriter" />.</summary> /// <value><see langword="true" /> if the reader is no longer reading data written to the <see cref="System.IO.Pipelines.PipeWriter" />; otherwise, <see langword="false" />.</value> public bool IsCompleted => (_resultFlags & ResultFlags.Completed) != 0; } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest466/Generated466.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated466 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct516`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase2`2<class BaseClass1,!T0>, class IBase2`2<class BaseClass1,class BaseClass0> { .pack 0 .size 1 .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct516::Method7.3992<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<class BaseClass1,T0>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass1,!T0>::Method7<[1]>() ldstr "MyStruct516::Method7.MI.3993<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod1023() cil managed noinlining { ldstr "MyStruct516::ClassMethod1023.3995()" ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated466 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct516.T.T<T0,T1,(valuetype MyStruct516`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct516.T.T<T0,T1,(valuetype MyStruct516`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct516`2<!!T0,!!T1> callvirt instance string class IBase2`2<class BaseClass1,!!T0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct516`2<!!T0,!!T1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct516.B.T<T1,(valuetype MyStruct516`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct516.B.T<T1,(valuetype MyStruct516`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct516`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct516`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct516.B.A<(valuetype MyStruct516`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct516.B.A<(valuetype MyStruct516`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct516`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct516`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct516.B.B<(valuetype MyStruct516`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct516.B.B<(valuetype MyStruct516`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct516`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct516`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloca V_3 dup call instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass0> on type MyStruct516" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::ClassMethod1023() ldstr "MyStruct516::ClassMethod1023.3995()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass0> on type MyStruct516" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::ToString() pop pop ldloc V_3 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloca V_4 dup call instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass1> on type MyStruct516" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::ClassMethod1023() ldstr "MyStruct516::ClassMethod1023.3995()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass1> on type MyStruct516" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::ToString() pop pop ldloc V_4 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass0> .try { ldloc V_7 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_7 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.B.T<class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_7 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.B.B<valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_7 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_7 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.B.T<class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_7 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.B.A<valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .try { ldloc V_7 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_7 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.A.T<class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_7 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.A.B<valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_7 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_7 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.A.T<class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_7 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.A.A<valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass1> .try { ldloc V_8 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_8 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.B.T<class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_8 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.B.B<valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_8 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_8 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.B.T<class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_8 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.B.A<valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .try { ldloc V_8 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_8 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.A.T<class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_8 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.A.B<valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .try { ldloc V_8 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .try { ldloc V_8 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.A.T<class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_8 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.A.A<valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass0> V_11) ldloca V_11 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass0> .try { ldloc V_11 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" + "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.MyStruct516.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_11 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" + "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.MyStruct516.B.T<class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_11 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" + "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.MyStruct516.B.A<valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass1> V_12) ldloca V_12 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass1> .try { ldloc V_12 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" + "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.MyStruct516.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_12 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" + "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.MyStruct516.B.T<class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_12 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" + "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.MyStruct516.B.B<valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass0> V_15) ldloca V_15 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::ClassMethod1023() calli default string(object) ldstr "MyStruct516::ClassMethod1023.3995()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldnull ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance bool valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass1> V_16) ldloca V_16 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::ClassMethod1023() calli default string(object) ldstr "MyStruct516::ClassMethod1023.3995()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldnull ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance bool valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated466::MethodCallingTest() call void Generated466::ConstrainedCallsTest() call void Generated466::StructConstrainedInterfaceCallsTest() call void Generated466::CalliTest() ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated466 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct516`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase2`2<class BaseClass1,!T0>, class IBase2`2<class BaseClass1,class BaseClass0> { .pack 0 .size 1 .method public hidebysig virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct516::Method7.3992<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<class BaseClass1,T0>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<class BaseClass1,!T0>::Method7<[1]>() ldstr "MyStruct516::Method7.MI.3993<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod1023() cil managed noinlining { ldstr "MyStruct516::ClassMethod1023.3995()" ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated466 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct516.T.T<T0,T1,(valuetype MyStruct516`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct516.T.T<T0,T1,(valuetype MyStruct516`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct516`2<!!T0,!!T1> callvirt instance string class IBase2`2<class BaseClass1,!!T0>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct516`2<!!T0,!!T1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct516.B.T<T1,(valuetype MyStruct516`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct516.B.T<T1,(valuetype MyStruct516`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct516`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct516`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct516.B.A<(valuetype MyStruct516`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct516.B.A<(valuetype MyStruct516`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct516`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct516`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct516.B.B<(valuetype MyStruct516`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 7 .locals init (string[] actualResults) ldc.i4.s 2 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct516.B.B<(valuetype MyStruct516`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 2 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct516`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct516`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloca V_3 dup call instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass0> on type MyStruct516" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::ClassMethod1023() ldstr "MyStruct516::ClassMethod1023.3995()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass0> on type MyStruct516" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::ToString() pop pop ldloc V_3 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloca V_4 dup call instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass1> on type MyStruct516" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::ClassMethod1023() ldstr "MyStruct516::ClassMethod1023.3995()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass1> on type MyStruct516" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::ToString() pop pop ldloc V_4 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass0> .try { ldloc V_7 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_7 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.B.T<class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_7 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.B.B<valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_7 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_7 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.B.T<class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_7 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.B.A<valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .try { ldloc V_7 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_7 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.A.T<class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_7 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.A.B<valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_7 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_7 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.A.T<class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_7 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.A.A<valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass1> .try { ldloc V_8 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_8 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.B.T<class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_8 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.B.B<valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_8 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_8 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.B.T<class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_8 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.B.A<valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .try { ldloc V_8 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_8 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.A.T<class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_8 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" call void Generated466::M.IBase2.A.B<valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .try { ldloc V_8 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .try { ldloc V_8 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.A.T<class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_8 ldstr "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.IBase2.A.A<valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass0> V_11) ldloca V_11 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass0> .try { ldloc V_11 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" + "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.MyStruct516.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_11 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" + "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.MyStruct516.B.T<class BaseClass0,valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_11 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" + "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.MyStruct516.B.A<valuetype MyStruct516`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass1> V_12) ldloca V_12 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass1> .try { ldloc V_12 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" + "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.MyStruct516.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_12 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" + "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.MyStruct516.B.T<class BaseClass1,valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_12 ldstr "MyStruct516::Method7.MI.3993<System.Object>()#" + "MyStruct516::Method7.3992<System.Object>()#" call void Generated466::M.MyStruct516.B.B<valuetype MyStruct516`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass0> V_15) ldloca V_15 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::ClassMethod1023() calli default string(object) ldstr "MyStruct516::ClassMethod1023.3995()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldnull ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance bool valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct516`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct516`2<class BaseClass1,class BaseClass1> V_16) ldloca V_16 initobj valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::ClassMethod1023() calli default string(object) ldstr "MyStruct516::ClassMethod1023.3995()" ldstr "valuetype MyStruct516`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldnull ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance bool valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct516`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.MI.3993<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct516`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct516::Method7.3992<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct516`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated466::MethodCallingTest() call void Generated466::ConstrainedCallsTest() call void Generated466::StructConstrainedInterfaceCallsTest() call void Generated466::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/System.Text.Json/tests/Common/PropertyVisibilityTests.NonPublicAccessors.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Threading.Tasks; using Xunit; namespace System.Text.Json.Serialization.Tests { public abstract partial class PropertyVisibilityTests { [Fact] public async Task NonPublic_AccessorsNotSupported_WithoutAttribute() { string json = @"{ ""MyInt"":1, ""MyString"":""Hello"", ""MyFloat"":2, ""MyUri"":""https://microsoft.com"" }"; var obj = await JsonSerializerWrapperForString.DeserializeWrapper<MyClass_WithNonPublicAccessors>(json); Assert.Equal(0, obj.MyInt); Assert.Null(obj.MyString); Assert.Equal(2f, obj.GetMyFloat); Assert.Equal(new Uri("https://microsoft.com"), obj.MyUri); json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""MyInt"":0", json); Assert.Contains(@"""MyString"":null", json); Assert.DoesNotContain(@"""MyFloat"":", json); Assert.DoesNotContain(@"""MyUri"":", json); } public class MyClass_WithNonPublicAccessors { public int MyInt { get; private set; } public string MyString { get; internal set; } public float MyFloat { private get; set; } public Uri MyUri { internal get; set; } // For test validation. internal float GetMyFloat => MyFloat; } [Fact] public virtual async Task Honor_JsonSerializablePropertyAttribute_OnProperties() { string json = @"{ ""MyInt"":1, ""MyString"":""Hello"", ""MyFloat"":2, ""MyUri"":""https://microsoft.com"" }"; var obj = await JsonSerializerWrapperForString.DeserializeWrapper<MyClass_WithNonPublicAccessors_WithPropertyAttributes>(json); Assert.Equal(1, obj.MyInt); Assert.Equal("Hello", obj.MyString); Assert.Equal(2f, obj.GetMyFloat); Assert.Equal(new Uri("https://microsoft.com"), obj.MyUri); json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""MyInt"":1", json); Assert.Contains(@"""MyString"":""Hello""", json); Assert.Contains(@"""MyFloat"":2", json); Assert.Contains(@"""MyUri"":""https://microsoft.com""", json); } public class MyClass_WithNonPublicAccessors_WithPropertyAttributes { [JsonInclude] public int MyInt { get; private set; } [JsonInclude] public string MyString { get; internal set; } [JsonInclude] public float MyFloat { private get; set; } [JsonInclude] public Uri MyUri { internal get; set; } // For test validation. internal float GetMyFloat => MyFloat; } private class MyClass_WithNonPublicAccessors_WithPropertyAttributes_And_PropertyIgnore { [JsonInclude] [JsonIgnore] public int MyInt { get; private set; } [JsonInclude] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public string MyString { get; internal set; } = "DefaultString"; [JsonInclude] [JsonIgnore(Condition = JsonIgnoreCondition.Always)] public float MyFloat { private get; set; } [JsonInclude] [JsonIgnore(Condition = JsonIgnoreCondition.Never)] public Uri MyUri { internal get; set; } // For test validation. internal float GetMyFloat => MyFloat; } [Fact] #if BUILDING_SOURCE_GENERATOR_TESTS // Need support for extension data. [ActiveIssue("https://github.com/dotnet/runtime/issues/45448")] #endif public async Task ExtensionDataCanHaveNonPublicSetter() { string json = @"{""Key"":""Value""}"; // Baseline var obj1 = await JsonSerializerWrapperForString.DeserializeWrapper<ClassWithExtensionData_NonPublicSetter>(json); Assert.Null(obj1.ExtensionData); Assert.Equal("{}", await JsonSerializerWrapperForString.SerializeWrapper(obj1)); // With attribute var obj2 = await JsonSerializerWrapperForString.DeserializeWrapper<ClassWithExtensionData_NonPublicSetter_WithAttribute>(json); Assert.Equal("Value", obj2.ExtensionData["Key"].GetString()); Assert.Equal(json, await JsonSerializerWrapperForString.SerializeWrapper(obj2)); } private class ClassWithExtensionData_NonPublicSetter { [JsonExtensionData] public Dictionary<string, JsonElement> ExtensionData { get; private set; } } private class ClassWithExtensionData_NonPublicSetter_WithAttribute { [JsonExtensionData] [JsonInclude] public Dictionary<string, JsonElement> ExtensionData { get; private set; } } private class ClassWithExtensionData_NonPublicGetter { [JsonExtensionData] public Dictionary<string, JsonElement> ExtensionData { internal get; set; } } [Fact] public virtual async Task HonorCustomConverter_UsingPrivateSetter() { var options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter()); string json = @"{""MyEnum"":""AnotherValue"",""MyInt"":2}"; // Deserialization baseline, without enum converter, we get JsonException. await Assert.ThrowsAsync<JsonException>(async () => await JsonSerializerWrapperForString.DeserializeWrapper<StructWithPropertiesWithConverter>(json)); var obj = await JsonSerializerWrapperForString.DeserializeWrapper<StructWithPropertiesWithConverter>(json, options); Assert.Equal(MySmallEnum.AnotherValue, obj.GetMyEnum); Assert.Equal(25, obj.MyInt); // ConverterForInt32 throws this exception. await Assert.ThrowsAsync<NotImplementedException>(async () => await JsonSerializerWrapperForString.SerializeWrapper(obj, options)); } public struct StructWithPropertiesWithConverter { [JsonInclude] public MySmallEnum MyEnum { private get; set; } [JsonInclude] [JsonConverter(typeof(ConverterForInt32))] public int MyInt { get; private set; } // For test validation. internal MySmallEnum GetMyEnum => MyEnum; } public enum MySmallEnum { DefaultValue = 0, AnotherValue = 1 } [Fact] public async Task HonorCaseInsensitivity() { var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; string json = @"{""MYSTRING"":""Hello""}"; Assert.Null((await JsonSerializerWrapperForString.DeserializeWrapper<MyStruct_WithNonPublicAccessors_WithTypeAttribute>(json)).MyString); Assert.Equal("Hello", (await JsonSerializerWrapperForString.DeserializeWrapper<MyStruct_WithNonPublicAccessors_WithTypeAttribute>(json, options)).MyString); } public struct MyStruct_WithNonPublicAccessors_WithTypeAttribute { [JsonInclude] public int MyInt { get; private set; } [JsonInclude] public string MyString { get; internal set; } [JsonInclude] public float MyFloat { private get; set; } [JsonInclude] public Uri MyUri { internal get; set; } // For test validation. internal float GetMyFloat => MyFloat; } [Fact] public async Task HonorNamingPolicy() { var options = new JsonSerializerOptions { PropertyNamingPolicy = new SimpleSnakeCasePolicy() }; string json = @"{""my_string"":""Hello""}"; Assert.Null((await JsonSerializerWrapperForString.DeserializeWrapper<MyStruct_WithNonPublicAccessors_WithTypeAttribute>(json)).MyString); Assert.Equal("Hello", (await JsonSerializerWrapperForString.DeserializeWrapper<MyStruct_WithNonPublicAccessors_WithTypeAttribute>(json, options)).MyString); } [Fact] public virtual async Task HonorJsonPropertyName_PrivateGetter() { string json = @"{""prop1"":1}"; var obj = await JsonSerializerWrapperForString.DeserializeWrapper<StructWithPropertiesWithJsonPropertyName_PrivateGetter>(json); Assert.Equal(MySmallEnum.AnotherValue, obj.GetProxy()); json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""prop1"":1", json); } [Fact] public virtual async Task HonorJsonPropertyName_PrivateSetter() { string json = @"{""prop2"":2}"; var obj = await JsonSerializerWrapperForString.DeserializeWrapper<StructWithPropertiesWithJsonPropertyName_PrivateSetter>(json); Assert.Equal(2, obj.MyInt); json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""prop2"":2", json); } public struct StructWithPropertiesWithJsonPropertyName_PrivateGetter { [JsonInclude] [JsonPropertyName("prop1")] public MySmallEnum MyEnum { private get; set; } // For test validation. internal MySmallEnum GetProxy() => MyEnum; } public struct StructWithPropertiesWithJsonPropertyName_PrivateSetter { [JsonInclude] [JsonPropertyName("prop2")] public int MyInt { get; private set; } internal void SetProxy(int myInt) => MyInt = myInt; } [Fact] #if BUILDING_SOURCE_GENERATOR_TESTS // Needs support for parameterized ctors. [ActiveIssue("https://github.com/dotnet/runtime/issues/45448")] #endif public async Task Map_JsonSerializableProperties_ToCtorArgs() { var obj = await JsonSerializerWrapperForString.DeserializeWrapper<PointWith_JsonSerializableProperties>(@"{""X"":1,""Y"":2}"); Assert.Equal(1, obj.X); Assert.Equal(2, obj.GetY); } private struct PointWith_JsonSerializableProperties { [JsonInclude] public int X { get; internal set; } [JsonInclude] public int Y { internal get; set; } internal int GetY => Y; [JsonConstructor] public PointWith_JsonSerializableProperties(int x, int y) => (X, Y) = (x, y); } [Fact] public virtual async Task Public_And_NonPublicPropertyAccessors_PropertyAttributes() { string json = @"{""W"":1,""X"":2,""Y"":3,""Z"":4}"; var obj = await JsonSerializerWrapperForString.DeserializeWrapper<ClassWithMixedPropertyAccessors_PropertyAttributes>(json); Assert.Equal(1, obj.W); Assert.Equal(2, obj.X); Assert.Equal(3, obj.Y); Assert.Equal(4, obj.GetZ); json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""W"":1", json); Assert.Contains(@"""X"":2", json); Assert.Contains(@"""Y"":3", json); Assert.Contains(@"""Z"":4", json); } public class ClassWithMixedPropertyAccessors_PropertyAttributes { [JsonInclude] public int W { get; set; } [JsonInclude] public int X { get; internal set; } [JsonInclude] public int Y { get; set; } [JsonInclude] public int Z { private get; set; } internal int GetZ => Z; } [Theory] [InlineData(typeof(ClassWithPrivateProperty_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithInternalProperty_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithProtectedProperty_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithPrivateField_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithInternalField_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithProtectedField_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithPrivate_InitOnlyProperty_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithInternal_InitOnlyProperty_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithProtected_InitOnlyProperty_WithJsonIncludeProperty))] public virtual async Task NonPublicProperty_WithJsonInclude_Invalid(Type type) { InvalidOperationException ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await JsonSerializerWrapperForString.DeserializeWrapper("{}", type)); string exAsStr = ex.ToString(); Assert.Contains("MyString", exAsStr); Assert.Contains(type.ToString(), exAsStr); Assert.Contains("JsonIncludeAttribute", exAsStr); ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await JsonSerializerWrapperForString.SerializeWrapper(Activator.CreateInstance(type), type)); exAsStr = ex.ToString(); Assert.Contains("MyString", exAsStr); Assert.Contains(type.ToString(), exAsStr); Assert.Contains("JsonIncludeAttribute", exAsStr); } public class ClassWithPrivateProperty_WithJsonIncludeProperty { [JsonInclude] private string MyString { get; set; } } public class ClassWithInternalProperty_WithJsonIncludeProperty { [JsonInclude] internal string MyString { get; } } public class ClassWithProtectedProperty_WithJsonIncludeProperty { [JsonInclude] protected string MyString { get; private set; } } public class ClassWithPrivateField_WithJsonIncludeProperty { [JsonInclude] private string MyString = null; public override string ToString() => MyString; } public class ClassWithInternalField_WithJsonIncludeProperty { [JsonInclude] internal string MyString = null; } public class ClassWithProtectedField_WithJsonIncludeProperty { [JsonInclude] protected string MyString = null; } public class ClassWithPrivate_InitOnlyProperty_WithJsonIncludeProperty { [JsonInclude] private string MyString { get; init; } } public class ClassWithInternal_InitOnlyProperty_WithJsonIncludeProperty { [JsonInclude] internal string MyString { get; init; } } public class ClassWithProtected_InitOnlyProperty_WithJsonIncludeProperty { [JsonInclude] protected string MyString { get; init; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Threading.Tasks; using Xunit; namespace System.Text.Json.Serialization.Tests { public abstract partial class PropertyVisibilityTests { [Fact] public async Task NonPublic_AccessorsNotSupported_WithoutAttribute() { string json = @"{ ""MyInt"":1, ""MyString"":""Hello"", ""MyFloat"":2, ""MyUri"":""https://microsoft.com"" }"; var obj = await JsonSerializerWrapperForString.DeserializeWrapper<MyClass_WithNonPublicAccessors>(json); Assert.Equal(0, obj.MyInt); Assert.Null(obj.MyString); Assert.Equal(2f, obj.GetMyFloat); Assert.Equal(new Uri("https://microsoft.com"), obj.MyUri); json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""MyInt"":0", json); Assert.Contains(@"""MyString"":null", json); Assert.DoesNotContain(@"""MyFloat"":", json); Assert.DoesNotContain(@"""MyUri"":", json); } public class MyClass_WithNonPublicAccessors { public int MyInt { get; private set; } public string MyString { get; internal set; } public float MyFloat { private get; set; } public Uri MyUri { internal get; set; } // For test validation. internal float GetMyFloat => MyFloat; } [Fact] public virtual async Task Honor_JsonSerializablePropertyAttribute_OnProperties() { string json = @"{ ""MyInt"":1, ""MyString"":""Hello"", ""MyFloat"":2, ""MyUri"":""https://microsoft.com"" }"; var obj = await JsonSerializerWrapperForString.DeserializeWrapper<MyClass_WithNonPublicAccessors_WithPropertyAttributes>(json); Assert.Equal(1, obj.MyInt); Assert.Equal("Hello", obj.MyString); Assert.Equal(2f, obj.GetMyFloat); Assert.Equal(new Uri("https://microsoft.com"), obj.MyUri); json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""MyInt"":1", json); Assert.Contains(@"""MyString"":""Hello""", json); Assert.Contains(@"""MyFloat"":2", json); Assert.Contains(@"""MyUri"":""https://microsoft.com""", json); } public class MyClass_WithNonPublicAccessors_WithPropertyAttributes { [JsonInclude] public int MyInt { get; private set; } [JsonInclude] public string MyString { get; internal set; } [JsonInclude] public float MyFloat { private get; set; } [JsonInclude] public Uri MyUri { internal get; set; } // For test validation. internal float GetMyFloat => MyFloat; } private class MyClass_WithNonPublicAccessors_WithPropertyAttributes_And_PropertyIgnore { [JsonInclude] [JsonIgnore] public int MyInt { get; private set; } [JsonInclude] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public string MyString { get; internal set; } = "DefaultString"; [JsonInclude] [JsonIgnore(Condition = JsonIgnoreCondition.Always)] public float MyFloat { private get; set; } [JsonInclude] [JsonIgnore(Condition = JsonIgnoreCondition.Never)] public Uri MyUri { internal get; set; } // For test validation. internal float GetMyFloat => MyFloat; } [Fact] #if BUILDING_SOURCE_GENERATOR_TESTS // Need support for extension data. [ActiveIssue("https://github.com/dotnet/runtime/issues/45448")] #endif public async Task ExtensionDataCanHaveNonPublicSetter() { string json = @"{""Key"":""Value""}"; // Baseline var obj1 = await JsonSerializerWrapperForString.DeserializeWrapper<ClassWithExtensionData_NonPublicSetter>(json); Assert.Null(obj1.ExtensionData); Assert.Equal("{}", await JsonSerializerWrapperForString.SerializeWrapper(obj1)); // With attribute var obj2 = await JsonSerializerWrapperForString.DeserializeWrapper<ClassWithExtensionData_NonPublicSetter_WithAttribute>(json); Assert.Equal("Value", obj2.ExtensionData["Key"].GetString()); Assert.Equal(json, await JsonSerializerWrapperForString.SerializeWrapper(obj2)); } private class ClassWithExtensionData_NonPublicSetter { [JsonExtensionData] public Dictionary<string, JsonElement> ExtensionData { get; private set; } } private class ClassWithExtensionData_NonPublicSetter_WithAttribute { [JsonExtensionData] [JsonInclude] public Dictionary<string, JsonElement> ExtensionData { get; private set; } } private class ClassWithExtensionData_NonPublicGetter { [JsonExtensionData] public Dictionary<string, JsonElement> ExtensionData { internal get; set; } } [Fact] public virtual async Task HonorCustomConverter_UsingPrivateSetter() { var options = new JsonSerializerOptions(); options.Converters.Add(new JsonStringEnumConverter()); string json = @"{""MyEnum"":""AnotherValue"",""MyInt"":2}"; // Deserialization baseline, without enum converter, we get JsonException. await Assert.ThrowsAsync<JsonException>(async () => await JsonSerializerWrapperForString.DeserializeWrapper<StructWithPropertiesWithConverter>(json)); var obj = await JsonSerializerWrapperForString.DeserializeWrapper<StructWithPropertiesWithConverter>(json, options); Assert.Equal(MySmallEnum.AnotherValue, obj.GetMyEnum); Assert.Equal(25, obj.MyInt); // ConverterForInt32 throws this exception. await Assert.ThrowsAsync<NotImplementedException>(async () => await JsonSerializerWrapperForString.SerializeWrapper(obj, options)); } public struct StructWithPropertiesWithConverter { [JsonInclude] public MySmallEnum MyEnum { private get; set; } [JsonInclude] [JsonConverter(typeof(ConverterForInt32))] public int MyInt { get; private set; } // For test validation. internal MySmallEnum GetMyEnum => MyEnum; } public enum MySmallEnum { DefaultValue = 0, AnotherValue = 1 } [Fact] public async Task HonorCaseInsensitivity() { var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; string json = @"{""MYSTRING"":""Hello""}"; Assert.Null((await JsonSerializerWrapperForString.DeserializeWrapper<MyStruct_WithNonPublicAccessors_WithTypeAttribute>(json)).MyString); Assert.Equal("Hello", (await JsonSerializerWrapperForString.DeserializeWrapper<MyStruct_WithNonPublicAccessors_WithTypeAttribute>(json, options)).MyString); } public struct MyStruct_WithNonPublicAccessors_WithTypeAttribute { [JsonInclude] public int MyInt { get; private set; } [JsonInclude] public string MyString { get; internal set; } [JsonInclude] public float MyFloat { private get; set; } [JsonInclude] public Uri MyUri { internal get; set; } // For test validation. internal float GetMyFloat => MyFloat; } [Fact] public async Task HonorNamingPolicy() { var options = new JsonSerializerOptions { PropertyNamingPolicy = new SimpleSnakeCasePolicy() }; string json = @"{""my_string"":""Hello""}"; Assert.Null((await JsonSerializerWrapperForString.DeserializeWrapper<MyStruct_WithNonPublicAccessors_WithTypeAttribute>(json)).MyString); Assert.Equal("Hello", (await JsonSerializerWrapperForString.DeserializeWrapper<MyStruct_WithNonPublicAccessors_WithTypeAttribute>(json, options)).MyString); } [Fact] public virtual async Task HonorJsonPropertyName_PrivateGetter() { string json = @"{""prop1"":1}"; var obj = await JsonSerializerWrapperForString.DeserializeWrapper<StructWithPropertiesWithJsonPropertyName_PrivateGetter>(json); Assert.Equal(MySmallEnum.AnotherValue, obj.GetProxy()); json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""prop1"":1", json); } [Fact] public virtual async Task HonorJsonPropertyName_PrivateSetter() { string json = @"{""prop2"":2}"; var obj = await JsonSerializerWrapperForString.DeserializeWrapper<StructWithPropertiesWithJsonPropertyName_PrivateSetter>(json); Assert.Equal(2, obj.MyInt); json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""prop2"":2", json); } public struct StructWithPropertiesWithJsonPropertyName_PrivateGetter { [JsonInclude] [JsonPropertyName("prop1")] public MySmallEnum MyEnum { private get; set; } // For test validation. internal MySmallEnum GetProxy() => MyEnum; } public struct StructWithPropertiesWithJsonPropertyName_PrivateSetter { [JsonInclude] [JsonPropertyName("prop2")] public int MyInt { get; private set; } internal void SetProxy(int myInt) => MyInt = myInt; } [Fact] #if BUILDING_SOURCE_GENERATOR_TESTS // Needs support for parameterized ctors. [ActiveIssue("https://github.com/dotnet/runtime/issues/45448")] #endif public async Task Map_JsonSerializableProperties_ToCtorArgs() { var obj = await JsonSerializerWrapperForString.DeserializeWrapper<PointWith_JsonSerializableProperties>(@"{""X"":1,""Y"":2}"); Assert.Equal(1, obj.X); Assert.Equal(2, obj.GetY); } private struct PointWith_JsonSerializableProperties { [JsonInclude] public int X { get; internal set; } [JsonInclude] public int Y { internal get; set; } internal int GetY => Y; [JsonConstructor] public PointWith_JsonSerializableProperties(int x, int y) => (X, Y) = (x, y); } [Fact] public virtual async Task Public_And_NonPublicPropertyAccessors_PropertyAttributes() { string json = @"{""W"":1,""X"":2,""Y"":3,""Z"":4}"; var obj = await JsonSerializerWrapperForString.DeserializeWrapper<ClassWithMixedPropertyAccessors_PropertyAttributes>(json); Assert.Equal(1, obj.W); Assert.Equal(2, obj.X); Assert.Equal(3, obj.Y); Assert.Equal(4, obj.GetZ); json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""W"":1", json); Assert.Contains(@"""X"":2", json); Assert.Contains(@"""Y"":3", json); Assert.Contains(@"""Z"":4", json); } public class ClassWithMixedPropertyAccessors_PropertyAttributes { [JsonInclude] public int W { get; set; } [JsonInclude] public int X { get; internal set; } [JsonInclude] public int Y { get; set; } [JsonInclude] public int Z { private get; set; } internal int GetZ => Z; } [Theory] [InlineData(typeof(ClassWithPrivateProperty_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithInternalProperty_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithProtectedProperty_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithPrivateField_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithInternalField_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithProtectedField_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithPrivate_InitOnlyProperty_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithInternal_InitOnlyProperty_WithJsonIncludeProperty))] [InlineData(typeof(ClassWithProtected_InitOnlyProperty_WithJsonIncludeProperty))] public virtual async Task NonPublicProperty_WithJsonInclude_Invalid(Type type) { InvalidOperationException ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await JsonSerializerWrapperForString.DeserializeWrapper("{}", type)); string exAsStr = ex.ToString(); Assert.Contains("MyString", exAsStr); Assert.Contains(type.ToString(), exAsStr); Assert.Contains("JsonIncludeAttribute", exAsStr); ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await JsonSerializerWrapperForString.SerializeWrapper(Activator.CreateInstance(type), type)); exAsStr = ex.ToString(); Assert.Contains("MyString", exAsStr); Assert.Contains(type.ToString(), exAsStr); Assert.Contains("JsonIncludeAttribute", exAsStr); } public class ClassWithPrivateProperty_WithJsonIncludeProperty { [JsonInclude] private string MyString { get; set; } } public class ClassWithInternalProperty_WithJsonIncludeProperty { [JsonInclude] internal string MyString { get; } } public class ClassWithProtectedProperty_WithJsonIncludeProperty { [JsonInclude] protected string MyString { get; private set; } } public class ClassWithPrivateField_WithJsonIncludeProperty { [JsonInclude] private string MyString = null; public override string ToString() => MyString; } public class ClassWithInternalField_WithJsonIncludeProperty { [JsonInclude] internal string MyString = null; } public class ClassWithProtectedField_WithJsonIncludeProperty { [JsonInclude] protected string MyString = null; } public class ClassWithPrivate_InitOnlyProperty_WithJsonIncludeProperty { [JsonInclude] private string MyString { get; init; } } public class ClassWithInternal_InitOnlyProperty_WithJsonIncludeProperty { [JsonInclude] internal string MyString { get; init; } } public class ClassWithProtected_InitOnlyProperty_WithJsonIncludeProperty { [JsonInclude] protected string MyString { get; init; } } } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./src/libraries/Common/src/Interop/Unix/System.Native/Interop.Link.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { [LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_Link", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] internal static partial int Link(string source, string link); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { [LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_Link", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] internal static partial int Link(string source, string link); } }
-1
dotnet/runtime
66,434
Expose `LibraryImportAttribute`
Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
elinor-fung
2022-03-10T05:02:25Z
2022-03-16T03:05:51Z
c3dbdea91835d67cc461b22125e652ad5063d746
d2688883510318aa0114268930fb2022d3dc64cf
Expose `LibraryImportAttribute`. Expose `LibraryImportAttribute` in runtime libraries. Resolves https://github.com/dotnet/runtime/issues/46822
./eng/common/cross/arm64/sources.list.bionic
deb http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe deb http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe deb http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted deb http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse
deb http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic main restricted universe deb http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-updates main restricted universe deb http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-backports main restricted deb http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse deb-src http://ports.ubuntu.com/ubuntu-ports/ bionic-security main restricted universe multiverse
-1