From edb7d7e30df3a61c82720ec377c3e53e5a8dbd97 Mon Sep 17 00:00:00 2001 From: Johan Lorensson Date: Mon, 29 Aug 2022 10:26:03 +0200 Subject: [PATCH 001/107] Use System.Numerics.IEqualityOperators.op_Equality in SpanHelper.T.cs where possible. (#74567) * Use System.Numerics.IEqualityOperators.op_Equality in SpanHelper.T.cs. Workaround crash hit by https://github.com/dotnet/runtime/issues/74179 making sure we avoid hitting codepath emitting this null pointer checks. The full fix includes codegen fixes as well, but will be performed in separate PR. There are still locations in SpanHelper.T.cs that uses Equal virtual call on value types that could be managed pointers to value types, but that code has remained the same for the last 4 years to 15 months and have not hit this issue in the past. * Re-enable globalization tests disabled in #74433. --- .../tests/CompareInfo/CompareInfoTests.IndexOf.cs | 1 - .../System.Globalization/tests/Invariant/InvariantMode.cs | 2 -- .../System.Private.CoreLib/src/System/SpanHelpers.T.cs | 4 ++-- 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/libraries/System.Globalization/tests/CompareInfo/CompareInfoTests.IndexOf.cs b/src/libraries/System.Globalization/tests/CompareInfo/CompareInfoTests.IndexOf.cs index fa12fb9cec5604..58d66e93be6d67 100644 --- a/src/libraries/System.Globalization/tests/CompareInfo/CompareInfoTests.IndexOf.cs +++ b/src/libraries/System.Globalization/tests/CompareInfo/CompareInfoTests.IndexOf.cs @@ -183,7 +183,6 @@ public static IEnumerable IndexOf_U_WithDiaeresis_TestData() [MemberData(nameof(IndexOf_TestData))] [MemberData(nameof(IndexOf_Aesc_Ligature_TestData))] [MemberData(nameof(IndexOf_U_WithDiaeresis_TestData))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/74179", TestRuntimes.Mono)] public void IndexOf_String(CompareInfo compareInfo, string source, string value, int startIndex, int count, CompareOptions options, int expected, int expectedMatchLength) { if (value.Length == 1) diff --git a/src/libraries/System.Globalization/tests/Invariant/InvariantMode.cs b/src/libraries/System.Globalization/tests/Invariant/InvariantMode.cs index 8416d0e3f7bdb6..361c39ec4272b8 100644 --- a/src/libraries/System.Globalization/tests/Invariant/InvariantMode.cs +++ b/src/libraries/System.Globalization/tests/Invariant/InvariantMode.cs @@ -864,7 +864,6 @@ private static StringComparison GetStringComparison(CompareOptions options) [ConditionalTheory(nameof(PredefinedCulturesOnlyIsDisabled))] [MemberData(nameof(IndexOf_TestData))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/74179", TestRuntimes.Mono)] public void TestIndexOf(string source, string value, int startIndex, int count, CompareOptions options, int result) { foreach (string cul in s_cultureNames) @@ -912,7 +911,6 @@ static void TestCore(CompareInfo compareInfo, string source, string value, int s [ConditionalTheory(nameof(PredefinedCulturesOnlyIsDisabled))] [MemberData(nameof(LastIndexOf_TestData))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/74179", TestRuntimes.Mono)] public void TestLastIndexOf(string source, string value, int startIndex, int count, CompareOptions options, int result) { foreach (string cul in s_cultureNames) diff --git a/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs b/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs index b093cb11a29e6d..877c21311876d5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs +++ b/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs @@ -1498,7 +1498,7 @@ private static int IndexOfValueType(ref TValue searchSpace, TV { length -= 1; - if (TNegator.NegateIfNeeded(Unsafe.Add(ref searchSpace, offset).Equals(value))) return (int)offset; + if (TNegator.NegateIfNeeded(Unsafe.Add(ref searchSpace, offset) == value)) return (int)offset; offset += 1; } @@ -2145,7 +2145,7 @@ private static int LastIndexOfValueType(ref TValue searchSpace { length -= 1; - if (TNegator.NegateIfNeeded(Unsafe.Add(ref searchSpace, offset).Equals(value))) return (int)offset; + if (TNegator.NegateIfNeeded(Unsafe.Add(ref searchSpace, offset) == value)) return (int)offset; offset -= 1; } From f21cf5295c1cc8c1b2e482167a28d4c696548dea Mon Sep 17 00:00:00 2001 From: Jakob Botsch Nielsen Date: Mon, 29 Aug 2022 11:42:29 +0200 Subject: [PATCH 002/107] Fix signature for 64-bit delegate profiling helper (#74500) * Fix signature for 64-bit delegate profiling helper I missed updating the signature of the 64-bit variant here when the vtable and delegate profiling helpers were originally split up. Fix #74295 * JIT: Randomly collect 64-bit counts Add some testing. * Disable collecting 64 bit counters on 32-bit This needs some work so disable it for now. --- src/coreclr/jit/compiler.cpp | 15 +++++++++++++++ src/coreclr/jit/compiler.h | 3 +++ src/coreclr/jit/fgprofile.cpp | 6 +++--- src/coreclr/jit/jitconfigvalues.h | 4 +++- src/coreclr/vm/jithelpers.cpp | 2 +- src/tests/Common/testenvironment.proj | 9 +++++---- 6 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/coreclr/jit/compiler.cpp b/src/coreclr/jit/compiler.cpp index 818c8bd6ad636e..1042c1800324f1 100644 --- a/src/coreclr/jit/compiler.cpp +++ b/src/coreclr/jit/compiler.cpp @@ -3208,6 +3208,21 @@ void Compiler::compInitOptions(JitFlags* jitFlags) #endif } +#ifdef TARGET_64BIT + opts.compCollect64BitCounts = JitConfig.JitCollect64BitCounts() != 0; + +#ifdef DEBUG + if (JitConfig.JitRandomlyCollect64BitCounts() != 0) + { + CLRRandom rng; + rng.Init(info.compMethodHash() ^ JitConfig.JitRandomlyCollect64BitCounts() ^ 0x3485e20e); + opts.compCollect64BitCounts = rng.Next(2) == 0; + } +#endif +#else + opts.compCollect64BitCounts = false; +#endif + #ifdef DEBUG // Now, set compMaxUncheckedOffsetForNullObject for STRESS_NULL_OBJECT_CHECK diff --git a/src/coreclr/jit/compiler.h b/src/coreclr/jit/compiler.h index cc69470cbb9af7..e5190a9dea64b1 100644 --- a/src/coreclr/jit/compiler.h +++ b/src/coreclr/jit/compiler.h @@ -9335,6 +9335,9 @@ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // Use early multi-dimensional array operator expansion (expand after loop optimizations; before lowering). bool compJitEarlyExpandMDArrays; + // Collect 64 bit counts for PGO data. + bool compCollect64BitCounts; + } opts; static bool s_pAltJitExcludeAssembliesListInitialized; diff --git a/src/coreclr/jit/fgprofile.cpp b/src/coreclr/jit/fgprofile.cpp index 22ef8e2d32911e..a0f82765b6b40c 100644 --- a/src/coreclr/jit/fgprofile.cpp +++ b/src/coreclr/jit/fgprofile.cpp @@ -570,7 +570,7 @@ void BlockCountInstrumentor::BuildSchemaElements(BasicBlock* block, Schema& sche ICorJitInfo::PgoInstrumentationSchema schemaElem; schemaElem.Count = 1; schemaElem.Other = 0; - schemaElem.InstrumentationKind = JitConfig.JitCollect64BitCounts() + schemaElem.InstrumentationKind = m_comp->opts.compCollect64BitCounts ? ICorJitInfo::PgoInstrumentationKind::BasicBlockLongCount : ICorJitInfo::PgoInstrumentationKind::BasicBlockIntCount; schemaElem.ILOffset = offset; @@ -1314,7 +1314,7 @@ void EfficientEdgeCountInstrumentor::BuildSchemaElements(BasicBlock* block, Sche ICorJitInfo::PgoInstrumentationSchema schemaElem; schemaElem.Count = 1; schemaElem.Other = targetKey; - schemaElem.InstrumentationKind = JitConfig.JitCollect64BitCounts() + schemaElem.InstrumentationKind = m_comp->opts.compCollect64BitCounts ? ICorJitInfo::PgoInstrumentationKind::EdgeLongCount : ICorJitInfo::PgoInstrumentationKind::EdgeIntCount; schemaElem.ILOffset = sourceKey; @@ -1503,7 +1503,7 @@ class BuildHandleHistogramProbeSchemaGen schemaElem.Other |= ICorJitInfo::HandleHistogram32::DELEGATE_FLAG; } - schemaElem.InstrumentationKind = JitConfig.JitCollect64BitCounts() + schemaElem.InstrumentationKind = compiler->opts.compCollect64BitCounts ? ICorJitInfo::PgoInstrumentationKind::HandleHistogramLongCount : ICorJitInfo::PgoInstrumentationKind::HandleHistogramIntCount; schemaElem.ILOffset = (int32_t)call->gtHandleHistogramProfileCandidateInfo->ilOffset; diff --git a/src/coreclr/jit/jitconfigvalues.h b/src/coreclr/jit/jitconfigvalues.h index de8a743cbfff72..fd32276e8b5cff 100644 --- a/src/coreclr/jit/jitconfigvalues.h +++ b/src/coreclr/jit/jitconfigvalues.h @@ -561,7 +561,9 @@ CONFIG_STRING(JitEnablePgoRange, W("JitEnablePgoRange")) // Enable pgo d CONFIG_INTEGER(JitRandomEdgeCounts, W("JitRandomEdgeCounts"), 0) // Substitute random values for edge counts CONFIG_INTEGER(JitCrossCheckDevirtualizationAndPGO, W("JitCrossCheckDevirtualizationAndPGO"), 0) CONFIG_INTEGER(JitNoteFailedExactDevirtualization, W("JitNoteFailedExactDevirtualization"), 0) -#endif // debug +CONFIG_INTEGER(JitRandomlyCollect64BitCounts, W("JitRandomlyCollect64BitCounts"), 0) // Collect 64-bit counts randomly + // for some methods. +#endif // debug // Devirtualize virtual calls with getExactClasses (NativeAOT only for now) CONFIG_INTEGER(JitEnableExactDevirtualization, W("JitEnableExactDevirtualization"), 1) diff --git a/src/coreclr/vm/jithelpers.cpp b/src/coreclr/vm/jithelpers.cpp index e2b23d5c5dfae1..86503f3d0efa53 100644 --- a/src/coreclr/vm/jithelpers.cpp +++ b/src/coreclr/vm/jithelpers.cpp @@ -5571,7 +5571,7 @@ HCIMPL2(void, JIT_DelegateProfile32, Object *obj, ICorJitInfo::HandleHistogram32 HCIMPLEND // Version of helper above used when the count is 64-bit -HCIMPL3(void, JIT_DelegateProfile64, Object *obj, CORINFO_METHOD_HANDLE baseMethod, ICorJitInfo::HandleHistogram64* methodProfile) +HCIMPL2(void, JIT_DelegateProfile64, Object *obj, ICorJitInfo::HandleHistogram64* methodProfile) { FCALL_CONTRACT; FC_GC_POLL_NOT_NEEDED(); diff --git a/src/tests/Common/testenvironment.proj b/src/tests/Common/testenvironment.proj index 64f21d76748ae6..85fa1cd07e4f77 100644 --- a/src/tests/Common/testenvironment.proj +++ b/src/tests/Common/testenvironment.proj @@ -66,6 +66,7 @@ COMPlus_JitRandomGuardedDevirtualization; COMPlus_JitRandomEdgeCounts; COMPlus_JitRandomOnStackReplacement; + COMPlus_JitRandomlyCollect64BitCounts; COMPlus_JitForceControlFlowGuard; COMPlus_JitCFGUseDispatcher; RunningIlasmRoundTrip @@ -214,10 +215,10 @@ - - - - + + + + From 8c4e6e2aba31a716e60f8546010b09d848f202d2 Mon Sep 17 00:00:00 2001 From: Jakob Botsch Nielsen Date: Mon, 29 Aug 2022 12:18:47 +0200 Subject: [PATCH 003/107] JIT: Clone all local addresses when importing `dup` (#72714) Roslyn emits `dup` for the field address when compound assignment operators are used on struct fields. We would previously spill this address leading us to mark such structs as address exposed and disabling promotion. Also allow removing unnecessary casts in cases like ``` ASG LCL_FLD ubyte V00 CAST int <- ubyte <- int ... ``` we only allowed this cast removal for LCL_VAR and IND before, which led to unnecessary new casts in some cases with this change. --- src/coreclr/jit/importer.cpp | 67 ++++++++++++++++++++---------------- src/coreclr/jit/morph.cpp | 2 +- 2 files changed, 38 insertions(+), 31 deletions(-) diff --git a/src/coreclr/jit/importer.cpp b/src/coreclr/jit/importer.cpp index bdf66cc22ee459..8afca0e44baee7 100644 --- a/src/coreclr/jit/importer.cpp +++ b/src/coreclr/jit/importer.cpp @@ -15016,53 +15016,60 @@ void Compiler::impImportBlockCode(BasicBlock* block) tiRetVal = se.seTypeInfo; op1 = tree; - // If the expression to dup is simple, just clone it. - // Otherwise spill it to a temp, and reload the temp twice. - bool cloneExpr = false; + // In unoptimized code we leave the decision of + // cloning/creating temps up to impCloneExpr, while in + // optimized code we prefer temps except for some cases we know + // are profitable. - if (!opts.compDbgCode) + if (opts.OptimizationEnabled()) { + bool clone = false; // Duplicate 0 and +0.0 if (op1->IsIntegralConst(0) || op1->IsFloatPositiveZero()) { - cloneExpr = true; + clone = true; } // Duplicate locals and addresses of them else if (op1->IsLocal()) { - cloneExpr = true; + clone = true; } - else if (op1->TypeIs(TYP_BYREF) && op1->OperIs(GT_ADDR) && op1->gtGetOp1()->IsLocal() && + else if (op1->TypeIs(TYP_BYREF, TYP_I_IMPL) && impIsAddressInLocal(op1) && (OPCODE)impGetNonPrefixOpcode(codeAddr + sz, codeEndp) != CEE_INITOBJ) { - cloneExpr = true; + // We mark implicit byrefs with GTF_GLOB_REF (see gtNewFieldRef for why). + // Avoid cloning for these. + clone = (op1->gtFlags & GTF_GLOB_REF) == 0; } - } - else - { - // Always clone for debug mode - cloneExpr = true; - } - if (!cloneExpr) - { - const unsigned tmpNum = lvaGrabTemp(true DEBUGARG("dup spill")); - impAssignTempGen(tmpNum, op1, tiRetVal.GetClassHandle(), (unsigned)CHECK_SPILL_ALL); - var_types type = genActualType(lvaTable[tmpNum].TypeGet()); - op1 = gtNewLclvNode(tmpNum, type); - - // Propagate type info to the temp from the stack and the original tree - if (type == TYP_REF) + if (clone) { - assert(lvaTable[tmpNum].lvSingleDef == 0); - lvaTable[tmpNum].lvSingleDef = 1; - JITDUMP("Marked V%02u as a single def local\n", tmpNum); - lvaSetClass(tmpNum, tree, tiRetVal.GetClassHandle()); + op2 = gtCloneExpr(op1); } - } + else + { + const unsigned tmpNum = lvaGrabTemp(true DEBUGARG("dup spill")); + impAssignTempGen(tmpNum, op1, tiRetVal.GetClassHandle(), (unsigned)CHECK_SPILL_ALL); + var_types type = genActualType(lvaTable[tmpNum].TypeGet()); - op1 = impCloneExpr(op1, &op2, tiRetVal.GetClassHandle(), (unsigned)CHECK_SPILL_ALL, - nullptr DEBUGARG("DUP instruction")); + // Propagate type info to the temp from the stack and the original tree + if (type == TYP_REF) + { + assert(lvaTable[tmpNum].lvSingleDef == 0); + lvaTable[tmpNum].lvSingleDef = 1; + JITDUMP("Marked V%02u as a single def local\n", tmpNum); + lvaSetClass(tmpNum, tree, tiRetVal.GetClassHandle()); + } + + op1 = gtNewLclvNode(tmpNum, type); + op2 = gtNewLclvNode(tmpNum, type); + } + } + else + { + op1 = impCloneExpr(op1, &op2, tiRetVal.GetClassHandle(), (unsigned)CHECK_SPILL_ALL, + nullptr DEBUGARG("DUP instruction")); + } assert(!(op1->gtFlags & GTF_GLOB_EFFECT) && !(op2->gtFlags & GTF_GLOB_EFFECT)); impPushOnStack(op1, tiRetVal); diff --git a/src/coreclr/jit/morph.cpp b/src/coreclr/jit/morph.cpp index d6d8e4c34d2661..7155c18207f7e7 100644 --- a/src/coreclr/jit/morph.cpp +++ b/src/coreclr/jit/morph.cpp @@ -11840,7 +11840,7 @@ GenTree* Compiler::fgOptimizeCastOnAssignment(GenTreeOp* asg) GenTree* const effectiveOp1 = op1->gtEffectiveVal(); - if (!effectiveOp1->OperIs(GT_IND, GT_LCL_VAR)) + if (!effectiveOp1->OperIs(GT_IND, GT_LCL_VAR, GT_LCL_FLD)) return asg; if (effectiveOp1->OperIs(GT_LCL_VAR) && From 11f65fd7240fc104bbe4f72fc9133dcc27d1b963 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Mon, 29 Aug 2022 07:13:08 -0400 Subject: [PATCH 004/107] Fix mentioned default value of DOTNET_TC_OnStackReplacement_InitialCounter (#74729) --- docs/design/features/OsrDetailsAndDebugging.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/design/features/OsrDetailsAndDebugging.md b/docs/design/features/OsrDetailsAndDebugging.md index 60d697473c147b..3ca35c2b9198eb 100644 --- a/docs/design/features/OsrDetailsAndDebugging.md +++ b/docs/design/features/OsrDetailsAndDebugging.md @@ -172,7 +172,7 @@ During the patchpoint phase, if any block was marked, the jit adds a new integer local to the method (the patchpoint counter) and adds IR to initialize the counter on method entry to the value of `DOTNET_TC_OnStackReplacement_InitialCounter` (by default this is -0x1000). +1000). At each marked block the JIT adds code to decrement the counter and conditionally invoke `CORINFO_HELP_PATCHPOINT` if the counter value is zero @@ -492,4 +492,4 @@ In the performance repo configurations we reduce the number of warmup iterations ## References * [OSR Design Document](https://github.com/dotnet/runtime/blob/main/docs/design/features/OnStackReplacement.md). May be a bit dated in places. -* [OSR Next Steps Issue](https://github.com/dotnet/runtime/issues/33658). Has a lot of information on issues encountered during bring-up, current limitations, and ideas for things we might revisit. \ No newline at end of file +* [OSR Next Steps Issue](https://github.com/dotnet/runtime/issues/33658). Has a lot of information on issues encountered during bring-up, current limitations, and ideas for things we might revisit. From 4b432474db7aad1fd831c551b5cdc5a63bcfd78a Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 29 Aug 2022 14:20:35 +0300 Subject: [PATCH 005/107] Retry logic for distributed transactions test (#74648) To make them resilient in the face of MSDTC flakiness in CI. Fixes #74120 --- .../tests/OleTxTests.cs | 617 +++++++++--------- 1 file changed, 295 insertions(+), 322 deletions(-) diff --git a/src/libraries/System.Transactions.Local/tests/OleTxTests.cs b/src/libraries/System.Transactions.Local/tests/OleTxTests.cs index 8ff6a221da1e7b..6a97aed542a13f 100644 --- a/src/libraries/System.Transactions.Local/tests/OleTxTests.cs +++ b/src/libraries/System.Transactions.Local/tests/OleTxTests.cs @@ -27,250 +27,230 @@ public OleTxTests(OleTxFixture fixture) [InlineData(Phase1Vote.Prepared, Phase1Vote.ForceRollback, EnlistmentOutcome.Aborted, EnlistmentOutcome.Aborted, TransactionStatus.Aborted)] [InlineData(Phase1Vote.ForceRollback, Phase1Vote.Prepared, EnlistmentOutcome.Aborted, EnlistmentOutcome.Aborted, TransactionStatus.Aborted)] public void Two_durable_enlistments_commit(Phase1Vote vote1, Phase1Vote vote2, EnlistmentOutcome expectedOutcome1, EnlistmentOutcome expectedOutcome2, TransactionStatus expectedTxStatus) - { - if (!Environment.Is64BitProcess || PlatformDetection.IsArm64Process) + => Test(() => { - // Temporarily skip on 32-bit where we have an issue - // ARM64 issue: https://github.com/dotnet/runtime/issues/74170 - return; - } - - using var tx = new CommittableTransaction(); + using var tx = new CommittableTransaction(); - try - { - var enlistment1 = new TestEnlistment(vote1, expectedOutcome1); - var enlistment2 = new TestEnlistment(vote2, expectedOutcome2); + try + { + var enlistment1 = new TestEnlistment(vote1, expectedOutcome1); + var enlistment2 = new TestEnlistment(vote2, expectedOutcome2); - tx.EnlistDurable(Guid.NewGuid(), enlistment1, EnlistmentOptions.None); - tx.EnlistDurable(Guid.NewGuid(), enlistment2, EnlistmentOptions.None); + tx.EnlistDurable(Guid.NewGuid(), enlistment1, EnlistmentOptions.None); + tx.EnlistDurable(Guid.NewGuid(), enlistment2, EnlistmentOptions.None); - Assert.Equal(TransactionStatus.Active, tx.TransactionInformation.Status); - tx.Commit(); - } - catch (TransactionInDoubtException) - { - Assert.Equal(TransactionStatus.InDoubt, expectedTxStatus); - } - catch (TransactionAbortedException) - { - Assert.Equal(TransactionStatus.Aborted, expectedTxStatus); - } + Assert.Equal(TransactionStatus.Active, tx.TransactionInformation.Status); + tx.Commit(); + } + catch (TransactionInDoubtException) + { + Assert.Equal(TransactionStatus.InDoubt, expectedTxStatus); + } + catch (TransactionAbortedException) + { + Assert.Equal(TransactionStatus.Aborted, expectedTxStatus); + } - Retry(() => Assert.Equal(expectedTxStatus, tx.TransactionInformation.Status)); - } + Retry(() => Assert.Equal(expectedTxStatus, tx.TransactionInformation.Status)); + }); [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] public void Two_durable_enlistments_rollback() - { - if (!Environment.Is64BitProcess || PlatformDetection.IsArm64Process) + => Test(() => { - // Temporarily skip on 32-bit where we have an issue - // ARM64 issue: https://github.com/dotnet/runtime/issues/74170 - return; - } - - using var tx = new CommittableTransaction(); + using var tx = new CommittableTransaction(); - var enlistment1 = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Aborted); - var enlistment2 = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Aborted); + var enlistment1 = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Aborted); + var enlistment2 = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Aborted); - tx.EnlistDurable(Guid.NewGuid(), enlistment1, EnlistmentOptions.None); - tx.EnlistDurable(Guid.NewGuid(), enlistment2, EnlistmentOptions.None); + tx.EnlistDurable(Guid.NewGuid(), enlistment1, EnlistmentOptions.None); + tx.EnlistDurable(Guid.NewGuid(), enlistment2, EnlistmentOptions.None); - tx.Rollback(); + tx.Rollback(); - Assert.False(enlistment1.WasPreparedCalled); - Assert.False(enlistment2.WasPreparedCalled); + Assert.False(enlistment1.WasPreparedCalled); + Assert.False(enlistment2.WasPreparedCalled); - // This matches the .NET Framework behavior - Retry(() => Assert.Equal(TransactionStatus.Aborted, tx.TransactionInformation.Status)); - } + // This matches the .NET Framework behavior + Retry(() => Assert.Equal(TransactionStatus.Aborted, tx.TransactionInformation.Status)); + }); [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] [InlineData(0)] [InlineData(1)] [InlineData(2)] public void Volatile_and_durable_enlistments(int volatileCount) - { - if (!Environment.Is64BitProcess || PlatformDetection.IsArm64Process) + => Test(() => { - // Temporarily skip on 32-bit where we have an issue - // ARM64 issue: https://github.com/dotnet/runtime/issues/74170 - return; - } - - using var tx = new CommittableTransaction(); + using var tx = new CommittableTransaction(); - if (volatileCount > 0) - { - TestEnlistment[] volatiles = new TestEnlistment[volatileCount]; - for (int i = 0; i < volatileCount; i++) + if (volatileCount > 0) { - // It doesn't matter what we specify for SinglePhaseVote. - volatiles[i] = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed); - tx.EnlistVolatile(volatiles[i], EnlistmentOptions.None); + TestEnlistment[] volatiles = new TestEnlistment[volatileCount]; + for (int i = 0; i < volatileCount; i++) + { + // It doesn't matter what we specify for SinglePhaseVote. + volatiles[i] = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed); + tx.EnlistVolatile(volatiles[i], EnlistmentOptions.None); + } } - } - var durable = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed); + var durable = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed); - // Creation of two phase durable enlistment attempts to promote to MSDTC - tx.EnlistDurable(Guid.NewGuid(), durable, EnlistmentOptions.None); + // Creation of two phase durable enlistment attempts to promote to MSDTC + tx.EnlistDurable(Guid.NewGuid(), durable, EnlistmentOptions.None); - tx.Commit(); + tx.Commit(); - Retry(() => Assert.Equal(TransactionStatus.Committed, tx.TransactionInformation.Status)); - } + Retry(() => Assert.Equal(TransactionStatus.Committed, tx.TransactionInformation.Status)); + }); protected static bool IsRemoteExecutorSupportedAndNotNano => RemoteExecutor.IsSupported && PlatformDetection.IsNotWindowsNanoServer; [ConditionalFact(nameof(IsRemoteExecutorSupportedAndNotNano))] public void Promotion() { - if (!Environment.Is64BitProcess || PlatformDetection.IsArm64Process) + Test(() => { - // Temporarily skip on 32-bit where we have an issue - // ARM64 issue: https://github.com/dotnet/runtime/issues/74170 - return; - } - - // This simulates the full promotable flow, as implemented for SQL Server. - - // We are going to spin up two external processes. - // 1. The 1st external process will create the transaction and save its propagation token to disk. - // 2. The main process will read that, and propagate the transaction to the 2nd external process. - // 3. The main process will then notify the 1st external process to commit (as the main's transaction is delegated to it). - // 4. At that point the MSDTC Commit will be triggered; enlistments on both the 1st and 2nd processes will be notified - // to commit, and the transaction status will reflect the committed status in the main process. - using var tx = new CommittableTransaction(); - - string propagationTokenFilePath = Path.GetTempFileName(); - string exportCookieFilePath = Path.GetTempFileName(); - using var waitHandle1 = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Promotion1"); - using var waitHandle2 = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Promotion2"); - using var waitHandle3 = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Promotion3"); + // This simulates the full promotable flow, as implemented for SQL Server. + + // We are going to spin up two external processes. + // 1. The 1st external process will create the transaction and save its propagation token to disk. + // 2. The main process will read that, and propagate the transaction to the 2nd external process. + // 3. The main process will then notify the 1st external process to commit (as the main's transaction is delegated to it). + // 4. At that point the MSDTC Commit will be triggered; enlistments on both the 1st and 2nd processes will be notified + // to commit, and the transaction status will reflect the committed status in the main process. + using var tx = new CommittableTransaction(); - RemoteInvokeHandle? remote1 = null, remote2 = null; + string propagationTokenFilePath = Path.GetTempFileName(); + string exportCookieFilePath = Path.GetTempFileName(); + using var waitHandle1 = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Promotion1"); + using var waitHandle2 = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Promotion2"); + using var waitHandle3 = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Promotion3"); - try - { - remote1 = RemoteExecutor.Invoke(Remote1, propagationTokenFilePath, new RemoteInvokeOptions { ExpectedExitCode = 42 }); - - // Wait for the external process to start a transaction and save its propagation token - Assert.True(waitHandle1.WaitOne(Timeout)); - - // Enlist the first PSPE. No escalation happens yet, since its the only enlistment. - var pspe1 = new TestPromotableSinglePhaseNotification(propagationTokenFilePath); - Assert.True(tx.EnlistPromotableSinglePhase(pspe1)); - Assert.True(pspe1.WasInitializedCalled); - Assert.False(pspe1.WasPromoteCalled); - Assert.False(pspe1.WasRollbackCalled); - Assert.False(pspe1.WasSinglePhaseCommitCalled); - - // Enlist the second PSPE. This returns false and does nothing, since there's already an enlistment. - var pspe2 = new TestPromotableSinglePhaseNotification(propagationTokenFilePath); - Assert.False(tx.EnlistPromotableSinglePhase(pspe2)); - Assert.False(pspe2.WasInitializedCalled); - Assert.False(pspe2.WasPromoteCalled); - Assert.False(pspe2.WasRollbackCalled); - Assert.False(pspe2.WasSinglePhaseCommitCalled); - - // Now generate an export cookie for the 2nd external process. This causes escalation and promotion. - byte[] whereabouts = TransactionInterop.GetWhereabouts(); - byte[] exportCookie = TransactionInterop.GetExportCookie(tx, whereabouts); - - Assert.True(pspe1.WasPromoteCalled); - Assert.False(pspe1.WasRollbackCalled); - Assert.False(pspe1.WasSinglePhaseCommitCalled); - - // Write the export cookie and start the 2nd external process, which will read the cookie and enlist in the transaction. - // Wait for it to complete. - File.WriteAllBytes(exportCookieFilePath, exportCookie); - remote2 = RemoteExecutor.Invoke(Remote2, exportCookieFilePath, new RemoteInvokeOptions { ExpectedExitCode = 42 }); - Assert.True(waitHandle2.WaitOne(Timeout)); - - // We now have two external processes with enlistments to our distributed transaction. Commit. - // Since our transaction is delegated to the 1st PSPE enlistment, Sys.Tx will call SinglePhaseCommit on it. - // In SQL Server this contacts the 1st DB to actually commit the transaction with MSDTC. In this simulation we'll just use a wait handle to trigger this. - tx.Commit(); - Assert.True(pspe1.WasSinglePhaseCommitCalled); - waitHandle3.Set(); + RemoteInvokeHandle? remote1 = null, remote2 = null; - Retry(() => Assert.Equal(TransactionStatus.Committed, tx.TransactionInformation.Status)); - } - catch - { try { - remote1?.Process.Kill(); - remote2?.Process.Kill(); + remote1 = RemoteExecutor.Invoke(Remote1, propagationTokenFilePath, new RemoteInvokeOptions { ExpectedExitCode = 42 }); + + // Wait for the external process to start a transaction and save its propagation token + Assert.True(waitHandle1.WaitOne(Timeout)); + + // Enlist the first PSPE. No escalation happens yet, since its the only enlistment. + var pspe1 = new TestPromotableSinglePhaseNotification(propagationTokenFilePath); + Assert.True(tx.EnlistPromotableSinglePhase(pspe1)); + Assert.True(pspe1.WasInitializedCalled); + Assert.False(pspe1.WasPromoteCalled); + Assert.False(pspe1.WasRollbackCalled); + Assert.False(pspe1.WasSinglePhaseCommitCalled); + + // Enlist the second PSPE. This returns false and does nothing, since there's already an enlistment. + var pspe2 = new TestPromotableSinglePhaseNotification(propagationTokenFilePath); + Assert.False(tx.EnlistPromotableSinglePhase(pspe2)); + Assert.False(pspe2.WasInitializedCalled); + Assert.False(pspe2.WasPromoteCalled); + Assert.False(pspe2.WasRollbackCalled); + Assert.False(pspe2.WasSinglePhaseCommitCalled); + + // Now generate an export cookie for the 2nd external process. This causes escalation and promotion. + byte[] whereabouts = TransactionInterop.GetWhereabouts(); + byte[] exportCookie = TransactionInterop.GetExportCookie(tx, whereabouts); + + Assert.True(pspe1.WasPromoteCalled); + Assert.False(pspe1.WasRollbackCalled); + Assert.False(pspe1.WasSinglePhaseCommitCalled); + + // Write the export cookie and start the 2nd external process, which will read the cookie and enlist in the transaction. + // Wait for it to complete. + File.WriteAllBytes(exportCookieFilePath, exportCookie); + remote2 = RemoteExecutor.Invoke(Remote2, exportCookieFilePath, new RemoteInvokeOptions { ExpectedExitCode = 42 }); + Assert.True(waitHandle2.WaitOne(Timeout)); + + // We now have two external processes with enlistments to our distributed transaction. Commit. + // Since our transaction is delegated to the 1st PSPE enlistment, Sys.Tx will call SinglePhaseCommit on it. + // In SQL Server this contacts the 1st DB to actually commit the transaction with MSDTC. In this simulation we'll just use a wait handle to trigger this. + tx.Commit(); + Assert.True(pspe1.WasSinglePhaseCommitCalled); + waitHandle3.Set(); + + Retry(() => Assert.Equal(TransactionStatus.Committed, tx.TransactionInformation.Status)); } catch { - } + try + { + remote1?.Process.Kill(); + remote2?.Process.Kill(); + } + catch + { + } - throw; - } - finally - { - File.Delete(propagationTokenFilePath); - } + throw; + } + finally + { + File.Delete(propagationTokenFilePath); + } - // Disposal of the RemoteExecutor handles will wait for the external processes to exit with the right exit code, - // which will happen when their enlistments receive the commit. - remote1?.Dispose(); - remote2?.Dispose(); + // Disposal of the RemoteExecutor handles will wait for the external processes to exit with the right exit code, + // which will happen when their enlistments receive the commit. + remote1?.Dispose(); + remote2?.Dispose(); + }); static void Remote1(string propagationTokenFilePath) - { - using var tx = new CommittableTransaction(); + => Test(() => + { + using var tx = new CommittableTransaction(); - var outcomeEvent = new AutoResetEvent(false); - var enlistment = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed, outcomeReceived: outcomeEvent); - tx.EnlistDurable(Guid.NewGuid(), enlistment, EnlistmentOptions.None); + var outcomeEvent = new AutoResetEvent(false); + var enlistment = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed, outcomeReceived: outcomeEvent); + tx.EnlistDurable(Guid.NewGuid(), enlistment, EnlistmentOptions.None); - // We now have an OleTx transaction. Save its propagation token to disk so that the main process can read it when promoting. - byte[] propagationToken = TransactionInterop.GetTransmitterPropagationToken(tx); - File.WriteAllBytes(propagationTokenFilePath, propagationToken); + // We now have an OleTx transaction. Save its propagation token to disk so that the main process can read it when promoting. + byte[] propagationToken = TransactionInterop.GetTransmitterPropagationToken(tx); + File.WriteAllBytes(propagationTokenFilePath, propagationToken); - // Signal to the main process that the propagation token is ready to be read - using var waitHandle1 = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Promotion1"); - waitHandle1.Set(); + // Signal to the main process that the propagation token is ready to be read + using var waitHandle1 = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Promotion1"); + waitHandle1.Set(); - // The main process will now import our transaction via the propagation token, and propagate it to a 2nd process. - // In the main process the transaction is delegated; we're the one who started it, and so we're the one who need to Commit. - // When Commit() is called in the main process, that will trigger a SinglePhaseCommit on the PSPE which represents us. In SQL Server this - // contacts the DB to actually commit the transaction with MSDTC. In this simulation we'll just use the wait handle again to trigger this. - using var waitHandle3 = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Promotion3"); - Assert.True(waitHandle3.WaitOne(Timeout)); + // The main process will now import our transaction via the propagation token, and propagate it to a 2nd process. + // In the main process the transaction is delegated; we're the one who started it, and so we're the one who need to Commit. + // When Commit() is called in the main process, that will trigger a SinglePhaseCommit on the PSPE which represents us. In SQL Server this + // contacts the DB to actually commit the transaction with MSDTC. In this simulation we'll just use the wait handle again to trigger this. + using var waitHandle3 = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Promotion3"); + Assert.True(waitHandle3.WaitOne(Timeout)); - tx.Commit(); + tx.Commit(); - // Wait for the commit to occur on our enlistment, then exit successfully. - Assert.True(outcomeEvent.WaitOne(Timeout)); - Environment.Exit(42); // 42 is error code expected by RemoteExecutor - } + // Wait for the commit to occur on our enlistment, then exit successfully. + Assert.True(outcomeEvent.WaitOne(Timeout)); + Environment.Exit(42); // 42 is error code expected by RemoteExecutor + }); static void Remote2(string exportCookieFilePath) - { - // Load the export cookie and enlist durably - byte[] exportCookie = File.ReadAllBytes(exportCookieFilePath); - using var tx = TransactionInterop.GetTransactionFromExportCookie(exportCookie); - - // Now enlist durably. This triggers promotion of the first PSPE, reading the propagation token. - var outcomeEvent = new AutoResetEvent(false); - var enlistment = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed, outcomeReceived: outcomeEvent); - tx.EnlistDurable(Guid.NewGuid(), enlistment, EnlistmentOptions.None); - - // Signal to the main process that we're enlisted and ready to commit - using var waitHandle = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Promotion2"); - waitHandle.Set(); - - // Wait for the main process to commit the transaction - Assert.True(outcomeEvent.WaitOne(Timeout)); - Environment.Exit(42); // 42 is error code expected by RemoteExecutor - } + => Test(() => + { + // Load the export cookie and enlist durably + byte[] exportCookie = File.ReadAllBytes(exportCookieFilePath); + using var tx = TransactionInterop.GetTransactionFromExportCookie(exportCookie); + + // Now enlist durably. This triggers promotion of the first PSPE, reading the propagation token. + var outcomeEvent = new AutoResetEvent(false); + var enlistment = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed, outcomeReceived: outcomeEvent); + tx.EnlistDurable(Guid.NewGuid(), enlistment, EnlistmentOptions.None); + + // Signal to the main process that we're enlisted and ready to commit + using var waitHandle = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Promotion2"); + waitHandle.Set(); + + // Wait for the main process to commit the transaction + Assert.True(outcomeEvent.WaitOne(Timeout)); + Environment.Exit(42); // 42 is error code expected by RemoteExecutor + }); } public class TestPromotableSinglePhaseNotification : IPromotableSinglePhaseNotification @@ -309,90 +289,87 @@ public void SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment) [ConditionalFact(nameof(IsRemoteExecutorSupportedAndNotNano))] public void Recovery() { - if (!Environment.Is64BitProcess || PlatformDetection.IsArm64Process) + Test(() => { - // Temporarily skip on 32-bit where we have an issue - // ARM64 issue: https://github.com/dotnet/runtime/issues/74170 - return; - } + // We are going to spin up an external process to also enlist in the transaction, and then to crash when it + // receives the commit notification. We will then initiate the recovery flow. - // We are going to spin up an external process to also enlist in the transaction, and then to crash when it - // receives the commit notification. We will then initiate the recovery flow. - - using var tx = new CommittableTransaction(); + using var tx = new CommittableTransaction(); - var outcomeEvent1 = new AutoResetEvent(false); - var enlistment1 = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed, outcomeReceived: outcomeEvent1); - var guid1 = Guid.NewGuid(); - tx.EnlistDurable(guid1, enlistment1, EnlistmentOptions.None); + var outcomeEvent1 = new AutoResetEvent(false); + var enlistment1 = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed, outcomeReceived: outcomeEvent1); + var guid1 = Guid.NewGuid(); + tx.EnlistDurable(guid1, enlistment1, EnlistmentOptions.None); - // The propagation token is used to propagate the transaction to that process so it can enlist to our - // transaction. We also provide the resource manager identifier GUID, and a path where the external process will - // write the recovery information it will receive from the MSDTC when preparing. - // We'll need these two elements later in order to Reenlist and trigger recovery. - byte[] propagationToken = TransactionInterop.GetTransmitterPropagationToken(tx); - string propagationTokenText = Convert.ToBase64String(propagationToken); - var guid2 = Guid.NewGuid(); - string secondEnlistmentRecoveryFilePath = Path.GetTempFileName(); + // The propagation token is used to propagate the transaction to that process so it can enlist to our + // transaction. We also provide the resource manager identifier GUID, and a path where the external process will + // write the recovery information it will receive from the MSDTC when preparing. + // We'll need these two elements later in order to Reenlist and trigger recovery. + byte[] propagationToken = TransactionInterop.GetTransmitterPropagationToken(tx); + string propagationTokenText = Convert.ToBase64String(propagationToken); + var guid2 = Guid.NewGuid(); + string secondEnlistmentRecoveryFilePath = Path.GetTempFileName(); - using var waitHandle = new EventWaitHandle( - initialState: false, - EventResetMode.ManualReset, - "System.Transactions.Tests.OleTxTests.Recovery"); + using var waitHandle = new EventWaitHandle( + initialState: false, + EventResetMode.ManualReset, + "System.Transactions.Tests.OleTxTests.Recovery"); - try - { - using (RemoteExecutor.Invoke( - EnlistAndCrash, - propagationTokenText, guid2.ToString(), secondEnlistmentRecoveryFilePath, - new RemoteInvokeOptions { ExpectedExitCode = 42 })) + try { - // Wait for the external process to enlist in the transaction, it will signal this EventWaitHandle. - Assert.True(waitHandle.WaitOne(Timeout)); + using (RemoteExecutor.Invoke( + EnlistAndCrash, + propagationTokenText, guid2.ToString(), secondEnlistmentRecoveryFilePath, + new RemoteInvokeOptions { ExpectedExitCode = 42 })) + { + // Wait for the external process to enlist in the transaction, it will signal this EventWaitHandle. + Assert.True(waitHandle.WaitOne(Timeout)); - tx.Commit(); - } + tx.Commit(); + } - // The other has crashed when the MSDTC notified it to commit. - // Load the recovery information the other process has written to disk for us and reenlist with - // the failed RM's Guid to commit. - var outcomeEvent3 = new AutoResetEvent(false); - var enlistment3 = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed, outcomeReceived: outcomeEvent3); - byte[] secondRecoveryInformation = File.ReadAllBytes(secondEnlistmentRecoveryFilePath); - _ = TransactionManager.Reenlist(guid2, secondRecoveryInformation, enlistment3); - TransactionManager.RecoveryComplete(guid2); - - Assert.True(outcomeEvent1.WaitOne(Timeout)); - Assert.True(outcomeEvent3.WaitOne(Timeout)); - Assert.Equal(EnlistmentOutcome.Committed, enlistment1.Outcome); - Assert.Equal(EnlistmentOutcome.Committed, enlistment3.Outcome); - Assert.Equal(TransactionStatus.Committed, tx.TransactionInformation.Status); - - // Note: verify manually in the MSDTC console that the distributed transaction is gone - // (i.e. successfully committed), - // (Start -> Component Services -> Computers -> My Computer -> Distributed Transaction Coordinator -> - // Local DTC -> Transaction List) - } - finally - { - File.Delete(secondEnlistmentRecoveryFilePath); - } + // The other has crashed when the MSDTC notified it to commit. + // Load the recovery information the other process has written to disk for us and reenlist with + // the failed RM's Guid to commit. + var outcomeEvent3 = new AutoResetEvent(false); + var enlistment3 = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed, outcomeReceived: outcomeEvent3); + byte[] secondRecoveryInformation = File.ReadAllBytes(secondEnlistmentRecoveryFilePath); + _ = TransactionManager.Reenlist(guid2, secondRecoveryInformation, enlistment3); + TransactionManager.RecoveryComplete(guid2); + + Assert.True(outcomeEvent1.WaitOne(Timeout)); + Assert.True(outcomeEvent3.WaitOne(Timeout)); + Assert.Equal(EnlistmentOutcome.Committed, enlistment1.Outcome); + Assert.Equal(EnlistmentOutcome.Committed, enlistment3.Outcome); + Assert.Equal(TransactionStatus.Committed, tx.TransactionInformation.Status); + + // Note: verify manually in the MSDTC console that the distributed transaction is gone + // (i.e. successfully committed), + // (Start -> Component Services -> Computers -> My Computer -> Distributed Transaction Coordinator -> + // Local DTC -> Transaction List) + } + finally + { + File.Delete(secondEnlistmentRecoveryFilePath); + } + }); static void EnlistAndCrash(string propagationTokenText, string resourceManagerIdentifierGuid, string recoveryInformationFilePath) - { - byte[] propagationToken = Convert.FromBase64String(propagationTokenText); - using var tx = TransactionInterop.GetTransactionFromTransmitterPropagationToken(propagationToken); + => Test(() => + { + byte[] propagationToken = Convert.FromBase64String(propagationTokenText); + using var tx = TransactionInterop.GetTransactionFromTransmitterPropagationToken(propagationToken); - var crashingEnlistment = new CrashingEnlistment(recoveryInformationFilePath); - tx.EnlistDurable(Guid.Parse(resourceManagerIdentifierGuid), crashingEnlistment, EnlistmentOptions.None); + var crashingEnlistment = new CrashingEnlistment(recoveryInformationFilePath); + tx.EnlistDurable(Guid.Parse(resourceManagerIdentifierGuid), crashingEnlistment, EnlistmentOptions.None); - // Signal to the main process that we've enlisted and are ready to accept prepare/commit. - using var waitHandle = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Recovery"); - waitHandle.Set(); + // Signal to the main process that we've enlisted and are ready to accept prepare/commit. + using var waitHandle = new EventWaitHandle(initialState: false, EventResetMode.ManualReset, "System.Transactions.Tests.OleTxTests.Recovery"); + waitHandle.Set(); - // We've enlisted, and set it up so that when the MSDTC tells us to commit, the process will crash. - Thread.Sleep(Timeout); - } + // We've enlisted, and set it up so that when the MSDTC tells us to commit, the process will crash. + Thread.Sleep(Timeout); + }); } public class CrashingEnlistment : IEnlistmentNotification @@ -422,50 +399,71 @@ public void InDoubt(Enlistment enlistment) [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] public void TransmitterPropagationToken() - { - if (!Environment.Is64BitProcess || PlatformDetection.IsArm64Process) + => Test(() => { - // Temporarily skip on 32-bit where we have an issue - // ARM64 issue: https://github.com/dotnet/runtime/issues/74170 - return; - } + using var tx = new CommittableTransaction(); - using var tx = new CommittableTransaction(); + Assert.Equal(Guid.Empty, tx.TransactionInformation.DistributedIdentifier); - Assert.Equal(Guid.Empty, tx.TransactionInformation.DistributedIdentifier); + var propagationToken = TransactionInterop.GetTransmitterPropagationToken(tx); - var propagationToken = TransactionInterop.GetTransmitterPropagationToken(tx); + Assert.NotEqual(Guid.Empty, tx.TransactionInformation.DistributedIdentifier); - Assert.NotEqual(Guid.Empty, tx.TransactionInformation.DistributedIdentifier); + var tx2 = TransactionInterop.GetTransactionFromTransmitterPropagationToken(propagationToken); - var tx2 = TransactionInterop.GetTransactionFromTransmitterPropagationToken(propagationToken); - - Assert.Equal(tx.TransactionInformation.DistributedIdentifier, tx2.TransactionInformation.DistributedIdentifier); - } + Assert.Equal(tx.TransactionInformation.DistributedIdentifier, tx2.TransactionInformation.DistributedIdentifier); + }); [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] public void GetExportCookie() - { - if (!Environment.Is64BitProcess || PlatformDetection.IsArm64Process) + => Test(() => { - // Temporarily skip on 32-bit where we have an issue - // ARM64 issue: https://github.com/dotnet/runtime/issues/74170 - return; - } + using var tx = new CommittableTransaction(); + + var whereabouts = TransactionInterop.GetWhereabouts(); + + Assert.Equal(Guid.Empty, tx.TransactionInformation.DistributedIdentifier); + + var exportCookie = TransactionInterop.GetExportCookie(tx, whereabouts); - using var tx = new CommittableTransaction(); + Assert.NotEqual(Guid.Empty, tx.TransactionInformation.DistributedIdentifier); - var whereabouts = TransactionInterop.GetWhereabouts(); + var tx2 = TransactionInterop.GetTransactionFromExportCookie(exportCookie); - Assert.Equal(Guid.Empty, tx.TransactionInformation.DistributedIdentifier); + Assert.Equal(tx.TransactionInformation.DistributedIdentifier, tx2.TransactionInformation.DistributedIdentifier); + }); - var exportCookie = TransactionInterop.GetExportCookie(tx, whereabouts); + private static void Test(Action action) + { + // Temporarily skip on 32-bit where we have an issue. + // ARM64 issue: https://github.com/dotnet/runtime/issues/74170 + if (!Environment.Is64BitProcess || PlatformDetection.IsArm64Process) + { + return; + } - Assert.NotEqual(Guid.Empty, tx.TransactionInformation.DistributedIdentifier); + // In CI, we sometimes get XACT_E_TMNOTAVAILABLE; when it happens, it's typically on the very first + // attempt to connect to MSDTC (flaky/slow on-demand startup of MSDTC), though not only. + // This catches that error and retries. + int nRetries = 5; - var tx2 = TransactionInterop.GetTransactionFromExportCookie(exportCookie); + while (true) + { + try + { + action(); + return; + } + catch (TransactionException e) when (e.InnerException is TransactionManagerCommunicationException) + { + if (--nRetries == 0) + { + throw; + } - Assert.Equal(tx.TransactionInformation.DistributedIdentifier, tx2.TransactionInformation.DistributedIdentifier); + Thread.Sleep(500); + } + } } // MSDTC is aynchronous, i.e. Commit/Rollback may return before the transaction has actually completed; @@ -495,46 +493,21 @@ private static void Retry(Action action) public class OleTxFixture { + // In CI, we sometimes get XACT_E_TMNOTAVAILABLE on the very first attempt to connect to MSDTC; + // this is likely due to on-demand slow startup of MSDTC. Perform pre-test connecting with retry + // to ensure that MSDTC is properly up when the first test runs. public OleTxFixture() - { - if (!Environment.Is64BitProcess || PlatformDetection.IsArm64Process) - { - // Temporarily skip on 32-bit where we have an issue - // ARM64 issue: https://github.com/dotnet/runtime/issues/74170 - return; - } - - // In CI, we sometimes get XACT_E_TMNOTAVAILABLE on the very first attempt to connect to MSDTC; - // this is likely due to on-demand slow startup of MSDTC. Perform pre-test connecting with retry - // to ensure that MSDTC is properly up when the first test runs. - int nRetries = 5; - - while (true) + => Test(() => { - try - { - using var tx = new CommittableTransaction(); + using var tx = new CommittableTransaction(); - var enlistment1 = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed); - var enlistment2 = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed); + var enlistment1 = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed); + var enlistment2 = new TestEnlistment(Phase1Vote.Prepared, EnlistmentOutcome.Committed); - tx.EnlistDurable(Guid.NewGuid(), enlistment1, EnlistmentOptions.None); - tx.EnlistDurable(Guid.NewGuid(), enlistment2, EnlistmentOptions.None); + tx.EnlistDurable(Guid.NewGuid(), enlistment1, EnlistmentOptions.None); + tx.EnlistDurable(Guid.NewGuid(), enlistment2, EnlistmentOptions.None); - tx.Commit(); - - return; - } - catch (TransactionException e) when (e.InnerException is TransactionManagerCommunicationException) - { - if (--nRetries == 0) - { - throw; - } - - Thread.Sleep(100); - } - } - } + tx.Commit(); + }); } } From 1c6752813014463c93ae753ee45994284878f007 Mon Sep 17 00:00:00 2001 From: Lakshan Fernando Date: Mon, 29 Aug 2022 04:36:03 -0700 Subject: [PATCH 006/107] Discourage using explicit package references to ILCompiler to publish (#74591) * Show a warning when an explicit package reference to ILCompiler is added * Apply suggestions from code review Co-authored-by: Jan Kotas * Fix issue 27239 * Apply suggestions from code review Co-authored-by: Sven Boemer * exclude the warning for direct targets file invoke cases Co-authored-by: Jan Kotas Co-authored-by: Sven Boemer --- ...soft.DotNet.ILCompiler.SingleEntry.targets | 15 +++++++++------ .../Microsoft.DotNet.ILCompiler.props | 2 -- src/coreclr/nativeaot/docs/compiling.md | 19 ++++++++++++++++--- 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.SingleEntry.targets b/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.SingleEntry.targets index 0018c70f987796..67cd1b2ceb5c0d 100644 --- a/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.SingleEntry.targets +++ b/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.SingleEntry.targets @@ -36,15 +36,18 @@ SetupProperties - - - <_PackageReferenceExceptILCompiler Include="@(PackageReference)" Exclude="Microsoft.DotNet.ILCompiler" /> - <_ILCompilerPackageReference Include="@(PackageReference)" Exclude="@(_PackageReferenceExceptILCompiler)" /> - - @(_ILCompilerPackageReference->'%(Version)') + + + + $([System.IO.Path]::GetFileName($([System.IO.Path]::GetDirectoryName($([System.IO.Path]::GetDirectoryName($(ILCompilerTargetsPath))))))) + + + + + diff --git a/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.props b/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.props index e0cc69015b8e16..c2f2f45bce605b 100644 --- a/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.props +++ b/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.props @@ -11,8 +11,6 @@ Copyright (c) .NET Foundation. All rights reserved. --> - - true $(MSBuildThisFileDirectory)Microsoft.DotNet.ILCompiler.SingleEntry.targets diff --git a/src/coreclr/nativeaot/docs/compiling.md b/src/coreclr/nativeaot/docs/compiling.md index 1b4475a89362d3..f142fa3afecb17 100644 --- a/src/coreclr/nativeaot/docs/compiling.md +++ b/src/coreclr/nativeaot/docs/compiling.md @@ -2,8 +2,7 @@ Please consult [documentation](https://docs.microsoft.com/dotnet/core/deploying/native-aot) for instructions how to compile and publish application. -The rest of this document covers advanced topics only. - +The rest of this document covers advanced topics only. Adding an explicit package reference to `Microsoft.DotNet.ILCompiler` will generate warning when publishing and it can run into version errors. When possible, use the PublishAot property to publish a native AOT application. ## Using daily builds @@ -34,7 +33,21 @@ or by adding the following element to the project file: ## Cross-architecture compilation -Native AOT toolchain allows targeting ARM64 on an x64 host and vice versa for both Windows and Linux. Cross-OS compilation, such as targeting Linux on a Windows host, is not supported. To target win-arm64 on a Windows x64 host, in addition to the `Microsoft.DotNet.ILCompiler` package reference, also add the `runtime.win-x64.Microsoft.DotNet.ILCompiler` package reference to get the x64-hosted compiler: +Native AOT toolchain allows targeting ARM64 on an x64 host and vice versa for both Windows and Linux and is now supported in the SDK. Cross-OS compilation, such as targeting Linux on a Windows host, is not supported. For SDK support, add the following to your project file, + +```xml + + true + +``` + +Targeting win-arm64 on a Windows x64 host machine, + +```bash +> dotnet publish -r win-arm64 -c Release +``` + +To target win-arm64 on a Windows x64 host on an advanced scenario where the SDK support is not sufficient (note that these scenarios will generate warnings for using explicit package references), in addition to the `Microsoft.DotNet.ILCompiler` package reference, also add the `runtime.win-x64.Microsoft.DotNet.ILCompiler` package reference to get the x64-hosted compiler: ```xml ``` From df45afd8471671f2b6f5917a59a2a7b8bde2fca2 Mon Sep 17 00:00:00 2001 From: Thays Grazia Date: Mon, 29 Aug 2022 09:55:26 -0300 Subject: [PATCH 007/107] [wasm][debugger] Fix chinese character in project name (#74516) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix chinese character in project name * Adding more tests as suggested by @radical Renaming variable as suggested by @radical * Update src/mono/wasm/debugger/tests/debugger-test-chinese-char-in-path-ㄨ/debugger-test-chinese-char-in-path-ㄨ.csproj Co-authored-by: Ankit Jain --- .../debugger/BrowserDebugProxy/DebugStore.cs | 3 +- .../DebuggerTestSuite/HotReloadTests.cs | 44 ++++---- .../debugger/DebuggerTestSuite/MiscTests.cs | 26 ++++- ...emblyChineseCharInPath\343\204\250.csproj" | 36 ++++++ .../MethodBody0.cs" | 15 +++ .../MethodBody1.cs" | 60 ++++++++++ .../MethodBody1_v1.cs" | 87 ++++++++++++++ .../MethodBody1_v2.cs" | 106 ++++++++++++++++++ .../deltascript.json" | 7 ++ ...-chinese-char-in-path-\343\204\250.csproj" | 6 + .../test.cs" | 10 ++ .../tests/debugger-test/debugger-test.csproj | 7 ++ ...-chinese-char-in-path-\343\204\250.csproj" | 2 + .../lazy-debugger-test.cs" | 25 +++++ 14 files changed, 407 insertions(+), 27 deletions(-) create mode 100644 "src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250.csproj" create mode 100644 "src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody0.cs" create mode 100644 "src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody1.cs" create mode 100644 "src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody1_v1.cs" create mode 100644 "src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody1_v2.cs" create mode 100644 "src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/deltascript.json" create mode 100644 "src/mono/wasm/debugger/tests/debugger-test-chinese-char-in-path-\343\204\250/debugger-test-chinese-char-in-path-\343\204\250.csproj" create mode 100644 "src/mono/wasm/debugger/tests/debugger-test-chinese-char-in-path-\343\204\250/test.cs" create mode 100644 "src/mono/wasm/debugger/tests/lazy-debugger-test-chinese-char-in-path-\343\204\250/lazy-debugger-test-chinese-char-in-path-\343\204\250.csproj" create mode 100644 "src/mono/wasm/debugger/tests/lazy-debugger-test-chinese-char-in-path-\343\204\250/lazy-debugger-test.cs" diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs b/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs index 15aea3c97466b7..c95bbb8c7a9b13 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs @@ -1467,11 +1467,12 @@ public async IAsyncEnumerable Load(SessionId id, string[] loaded_fil continue; try { + string unescapedFileName = Uri.UnescapeDataString(file_name); steps.Add( new DebugItem { Url = file_name, - Data = context.SdbAgent.GetBytesFromAssemblyAndPdb(Path.GetFileName(file_name), token) + Data = context.SdbAgent.GetBytesFromAssemblyAndPdb(Path.GetFileName(unescapedFileName), token) }); } catch (Exception e) diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/HotReloadTests.cs b/src/mono/wasm/debugger/DebuggerTestSuite/HotReloadTests.cs index 146ecaebac862c..7e5f5fa3cd8102 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/HotReloadTests.cs +++ b/src/mono/wasm/debugger/DebuggerTestSuite/HotReloadTests.cs @@ -51,35 +51,37 @@ public async Task DebugHotReloadMethodUnchanged() CheckNumber(locals, "a", 10); } - [ConditionalFact(nameof(RunningOnChrome))] - public async Task DebugHotReloadMethodAddBreakpoint() + [ConditionalTheory(nameof(RunningOnChrome))] + [InlineData("ApplyUpdateReferencedAssembly")] + [InlineData("ApplyUpdateReferencedAssemblyChineseCharInPathㄨ")] + public async Task DebugHotReloadMethodAddBreakpoint(string assembly_name) { int line = 30; await SetBreakpoint(".*/MethodBody1.cs$", line, 12, use_regex: true); var pause_location = await LoadAssemblyAndTestHotReload( - Path.Combine(DebuggerTestAppPath, "ApplyUpdateReferencedAssembly.dll"), - Path.Combine(DebuggerTestAppPath, "ApplyUpdateReferencedAssembly.pdb"), - Path.Combine(DebuggerTestAppPath, "../wasm/ApplyUpdateReferencedAssembly.dll"), + Path.Combine(DebuggerTestAppPath, $"{assembly_name}.dll"), + Path.Combine(DebuggerTestAppPath, $"{assembly_name}.pdb"), + Path.Combine(DebuggerTestAppPath, $"../wasm/{assembly_name}.dll"), "MethodBody3", "StaticMethod3", expectBpResolvedEvent: true); var locals = await GetProperties(pause_location["callFrames"][0]["callFrameId"].Value()); CheckNumber(locals, "a", 10); - pause_location = await SendCommandAndCheck(JObject.FromObject(new { }), "Debugger.resume", "dotnet://ApplyUpdateReferencedAssembly.dll/MethodBody1.cs", 30, 12, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3"); + pause_location = await SendCommandAndCheck(JObject.FromObject(new { }), "Debugger.resume", $"dotnet://{assembly_name}.dll/MethodBody1.cs", 30, 12, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3"); locals = await GetProperties(pause_location["callFrames"][0]["callFrameId"].Value()); CheckNumber(locals, "b", 15); - pause_location = await SendCommandAndCheck(JObject.FromObject(new { }), "Debugger.resume", "dotnet://ApplyUpdateReferencedAssembly.dll/MethodBody1.cs", 30, 12, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3"); + pause_location = await SendCommandAndCheck(JObject.FromObject(new { }), "Debugger.resume", $"dotnet://{assembly_name}.dll/MethodBody1.cs", 30, 12, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3"); locals = await GetProperties(pause_location["callFrames"][0]["callFrameId"].Value()); await CheckBool(locals, "c", true); - await StepAndCheck(StepKind.Over, "dotnet://ApplyUpdateReferencedAssembly.dll/MethodBody1.cs", 31, 12, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", + await StepAndCheck(StepKind.Over, $"dotnet://{assembly_name}.dll/MethodBody1.cs", 31, 12, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", locals_fn: async (locals) => { CheckNumber(locals, "d", 10); await Task.CompletedTask; } ); - await StepAndCheck(StepKind.Over, "dotnet://ApplyUpdateReferencedAssembly.dll/MethodBody1.cs", 32, 12, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", + await StepAndCheck(StepKind.Over, $"dotnet://{assembly_name}.dll/MethodBody1.cs", 32, 12, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", locals_fn: async (locals) => { CheckNumber(locals, "d", 10); @@ -87,7 +89,7 @@ await StepAndCheck(StepKind.Over, "dotnet://ApplyUpdateReferencedAssembly.dll/Me await Task.CompletedTask; } ); - await StepAndCheck(StepKind.Over, "dotnet://ApplyUpdateReferencedAssembly.dll/MethodBody1.cs", 33, 8, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", + await StepAndCheck(StepKind.Over, $"dotnet://{assembly_name}.dll/MethodBody1.cs", 33, 8, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", locals_fn: async (locals) => { CheckNumber(locals, "d", 10); @@ -217,12 +219,14 @@ public async Task DebugHotReloadMethodUnchangedUsingSDB() CheckLocation("dotnet://ApplyUpdateReferencedAssembly.dll/MethodBody1.cs", 21, 12, scripts, top_frame["location"]); } - [ConditionalFact(nameof(RunningOnChrome))] - public async Task DebugHotReloadMethodAddBreakpointUsingSDB() + [ConditionalTheory(nameof(RunningOnChrome))] + [InlineData("ApplyUpdateReferencedAssembly")] + [InlineData("ApplyUpdateReferencedAssemblyChineseCharInPathㄨ")] + public async Task DebugHotReloadMethodAddBreakpointUsingSDB(string assembly_name) { - string asm_file = Path.Combine(DebuggerTestAppPath, "ApplyUpdateReferencedAssembly.dll"); - string pdb_file = Path.Combine(DebuggerTestAppPath, "ApplyUpdateReferencedAssembly.pdb"); - string asm_file_hot_reload = Path.Combine(DebuggerTestAppPath, "../wasm/ApplyUpdateReferencedAssembly.dll"); + string asm_file = Path.Combine(DebuggerTestAppPath, $"{assembly_name}.dll"); + string pdb_file = Path.Combine(DebuggerTestAppPath, $"{assembly_name}.pdb"); + string asm_file_hot_reload = Path.Combine(DebuggerTestAppPath, $"../wasm/{assembly_name}.dll"); int line = 30; await SetBreakpoint(".*/MethodBody1.cs$", line, 12, use_regex: true); @@ -238,7 +242,7 @@ public async Task DebugHotReloadMethodAddBreakpointUsingSDB() JToken top_frame = pause_location["callFrames"]?[0]; AssertEqual("ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", top_frame?["functionName"]?.Value(), top_frame?.ToString()); - CheckLocation("dotnet://ApplyUpdateReferencedAssembly.dll/MethodBody1.cs", 30, 12, scripts, top_frame["location"]); + CheckLocation($"dotnet://{assembly_name}.dll/MethodBody1.cs", 30, 12, scripts, top_frame["location"]); locals = await GetProperties(pause_location["callFrames"][0]["callFrameId"].Value()); CheckNumber(locals, "b", 15); @@ -249,19 +253,19 @@ public async Task DebugHotReloadMethodAddBreakpointUsingSDB() top_frame = pause_location["callFrames"]?[0]; AssertEqual("ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", top_frame?["functionName"]?.Value(), top_frame?.ToString()); - CheckLocation("dotnet://ApplyUpdateReferencedAssembly.dll/MethodBody1.cs", 30, 12, scripts, top_frame["location"]); + CheckLocation($"dotnet://{assembly_name}.dll/MethodBody1.cs", 30, 12, scripts, top_frame["location"]); locals = await GetProperties(pause_location["callFrames"][0]["callFrameId"].Value()); await CheckBool(locals, "c", true); - await StepAndCheck(StepKind.Over, "dotnet://ApplyUpdateReferencedAssembly.dll/MethodBody1.cs", 31, 12, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", + await StepAndCheck(StepKind.Over, $"dotnet://{assembly_name}.dll/MethodBody1.cs", 31, 12, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", locals_fn: async (locals) => { CheckNumber(locals, "d", 10); await Task.CompletedTask; } ); - await StepAndCheck(StepKind.Over, "dotnet://ApplyUpdateReferencedAssembly.dll/MethodBody1.cs", 32, 12, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", + await StepAndCheck(StepKind.Over, $"dotnet://{assembly_name}.dll/MethodBody1.cs", 32, 12, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", locals_fn: async (locals) => { CheckNumber(locals, "d", 10); @@ -269,7 +273,7 @@ await StepAndCheck(StepKind.Over, "dotnet://ApplyUpdateReferencedAssembly.dll/Me await Task.CompletedTask; } ); - await StepAndCheck(StepKind.Over, "dotnet://ApplyUpdateReferencedAssembly.dll/MethodBody1.cs", 33, 8, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", + await StepAndCheck(StepKind.Over, $"dotnet://{assembly_name}.dll/MethodBody1.cs", 33, 8, "ApplyUpdateReferencedAssembly.MethodBody3.StaticMethod3", locals_fn: async (locals) => { CheckNumber(locals, "d", 10); diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/MiscTests.cs b/src/mono/wasm/debugger/DebuggerTestSuite/MiscTests.cs index 5c7d237df0f406..5e1cfda9a92bac 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/MiscTests.cs +++ b/src/mono/wasm/debugger/DebuggerTestSuite/MiscTests.cs @@ -735,23 +735,25 @@ JObject FindFrame(JObject pause_location, string function_name) ?.Where(f => f["functionName"]?.Value() == function_name) ?.FirstOrDefault(); - [ConditionalFact(nameof(RunningOnChrome))] - public async Task DebugLazyLoadedAssemblyWithPdb() + [ConditionalTheory(nameof(RunningOnChrome))] + [InlineData("lazy-debugger-test")] + [InlineData("lazy-debugger-test-chinese-char-in-path-ㄨ")] + public async Task DebugLazyLoadedAssemblyWithPdb(string assembly_name) { Task bpResolved = WaitForBreakpointResolvedEvent(); int line = 9; await SetBreakpoint(".*/lazy-debugger-test.cs$", line, 0, use_regex: true); await LoadAssemblyDynamically( - Path.Combine(DebuggerTestAppPath, "lazy-debugger-test.dll"), - Path.Combine(DebuggerTestAppPath, "lazy-debugger-test.pdb")); + Path.Combine(DebuggerTestAppPath, $"{assembly_name}.dll"), + Path.Combine(DebuggerTestAppPath, $"{assembly_name}.pdb")); - var source_location = "dotnet://lazy-debugger-test.dll/lazy-debugger-test.cs"; + var source_location = $"dotnet://{assembly_name}.dll/lazy-debugger-test.cs"; Assert.Contains(source_location, scripts.Values); await bpResolved; var pause_location = await EvaluateAndCheck( - "window.setTimeout(function () { invoke_static_method('[lazy-debugger-test] LazyMath:IntAdd', 5, 10); }, 1);", + "window.setTimeout(function () { invoke_static_method('[" + assembly_name + "] LazyMath:IntAdd', 5, 10); }, 1);", source_location, line, 8, "LazyMath.IntAdd"); var locals = await GetProperties(pause_location["callFrames"][0]["callFrameId"].Value()); @@ -1086,5 +1088,17 @@ await EvaluateAndCheck( } ); } + + [ConditionalFact(nameof(RunningOnChrome))] + public async Task SetBreakpointInProjectWithChineseCharactereInPath() + { + var bp = await SetBreakpointInMethod("debugger-test-chinese-char-in-path-ㄨ.dll", "DebuggerTests.CheckChineseCharacterInPath", "Evaluate", 1); + await EvaluateAndCheck( + $"window.setTimeout(function() {{ invoke_static_method ('[debugger-test-chinese-char-in-path-ㄨ] DebuggerTests.CheckChineseCharacterInPath:Evaluate'); }}, 1);", + "dotnet://debugger-test-chinese-char-in-path-ㄨ.dll/test.cs", + bp.Value["locations"][0]["lineNumber"].Value(), + bp.Value["locations"][0]["columnNumber"].Value(), + $"DebuggerTests.CheckChineseCharacterInPath.Evaluate"); + } } } diff --git "a/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250.csproj" "b/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250.csproj" new file mode 100644 index 00000000000000..9b4c7a12d15077 --- /dev/null +++ "b/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250.csproj" @@ -0,0 +1,36 @@ + + + true + deltascript.json + library + false + true + + false + true + + false + false + false + true + + + true + + + + + + + + + + + + diff --git "a/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody0.cs" "b/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody0.cs" new file mode 100644 index 00000000000000..833ac95a642f02 --- /dev/null +++ "b/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody0.cs" @@ -0,0 +1,15 @@ +// 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; + +namespace ApplyUpdateReferencedAssembly +{ + public class MethodBodyUnchangedAssembly { + public static string StaticMethod1 () { + Console.WriteLine("original"); + return "ok"; + } + } +} diff --git "a/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody1.cs" "b/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody1.cs" new file mode 100644 index 00000000000000..3abc1d4b538bb7 --- /dev/null +++ "b/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody1.cs" @@ -0,0 +1,60 @@ +// 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; +//keep the same line number for class in the original file and the updates ones +namespace ApplyUpdateReferencedAssembly +{ + public class MethodBody1 { + public static string StaticMethod1 () { + Console.WriteLine("original"); + int a = 10; + Debugger.Break(); + return "OLD STRING"; + } + } + + public class MethodBody2 { + public static string StaticMethod1 () { + Console.WriteLine("original"); + int a = 10; + Debugger.Break(); + return "OLD STRING"; + } + } + + public class MethodBody3 { + public static string StaticMethod3 () { + int a = 10; + Console.WriteLine("original"); + return "OLD STRING"; + } + } + + + + public class MethodBody4 { + public static void StaticMethod4 () { + } + } + + + + + + + public class MethodBody5 { + public static void StaticMethod1 () { + Console.WriteLine("breakpoint in a line that will not be changed"); + Console.WriteLine("original"); + } + } + + public class MethodBody6 { + public static void StaticMethod1 () { + Console.WriteLine("breakpoint in a line that will not be changed"); + Console.WriteLine("original"); + } + } +} diff --git "a/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody1_v1.cs" "b/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody1_v1.cs" new file mode 100644 index 00000000000000..cef3214d9c89e9 --- /dev/null +++ "b/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody1_v1.cs" @@ -0,0 +1,87 @@ +// 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; +//keep the same line number for class in the original file and the updates ones +namespace ApplyUpdateReferencedAssembly +{ + public class MethodBody1 { + public static string StaticMethod1 () { + Console.WriteLine("v1"); + double b = 15; + Debugger.Break(); + return "NEW STRING"; + } + } + + public class MethodBody2 { + public static string StaticMethod1 () { + Console.WriteLine("original"); + int a = 10; + Debugger.Break(); + return "OLD STRING"; + } + } + + public class MethodBody3 { + public static string StaticMethod3 () { + float b = 15; + Console.WriteLine("v1"); + return "NEW STRING"; + } + } + + + + public class MethodBody4 { + public static void StaticMethod4 () { + int a = 10; + int b = 20; + Console.WriteLine(a + b); + Console.WriteLine(a + b); + Console.WriteLine(a + b); + } + } + + public class MethodBody5 { + public static void StaticMethod1 () { + Console.WriteLine("breakpoint in a line that will not be changed"); + Console.WriteLine("beforeoriginal"); + Console.WriteLine("original"); + } + } + public class MethodBody6 { + public static void StaticMethod1 () { + Console.WriteLine("breakpoint in a line that will not be changed"); + Console.WriteLine("original"); + } + public static void NewMethodStatic () { + int i = 20; + newStaticField = 10; + Console.WriteLine($"add a breakpoint in the new static method, look at locals {newStaticField}"); + /*var newvar = new MethodBody6(); + newvar.NewMethodInstance (10);*/ + } + public static int newStaticField; + } + + public class MethodBody7 { + public static int staticField; + int attr1; + string attr2; + public static void StaticMethod1 () { + Console.WriteLine("breakpoint in a method in a new class"); + Console.WriteLine("original"); + MethodBody7 newvar = new MethodBody7(); + staticField = 80; + newvar.InstanceMethod(); + } + public void InstanceMethod () { + int aLocal = 50; + attr1 = 15; + attr2 = "20"; + Console.WriteLine($"add a breakpoint the instance method of the new class"); + } + } +} diff --git "a/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody1_v2.cs" "b/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody1_v2.cs" new file mode 100644 index 00000000000000..48c3b9911e8059 --- /dev/null +++ "b/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/MethodBody1_v2.cs" @@ -0,0 +1,106 @@ +// 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; +//keep the same line number for class in the original file and the updates ones +namespace ApplyUpdateReferencedAssembly +{ + public class MethodBody1 { + public static string StaticMethod1 () + { + Console.WriteLine("v2"); + bool c = true; + Debugger.Break(); + return "NEWEST STRING"; + } + } + + public class MethodBody2 { + public static string StaticMethod1 () { + Console.WriteLine("original"); + int a = 10; + Debugger.Break(); + return "OLD STRING"; + } + } + + public class MethodBody3 { + public static string StaticMethod3 () { + bool c = true; + int d = 10; + int e = 20; + int f = 50; + return "NEWEST STRING"; + } + } + + public class MethodBody4 { + public static void StaticMethod4 () { + } + } + + + + + + + public class MethodBody5 { + public static void StaticMethod1 () { + Console.WriteLine("beforeoriginal"); + Console.WriteLine("original"); + } + } + + public class MethodBody6 { + public static void StaticMethod1 () { + Console.WriteLine("breakpoint in a line that will not be changed"); + Console.WriteLine("original"); + } + public static void NewMethodStatic () { + int i = 20; + newStaticField = 10; + Console.WriteLine($"add a breakpoint in the new static method, look at locals {newStaticField}"); + /*var newvar = new MethodBody6(); + newvar.NewMethodInstance (10);*/ + } + public static int newStaticField; + } + + public class MethodBody7 { + public static int staticField; + int attr1; + string attr2; + public static void StaticMethod1 () { + Console.WriteLine("breakpoint in a method in a new class"); + Console.WriteLine("original"); + MethodBody7 newvar = new MethodBody7(); + staticField = 80; + newvar.InstanceMethod(); + } + public void InstanceMethod () { + int aLocal = 50; + attr1 = 15; + attr2 = "20"; + Console.WriteLine($"add a breakpoint the instance method of the new class"); + } + } + + public class MethodBody8 { + public static int staticField; + int attr1; + string attr2; + public static void StaticMethod1 () { + Console.WriteLine("breakpoint in a method in a new class"); + Console.WriteLine("original"); + MethodBody8 newvar = new MethodBody8(); + staticField = 80; + newvar.InstanceMethod(); + } + public void InstanceMethod () { + int aLocal = 50; + attr1 = 15; + attr2 = "20"; + Console.WriteLine($"add a breakpoint the instance method of the new class"); + } + } +} diff --git "a/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/deltascript.json" "b/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/deltascript.json" new file mode 100644 index 00000000000000..8e738364bc7475 --- /dev/null +++ "b/src/mono/wasm/debugger/tests/ApplyUpdateReferencedAssemblyChineseCharInPath\343\204\250/deltascript.json" @@ -0,0 +1,7 @@ +{ + "changes": [ + {"document": "MethodBody1.cs", "update": "MethodBody1_v1.cs"}, + {"document": "MethodBody1.cs", "update": "MethodBody1_v2.cs"}, + ] +} + diff --git "a/src/mono/wasm/debugger/tests/debugger-test-chinese-char-in-path-\343\204\250/debugger-test-chinese-char-in-path-\343\204\250.csproj" "b/src/mono/wasm/debugger/tests/debugger-test-chinese-char-in-path-\343\204\250/debugger-test-chinese-char-in-path-\343\204\250.csproj" new file mode 100644 index 00000000000000..1463b4a398f1f7 --- /dev/null +++ "b/src/mono/wasm/debugger/tests/debugger-test-chinese-char-in-path-\343\204\250/debugger-test-chinese-char-in-path-\343\204\250.csproj" @@ -0,0 +1,6 @@ + + + + false + + diff --git "a/src/mono/wasm/debugger/tests/debugger-test-chinese-char-in-path-\343\204\250/test.cs" "b/src/mono/wasm/debugger/tests/debugger-test-chinese-char-in-path-\343\204\250/test.cs" new file mode 100644 index 00000000000000..6902b401317936 --- /dev/null +++ "b/src/mono/wasm/debugger/tests/debugger-test-chinese-char-in-path-\343\204\250/test.cs" @@ -0,0 +1,10 @@ +namespace DebuggerTests +{ + public class CheckChineseCharacterInPath + { + public static void Evaluate() + { + var a = 123; + } + } +} diff --git a/src/mono/wasm/debugger/tests/debugger-test/debugger-test.csproj b/src/mono/wasm/debugger/tests/debugger-test/debugger-test.csproj index 0e457832913513..c6977c5f2d0407 100644 --- a/src/mono/wasm/debugger/tests/debugger-test/debugger-test.csproj +++ b/src/mono/wasm/debugger/tests/debugger-test/debugger-test.csproj @@ -20,7 +20,9 @@ + + @@ -29,6 +31,7 @@ <_AssemblyForDynamicLoading Include="lazy-debugger-test" /> + <_AssemblyForDynamicLoading Include="lazy-debugger-test-chinese-char-in-path-ㄨ" /> <_AssemblyForDynamicLoading Include="debugger-test-with-full-debug-type" /> <_AssemblyForDynamicLoading Include="debugger-test-with-pdb-deleted" /> <_AssemblyForDynamicLoading Include="debugger-test-without-debug-symbols" /> @@ -53,6 +56,7 @@ + @@ -78,6 +82,9 @@ + + diff --git "a/src/mono/wasm/debugger/tests/lazy-debugger-test-chinese-char-in-path-\343\204\250/lazy-debugger-test.cs" "b/src/mono/wasm/debugger/tests/lazy-debugger-test-chinese-char-in-path-\343\204\250/lazy-debugger-test.cs" new file mode 100644 index 00000000000000..2da3c708e85acb --- /dev/null +++ "b/src/mono/wasm/debugger/tests/lazy-debugger-test-chinese-char-in-path-\343\204\250/lazy-debugger-test.cs" @@ -0,0 +1,25 @@ +// 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 partial class LazyMath +{ + public static int IntAdd(int a, int b) + { + int c = a + b; + return c; + } +} + +namespace DebuggerTests +{ + public class ClassToCheckFieldValue + { + public int valueToCheck; + public ClassToCheckFieldValue() + { + valueToCheck = 20; + } + } +} From f7870ad3213ce279b54752a3b563a81182558b97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Mon, 29 Aug 2022 22:55:23 +0900 Subject: [PATCH 008/107] Mark UnmanagedCallersOnlyTest as NativeAOT incompatible (#74546) * Mark UnmanagedCallersOnlyTest as NativeAOT incompatible * Also remove from issues.targets --- .../UnmanagedCallersOnly/UnmanagedCallersOnlyTest.csproj | 1 + src/tests/issues.targets | 3 --- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/tests/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest.csproj b/src/tests/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest.csproj index 5a5439c4127a50..f9ae90e24b7910 100644 --- a/src/tests/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest.csproj +++ b/src/tests/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest.csproj @@ -3,6 +3,7 @@ Exe true true + true diff --git a/src/tests/issues.targets b/src/tests/issues.targets index 9304527ad6afcd..4a97ccfeb9786d 100644 --- a/src/tests/issues.targets +++ b/src/tests/issues.targets @@ -1096,9 +1096,6 @@ https://github.com/dotnet/runtimelab/issues/181 - - https://github.com/dotnet/runtimelab/issues/154 - https://github.com/dotnet/runtimelab/issues/182 From 3cad3d2463df6cac2376cab7710a0f1f8974ddac Mon Sep 17 00:00:00 2001 From: Tlakaelel Axayakatl Ceja Date: Mon, 29 Aug 2022 08:21:30 -0700 Subject: [PATCH 009/107] Annotate System.Runtime.Serialization for AOT warnings (#74663) Annotate System.Runtime.Serialization for AOT warnings Modify current RUC warnings where they use the word `Type` starting with uppercase to just `type` to be consistent with the rest of the framework --- .../ref/System.Data.Common.cs | 3 ++ .../src/System/Data/DataSet.cs | 7 ++++ ...System.Runtime.Serialization.Formatters.cs | 29 +++++++------ ...em.Runtime.Serialization.Formatters.csproj | 1 + .../System/Runtime/Serialization/Formatter.cs | 1 + .../Formatters/Binary/BinaryFormatter.Core.cs | 1 + .../BinaryFormatter.PlatformNotSupported.cs | 1 + .../Formatters/Binary/BinaryObjectReader.cs | 9 ++++ .../Formatters/Binary/BinaryParser.cs | 14 +++++++ .../Runtime/Serialization/IFormatter.cs | 4 +- .../Runtime/Serialization/ObjectManager.cs | 2 +- .../SerializationObjectManager.cs | 2 +- ...iCompatBaseline.NetCoreAppLatestStable.txt | 42 ++++++++++++++++++- 13 files changed, 99 insertions(+), 17 deletions(-) diff --git a/src/libraries/System.Data.Common/ref/System.Data.Common.cs b/src/libraries/System.Data.Common/ref/System.Data.Common.cs index e46b17a11d3029..b15070d6e173b2 100644 --- a/src/libraries/System.Data.Common/ref/System.Data.Common.cs +++ b/src/libraries/System.Data.Common/ref/System.Data.Common.cs @@ -492,8 +492,10 @@ public void EndEdit() { } public partial class DataSet : System.ComponentModel.MarshalByValueComponent, System.ComponentModel.IListSource, System.ComponentModel.ISupportInitialize, System.ComponentModel.ISupportInitializeNotification, System.Runtime.Serialization.ISerializable, System.Xml.Serialization.IXmlSerializable { public DataSet() { } + [System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute("Members from serialized types may use dynamic code generation.")] [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Members from serialized types may be trimmed if not referenced directly.")] protected DataSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } + [System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute("Members from serialized types may use dynamic code generation.")] [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Members from serialized types may be trimmed if not referenced directly.")] protected DataSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context, bool ConstructSchema) { } public DataSet(string dataSetName) { } @@ -548,6 +550,7 @@ public void EndInit() { } public static System.Xml.Schema.XmlSchemaComplexType GetDataSetSchema(System.Xml.Schema.XmlSchemaSet? schemaSet) { throw null; } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } protected virtual System.Xml.Schema.XmlSchema? GetSchemaSerializable() { throw null; } + [System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute("Members from serialized types may use dynamic code generation.")] [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Members from serialized types may be trimmed if not referenced directly.")] protected void GetSerializationData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("Members from serialized types may be trimmed if not referenced directly.")] diff --git a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs index d65d72bc111cd1..f08e12b978d154 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs @@ -33,6 +33,7 @@ namespace System.Data [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.NonPublicConstructors)] // needed by Clone() to preserve derived ctors public class DataSet : MarshalByValueComponent, IListSource, IXmlSerializable, ISupportInitializeNotification, ISerializable { + internal const string RequiresDynamicCodeMessage = "Members from serialized types may use dynamic code generation."; internal const string RequiresUnreferencedCodeMessage = "Members from serialized types may be trimmed if not referenced directly."; private const string KEY_XMLSCHEMA = "XmlSchema"; private const string KEY_XMLDIFFGRAM = "XmlDiffGram"; @@ -217,6 +218,7 @@ protected SchemaSerializationMode DetermineSchemaSerializationMode(XmlReader rea // Deserialize all the tables data of the dataset from binary/xml stream. // 'instance' method that consumes SerializationInfo + [RequiresDynamicCode(RequiresDynamicCodeMessage)] [RequiresUnreferencedCode(RequiresUnreferencedCodeMessage)] protected void GetSerializationData(SerializationInfo info, StreamingContext context) { @@ -238,6 +240,7 @@ protected void GetSerializationData(SerializationInfo info, StreamingContext con // Deserialize all the tables schema and data of the dataset from binary/xml stream. + [RequiresDynamicCode(RequiresDynamicCodeMessage)] [RequiresUnreferencedCode(RequiresUnreferencedCodeMessage)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "CreateInstanceOfThisType's use of GetType uses only the parameterless constructor, but the annotations preserve all non-public constructors causing a warning for the serialization constructors. Those constructors won't be used here.")] @@ -245,6 +248,7 @@ protected DataSet(SerializationInfo info, StreamingContext context) : this(info, { } + [RequiresDynamicCode(RequiresDynamicCodeMessage)] [RequiresUnreferencedCode(RequiresUnreferencedCodeMessage)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2112:ReflectionToRequiresUnreferencedCode", Justification = "CreateInstanceOfThisType's use of GetType uses only the parameterless constructor, but the annotations preserve all non-public constructors causing a warning for the serialization constructors. Those constructors won't be used here.")] @@ -386,6 +390,7 @@ private void SerializeDataSet(SerializationInfo info, StreamingContext context, } // Deserialize all the tables - marked internal so that DataTable can call into this + [RequiresDynamicCode(RequiresDynamicCodeMessage)] [RequiresUnreferencedCode(RequiresUnreferencedCodeMessage)] internal void DeserializeDataSet(SerializationInfo info, StreamingContext context, SerializationFormat remotingFormat, SchemaSerializationMode schemaSerializationMode) { @@ -396,6 +401,7 @@ internal void DeserializeDataSet(SerializationInfo info, StreamingContext contex } // Deserialize schema. + [RequiresDynamicCode(RequiresDynamicCodeMessage)] [RequiresUnreferencedCode(RequiresUnreferencedCodeMessage)] private void DeserializeDataSetSchema(SerializationInfo info, StreamingContext context, SerializationFormat remotingFormat, SchemaSerializationMode schemaSerializationMode) { @@ -455,6 +461,7 @@ private void DeserializeDataSetSchema(SerializationInfo info, StreamingContext c } // Deserialize all data. + [RequiresDynamicCode(RequiresDynamicCodeMessage)] [RequiresUnreferencedCode(RequiresUnreferencedCodeMessage)] private void DeserializeDataSetData(SerializationInfo info, StreamingContext context, SerializationFormat remotingFormat) { diff --git a/src/libraries/System.Runtime.Serialization.Formatters/ref/System.Runtime.Serialization.Formatters.cs b/src/libraries/System.Runtime.Serialization.Formatters/ref/System.Runtime.Serialization.Formatters.cs index ecfda2d0efd1f3..d1ebf7e6bd2257 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/ref/System.Runtime.Serialization.Formatters.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/ref/System.Runtime.Serialization.Formatters.cs @@ -16,12 +16,13 @@ protected Formatter() { } public abstract System.Runtime.Serialization.StreamingContext Context { get; set; } public abstract System.Runtime.Serialization.ISurrogateSelector? SurrogateSelector { get; set; } [System.ObsoleteAttribute("BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.", DiagnosticId = "SYSLIB0011", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute("BinaryFormatter serialization uses dynamic code generation, the type of objects being processed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")] public abstract object Deserialize(System.IO.Stream serializationStream); protected virtual object? GetNext(out long objID) { throw null; } protected virtual long Schedule(object? obj) { throw null; } [System.ObsoleteAttribute("BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.", DiagnosticId = "SYSLIB0011", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")] public abstract void Serialize(System.IO.Stream serializationStream, object graph); protected abstract void WriteArray(object obj, string name, System.Type memberType); protected abstract void WriteBoolean(bool val, string name); @@ -91,10 +92,11 @@ public partial interface IFormatter System.Runtime.Serialization.StreamingContext Context { get; set; } System.Runtime.Serialization.ISurrogateSelector? SurrogateSelector { get; set; } [System.ObsoleteAttribute("BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.", DiagnosticId = "SYSLIB0011", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute("BinaryFormatter serialization uses dynamic code generation, the type of objects being processed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")] object Deserialize(System.IO.Stream serializationStream); [System.ObsoleteAttribute("BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.", DiagnosticId = "SYSLIB0011", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")] void Serialize(System.IO.Stream serializationStream, object graph); } public partial interface ISerializationSurrogate @@ -117,23 +119,23 @@ public ObjectIDGenerator() { } public partial class ObjectManager { public ObjectManager(System.Runtime.Serialization.ISurrogateSelector? selector, System.Runtime.Serialization.StreamingContext context) { } - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")] public virtual void DoFixups() { } public virtual object? GetObject(long objectID) { throw null; } public virtual void RaiseDeserializationEvent() { } - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")] public void RaiseOnDeserializingEvent(object obj) { } public virtual void RecordArrayElementFixup(long arrayToBeFixed, int index, long objectRequired) { } public virtual void RecordArrayElementFixup(long arrayToBeFixed, int[] indices, long objectRequired) { } public virtual void RecordDelayedFixup(long objectToBeFixed, string memberName, long objectRequired) { } public virtual void RecordFixup(long objectToBeFixed, System.Reflection.MemberInfo member, long objectRequired) { } - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")] public virtual void RegisterObject(object obj, long objectID) { } - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")] public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo info) { } - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")] public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo? info, long idOfContainingObj, System.Reflection.MemberInfo? member) { } - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")] public void RegisterObject(object obj, long objectID, System.Runtime.Serialization.SerializationInfo? info, long idOfContainingObj, System.Reflection.MemberInfo? member, int[]? arrayIndex) { } } public abstract partial class SerializationBinder @@ -146,7 +148,7 @@ public sealed partial class SerializationObjectManager { public SerializationObjectManager(System.Runtime.Serialization.StreamingContext context) { } public void RaiseOnSerializedEvent() { } - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("SerializationObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("SerializationObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")] public void RegisterObject(object obj) { } } public partial class SurrogateSelector : System.Runtime.Serialization.ISurrogateSelector @@ -196,10 +198,11 @@ public BinaryFormatter(System.Runtime.Serialization.ISurrogateSelector? selector public System.Runtime.Serialization.ISurrogateSelector? SurrogateSelector { get { throw null; } set { } } public System.Runtime.Serialization.Formatters.FormatterTypeStyle TypeFormat { get { throw null; } set { } } [System.ObsoleteAttribute("BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.", DiagnosticId = "SYSLIB0011", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute("BinaryFormatter serialization uses dynamic code generation, the type of objects being processed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")] public object Deserialize(System.IO.Stream serializationStream) { throw null; } [System.ObsoleteAttribute("BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.", DiagnosticId = "SYSLIB0011", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] - [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")] + [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")] public void Serialize(System.IO.Stream serializationStream, object graph) { } } } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System.Runtime.Serialization.Formatters.csproj b/src/libraries/System.Runtime.Serialization.Formatters/src/System.Runtime.Serialization.Formatters.csproj index 2f03c80aec6adb..a9438b21825df1 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System.Runtime.Serialization.Formatters.csproj +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System.Runtime.Serialization.Formatters.csproj @@ -3,6 +3,7 @@ $(NetCoreAppCurrent);$(NetCoreAppCurrent)-Browser;$(NetCoreAppCurrent)-iOS;$(NetCoreAppCurrent)-tvOS;$(NetCoreAppCurrent)-Android $(MSBuildThisFileDirectory)ILLink\ + true diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatter.cs index 8748e6901547de..7d14ebcb67647a 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatter.cs @@ -21,6 +21,7 @@ protected Formatter() } [Obsolete(Obsoletions.BinaryFormatterMessage, DiagnosticId = Obsoletions.BinaryFormatterDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] + [RequiresDynamicCode(IFormatter.RequiresDynamicCodeMessage)] [RequiresUnreferencedCode(IFormatter.RequiresUnreferencedCodeMessage)] public abstract object Deserialize(Stream serializationStream); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.Core.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.Core.cs index 5021aaa157c942..d495d26ed49d18 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.Core.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.Core.cs @@ -9,6 +9,7 @@ namespace System.Runtime.Serialization.Formatters.Binary public sealed partial class BinaryFormatter : IFormatter { [Obsolete(Obsoletions.BinaryFormatterMessage, DiagnosticId = Obsoletions.BinaryFormatterDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] + [RequiresDynamicCode(IFormatter.RequiresDynamicCodeMessage)] [RequiresUnreferencedCode(IFormatter.RequiresUnreferencedCodeMessage)] public object Deserialize(Stream serializationStream) { diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.PlatformNotSupported.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.PlatformNotSupported.cs index 1e194973e2629b..b212e94ea577a2 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.PlatformNotSupported.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.PlatformNotSupported.cs @@ -9,6 +9,7 @@ namespace System.Runtime.Serialization.Formatters.Binary public sealed partial class BinaryFormatter : IFormatter { [Obsolete(Obsoletions.BinaryFormatterMessage, DiagnosticId = Obsoletions.BinaryFormatterDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] + [RequiresDynamicCode(IFormatter.RequiresDynamicCodeMessage)] [RequiresUnreferencedCode(IFormatter.RequiresUnreferencedCodeMessage)] public object Deserialize(Stream serializationStream) => throw new PlatformNotSupportedException(SR.BinaryFormatter_SerializationNotSupportedOnThisPlatform); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs index 4411b3b42d2557..1ebff5de27d1db 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs @@ -12,6 +12,7 @@ namespace System.Runtime.Serialization.Formatters.Binary internal sealed class ObjectReader { private const string ObjectReaderUnreferencedCodeMessage = "ObjectReader requires unreferenced code"; + private const string ObjectReaderDynamicCodeMessage = "ObjectReader requires dynamic code"; // System.Serializer information internal Stream _stream; @@ -74,6 +75,7 @@ internal ObjectReader(Stream stream, ISurrogateSelector? selector, StreamingCont _formatterEnums = formatterEnums; } + [RequiresDynamicCode(ObjectReaderUnreferencedCodeMessage)] [RequiresUnreferencedCode("Types might be removed")] internal object Deserialize(BinaryParser serParser) { @@ -170,6 +172,7 @@ internal ReadObjectInfo CreateReadObjectInfo( return ReadObjectInfo.Create(objectType, memberNames, memberTypes, _surrogates, _context, _objectManager, _serObjectInfoInit, _formatterConverter, _isSimpleAssembly); } + [RequiresDynamicCode(ObjectReaderDynamicCodeMessage)] [RequiresUnreferencedCode(ObjectReaderUnreferencedCodeMessage)] internal void Parse(ParseRecord pr) { @@ -217,6 +220,7 @@ private void ParseError(ParseRecord processing, ParseRecord onStack) private void ParseSerializedStreamHeaderEnd(ParseRecord pr) => _stack!.Pop(); // New object encountered in stream + [RequiresDynamicCode(ObjectReaderDynamicCodeMessage)] [RequiresUnreferencedCode(ObjectReaderUnreferencedCodeMessage)] private void ParseObject(ParseRecord pr) { @@ -357,6 +361,7 @@ private void ParseObjectEnd(ParseRecord pr) } // Array object encountered in stream + [RequiresDynamicCode(ObjectReaderDynamicCodeMessage)] [RequiresUnreferencedCode(ObjectReaderUnreferencedCodeMessage)] private void ParseArray(ParseRecord pr) { @@ -523,6 +528,7 @@ private void NextRectangleMap(ParseRecord pr) // Array object item encountered in stream + [RequiresDynamicCode(ObjectReaderDynamicCodeMessage)] [RequiresUnreferencedCode(ObjectReaderUnreferencedCodeMessage)] private void ParseArrayMember(ParseRecord pr) { @@ -697,6 +703,7 @@ private void ParseArrayMember(ParseRecord pr) objectPr._memberIndex++; } + [RequiresDynamicCode(ObjectReaderDynamicCodeMessage)] [RequiresUnreferencedCode(ObjectReaderUnreferencedCodeMessage)] private void ParseArrayMemberEnd(ParseRecord pr) { @@ -708,6 +715,7 @@ private void ParseArrayMemberEnd(ParseRecord pr) } // Object member encountered in stream + [RequiresDynamicCode(ObjectReaderDynamicCodeMessage)] [RequiresUnreferencedCode(ObjectReaderUnreferencedCodeMessage)] private void ParseMember(ParseRecord pr) { @@ -821,6 +829,7 @@ private void ParseMember(ParseRecord pr) } // Object member end encountered in stream + [RequiresDynamicCode(ObjectReaderDynamicCodeMessage)] [RequiresUnreferencedCode(ObjectReaderUnreferencedCodeMessage)] private void ParseMemberEnd(ParseRecord pr) { diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs index b648c85b0ac4a5..1f9f869a6e0533 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs @@ -13,6 +13,7 @@ namespace System.Runtime.Serialization.Formatters.Binary internal sealed class BinaryParser { private const string BinaryParserUnreferencedCodeMessage = "ObjectReader requires unreferenced code"; + private const string BinaryParserDynamicCodeMessage = "ObjectReader requires dynamic code"; private const int ChunkSize = 4096; private static readonly Encoding s_encoding = new UTF8Encoding(false, true); @@ -69,6 +70,7 @@ internal BinaryParser(Stream stream, ObjectReader objectReader) // Reads each record from the input stream. If the record is a primitive type (A number) // then it doesn't have a BinaryHeaderEnum byte. For this case the expected type // has been previously set to Primitive + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] internal void Run() { @@ -307,6 +309,7 @@ internal void ReadAssembly(BinaryHeaderEnum binaryHeaderEnum) AssemIdToAssemblyTable[record._assemId] = new BinaryAssemblyInfo(record._assemblyString!); } + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadObject() { @@ -375,6 +378,7 @@ private void ReadObject() _objectReader.Parse(pr); } + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] internal void ReadCrossAppDomainMap() { @@ -398,6 +402,7 @@ internal void ReadCrossAppDomainMap() } } + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] internal void ReadObjectWithMap(BinaryHeaderEnum binaryHeaderEnum) { @@ -413,6 +418,7 @@ internal void ReadObjectWithMap(BinaryHeaderEnum binaryHeaderEnum) ReadObjectWithMap(_bowm); } + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode("Types might be removed")] private void ReadObjectWithMap(BinaryObjectWithMap record) { @@ -500,6 +506,7 @@ private void ReadObjectWithMap(BinaryObjectWithMap record) _objectReader.Parse(pr); } + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode("Types might be removed")] internal void ReadObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum) { @@ -515,6 +522,7 @@ internal void ReadObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum) ReadObjectWithMapTyped(_bowmt); } + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode("Types might be removed")] private void ReadObjectWithMapTyped(BinaryObjectWithMapTyped record) { @@ -596,6 +604,7 @@ private void ReadObjectWithMapTyped(BinaryObjectWithMapTyped record) _objectReader.Parse(pr); } + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadObjectString(BinaryHeaderEnum binaryHeaderEnum) { @@ -667,6 +676,7 @@ private void ReadObjectString(BinaryHeaderEnum binaryHeaderEnum) _objectReader.Parse(PRs); } + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadMemberPrimitiveTyped() { @@ -712,6 +722,7 @@ private void ReadMemberPrimitiveTyped() _objectReader.Parse(PRs); } + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadArray(BinaryHeaderEnum binaryHeaderEnum) { @@ -895,6 +906,7 @@ private void ReadArrayAsBytes(ParseRecord pr) } } + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadMemberPrimitiveUnTyped() { @@ -925,6 +937,7 @@ private void ReadMemberPrimitiveUnTyped() _objectReader.Parse(PRs); } + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadMemberReference() { @@ -953,6 +966,7 @@ private void ReadMemberReference() _objectReader.Parse(PRs); } + [RequiresDynamicCode(BinaryParserDynamicCodeMessage)] [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadObjectNull(BinaryHeaderEnum binaryHeaderEnum) { diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/IFormatter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/IFormatter.cs index c1640a573bfbba..0928b3982c26b8 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/IFormatter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/IFormatter.cs @@ -8,9 +8,11 @@ namespace System.Runtime.Serialization { public interface IFormatter { - internal const string RequiresUnreferencedCodeMessage = "BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered."; + internal const string RequiresDynamicCodeMessage = "BinaryFormatter serialization uses dynamic code generation, the type of objects being processed cannot be statically discovered."; + internal const string RequiresUnreferencedCodeMessage = "BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered."; [Obsolete(Obsoletions.BinaryFormatterMessage, DiagnosticId = Obsoletions.BinaryFormatterDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] + [RequiresDynamicCode(RequiresDynamicCodeMessage)] [RequiresUnreferencedCode(RequiresUnreferencedCodeMessage)] object Deserialize(Stream serializationStream); [Obsolete(Obsoletions.BinaryFormatterMessage, DiagnosticId = Obsoletions.BinaryFormatterDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs index 523daff89fc77b..53d1ab836b567c 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs @@ -14,7 +14,7 @@ public class ObjectManager private const int ArrayMask = MaxArraySize - 1; private const int MaxReferenceDepth = 100; - private const string ObjectManagerUnreferencedCodeMessage = "ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered."; + private const string ObjectManagerUnreferencedCodeMessage = "ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered."; private static readonly FieldInfo s_nullableValueField = typeof(Nullable<>).GetField("value", BindingFlags.NonPublic | BindingFlags.Instance)!; diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationObjectManager.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationObjectManager.cs index 69ae9935da416e..9c0b1299f093fd 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationObjectManager.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/SerializationObjectManager.cs @@ -8,7 +8,7 @@ namespace System.Runtime.Serialization { public sealed class SerializationObjectManager { - private const string SerializationObjectManagerUnreferencedCodeMessage = "SerializationObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered."; + private const string SerializationObjectManagerUnreferencedCodeMessage = "SerializationObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered."; private readonly Dictionary _objectSeenTable; // Table to keep track of objects [OnSerializing] has been called on private readonly StreamingContext _context; diff --git a/src/libraries/apicompat/ApiCompatBaseline.NetCoreAppLatestStable.txt b/src/libraries/apicompat/ApiCompatBaseline.NetCoreAppLatestStable.txt index 1361a3c323a21c..b01dfa19767715 100644 --- a/src/libraries/apicompat/ApiCompatBaseline.NetCoreAppLatestStable.txt +++ b/src/libraries/apicompat/ApiCompatBaseline.NetCoreAppLatestStable.txt @@ -2,6 +2,19 @@ Compat issues with assembly mscorlib: CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.IO.FileStream.Lock(System.Int64, System.Int64)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("freebsd")]' in the implementation. CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.IO.FileStream.Unlock(System.Int64, System.Int64)' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("freebsd")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.RequiresPreviewFeaturesAttribute' exists on 'System.String System.Runtime.CompilerServices.RuntimeFeature.VirtualStaticsInInterfaces' in the contract but not the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.Formatter.Deserialize(System.IO.Stream)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.Formatter.Serialize(System.IO.Stream, System.Object)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.IFormatter.Deserialize(System.IO.Stream)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.IFormatter.Serialize(System.IO.Stream, System.Object)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.DoFixups()' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RaiseOnDeserializingEvent(System.Object)' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RegisterObject(System.Object, System.Int64)' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RegisterObject(System.Object, System.Int64, System.Runtime.Serialization.SerializationInfo)' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RegisterObject(System.Object, System.Int64, System.Runtime.Serialization.SerializationInfo, System.Int64, System.Reflection.MemberInfo)' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RegisterObject(System.Object, System.Int64, System.Runtime.Serialization.SerializationInfo, System.Int64, System.Reflection.MemberInfo, System.Int32[])' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.SerializationObjectManager.RegisterObject(System.Object)' changed from '[RequiresUnreferencedCodeAttribute("SerializationObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("SerializationObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(System.IO.Stream)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(System.IO.Stream, System.Object)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Aes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeFormatter' in the contract but not the implementation. @@ -59,6 +72,19 @@ CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAtt CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector.TryCopyTo(System.Span)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.CompilerServices.IsReadOnlyAttribute' exists on 'System.Numerics.Vector.TryCopyTo(System.Span)' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.RequiresPreviewFeaturesAttribute' exists on 'System.String System.Runtime.CompilerServices.RuntimeFeature.VirtualStaticsInInterfaces' in the contract but not the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.Formatter.Deserialize(System.IO.Stream)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.Formatter.Serialize(System.IO.Stream, System.Object)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.IFormatter.Deserialize(System.IO.Stream)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.IFormatter.Serialize(System.IO.Stream, System.Object)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.DoFixups()' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RaiseOnDeserializingEvent(System.Object)' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RegisterObject(System.Object, System.Int64)' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RegisterObject(System.Object, System.Int64, System.Runtime.Serialization.SerializationInfo)' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RegisterObject(System.Object, System.Int64, System.Runtime.Serialization.SerializationInfo, System.Int64, System.Reflection.MemberInfo)' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RegisterObject(System.Object, System.Int64, System.Runtime.Serialization.SerializationInfo, System.Int64, System.Reflection.MemberInfo, System.Int32[])' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.SerializationObjectManager.RegisterObject(System.Object)' changed from '[RequiresUnreferencedCodeAttribute("SerializationObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("SerializationObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(System.IO.Stream)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(System.IO.Stream, System.Object)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Aes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeDeformatter' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeFormatter' in the contract but not the implementation. @@ -150,6 +176,20 @@ Compat issues with assembly System.Runtime.Intrinsics: MembersMustExist : Member 'public System.Runtime.Intrinsics.Vector128 System.Runtime.Intrinsics.Vector128.As(System.Runtime.Intrinsics.Vector128)' does not exist in the implementation but it does exist in the contract. MembersMustExist : Member 'public System.Runtime.Intrinsics.Vector256 System.Runtime.Intrinsics.Vector256.As(System.Runtime.Intrinsics.Vector256)' does not exist in the implementation but it does exist in the contract. MembersMustExist : Member 'public System.Runtime.Intrinsics.Vector64 System.Runtime.Intrinsics.Vector64.As(System.Runtime.Intrinsics.Vector64)' does not exist in the implementation but it does exist in the contract. +Compat issues with assembly System.Runtime.Serialization.Formatters: +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.Formatter.Deserialize(System.IO.Stream)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.Formatter.Serialize(System.IO.Stream, System.Object)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.IFormatter.Deserialize(System.IO.Stream)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.IFormatter.Serialize(System.IO.Stream, System.Object)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.DoFixups()' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RaiseOnDeserializingEvent(System.Object)' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RegisterObject(System.Object, System.Int64)' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RegisterObject(System.Object, System.Int64, System.Runtime.Serialization.SerializationInfo)' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RegisterObject(System.Object, System.Int64, System.Runtime.Serialization.SerializationInfo, System.Int64, System.Reflection.MemberInfo)' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.ObjectManager.RegisterObject(System.Object, System.Int64, System.Runtime.Serialization.SerializationInfo, System.Int64, System.Reflection.MemberInfo, System.Int32[])' changed from '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("ObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.SerializationObjectManager.RegisterObject(System.Object)' changed from '[RequiresUnreferencedCodeAttribute("SerializationObjectManager is not trim compatible because the Type of objects being managed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("SerializationObjectManager is not trim compatible because the type of objects being managed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(System.IO.Stream)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. +CannotChangeAttribute : Attribute 'System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute' on 'System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(System.IO.Stream, System.Object)' changed from '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the Type of objects being processed cannot be statically discovered.")]' in the contract to '[RequiresUnreferencedCodeAttribute("BinaryFormatter serialization is not trim compatible because the type of objects being processed cannot be statically discovered.")]' in the implementation. Compat issues with assembly System.Security.Cryptography.Algorithms: CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.Aes' in the contract but not the implementation. CannotRemoveAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' exists on 'System.Security.Cryptography.AsymmetricKeyExchangeDeformatter' in the contract but not the implementation. @@ -197,4 +237,4 @@ Compat issues with assembly System.Security.Cryptography.X509Certificates: CannotChangeAttribute : Attribute 'System.Runtime.Versioning.UnsupportedOSPlatformAttribute' on 'System.Security.Cryptography.X509Certificates.PublicKey.GetDSAPublicKey()' changed from '[UnsupportedOSPlatformAttribute("ios")]' in the contract to '[UnsupportedOSPlatformAttribute("browser")]' in the implementation. Compat issues with assembly System.Text.Json: CannotMakeTypeAbstract : Type 'System.Text.Json.Serialization.Metadata.JsonTypeInfo' is abstract in the implementation but is not abstract in the contract. -Total Issues: 184 +Total Issues: 223 From ab380106630654a988e4646fa25ec3137a03ef0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Cant=C3=BA?= Date: Mon, 29 Aug 2022 10:44:13 -0500 Subject: [PATCH 010/107] Add support for indefinite length arrays (#74215) * Add support for indefinite length arrays * Update src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderMap.cs Co-authored-by: campersau * Validate indefinite-length arrays length up-front for fixed-lengh arrays * Update src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs Co-authored-by: Jeremy Barton Co-authored-by: campersau Co-authored-by: Jeremy Barton --- .../src/Resources/Strings.resx | 65 +++++----- .../Cryptography/Cose/CoseHeaderMap.cs | 23 ++-- .../Security/Cryptography/Cose/CoseMessage.cs | 112 ++++++++++++------ .../Cryptography/Cose/CoseMultiSignMessage.cs | 6 +- .../Cryptography/Cose/CoseSign1Message.cs | 2 +- .../Cryptography/Cose/CoseSignature.cs | 16 ++- .../tests/CoseHeaderMapTests.cs | 41 ++++++- .../tests/CoseMessageTests.DecodeMultiSign.cs | 62 ++++++++++ .../tests/CoseMessageTests.DecodeSign1.cs | 33 ++++++ .../tests/CoseTestHelpers.cs | 8 +- 10 files changed, 277 insertions(+), 91 deletions(-) diff --git a/src/libraries/System.Security.Cryptography.Cose/src/Resources/Strings.resx b/src/libraries/System.Security.Cryptography.Cose/src/Resources/Strings.resx index 4a371d8e133298..c03febddebb117 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/Resources/Strings.resx +++ b/src/libraries/System.Security.Cryptography.Cose/src/Resources/Strings.resx @@ -1,17 +1,17 @@  - @@ -154,10 +154,10 @@ Label in Critical Headers array was incorrect. - Critical Headers must be a definite-length CBOR array of at least one element. + Critical Headers must be a CBOR array of at least one element. - COSE Signature must be a definite-length array of 3 elements. + COSE Signature must be an array of three elements. Error while decoding COSE message. {0} @@ -168,11 +168,14 @@ CBOR payload contained trailing data after message was complete. + + COSE_Sign must be an array of four elements. + Incorrect tag. Expected Sign(98) or Untagged, Actual '{0}'. - Array length for COSE_Sign1 must be four. + COSE_Sign1 must be an array of four elements. Protected map was incorrect. @@ -225,4 +228,4 @@ Algorithm (alg) header is required and it must be a protected header. - + \ No newline at end of file diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderMap.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderMap.cs index 5b9e30bc4cf332..50d36b1fa08515 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderMap.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderMap.cs @@ -266,16 +266,18 @@ private static void ValidateInsertion(CoseHeaderLabel label, CoseHeaderValue val reader.SkipValue(); break; case KnownHeaders.Crit: - int length = reader.ReadStartArray().GetValueOrDefault(); - if (length < 1) - { - throw new ArgumentException(SR.CriticalHeadersMustBeArrayOfAtLeastOne, nameof(value)); - } + reader.ReadStartArray(); + bool isEmpty = true; - for (int i = 0; i < length; i++) + while (true) { CborReaderState state = reader.PeekState(); - if (state == CborReaderState.UnsignedInteger || state == CborReaderState.NegativeInteger) + if (state == CborReaderState.EndArray) + { + reader.ReadEndArray(); + break; + } + else if (state == CborReaderState.UnsignedInteger || state == CborReaderState.NegativeInteger) { reader.ReadInt32(); } @@ -287,8 +289,13 @@ private static void ValidateInsertion(CoseHeaderLabel label, CoseHeaderValue val { throw new ArgumentException(SR.Format(SR.CoseHeaderMapHeaderDoesNotAcceptSpecifiedValue, label.LabelName), nameof(value)); } + isEmpty = false; + } + + if (isEmpty) + { + throw new ArgumentException(SR.CriticalHeadersMustBeArrayOfAtLeastOne, nameof(value)); } - reader.SkipToParent(); break; case KnownHeaders.ContentType: if (initialState != CborReaderState.TextString && diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs index 1f5abdc4dd8b8f..1d74e269b4e689 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMessage.cs @@ -128,8 +128,18 @@ private static CoseSign1Message DecodeCoseSign1Core(CborReader reader) throw new CryptographicException(SR.Format(SR.DecodeSign1IncorrectTag, tag)); } + ReadOnlyMemory coseSignArray = reader.ReadEncodedValue(); + + if (reader.BytesRemaining != 0) + { + throw new CryptographicException(SR.Format(SR.DecodeErrorWhileDecoding, SR.DecodeMessageContainedTrailingData)); + } + + reader = new CborReader(coseSignArray); + int? arrayLength = reader.ReadStartArray(); - if (arrayLength != 4) + if (arrayLength.HasValue ? arrayLength != CoseSign1Message.Sign1ArrayLength : + HasIndefiniteLengthArrayIncorrectLength(coseSignArray, CoseSign1Message.Sign1ArrayLength)) { throw new CryptographicException(SR.Format(SR.DecodeErrorWhileDecoding, SR.DecodeSign1ArrayLengthMustBeFour)); } @@ -149,10 +159,7 @@ private static CoseSign1Message DecodeCoseSign1Core(CborReader reader) byte[] signature = DecodeSignature(reader); reader.ReadEndArray(); - if (reader.BytesRemaining != 0) - { - throw new CryptographicException(SR.Format(SR.DecodeErrorWhileDecoding, SR.DecodeMessageContainedTrailingData)); - } + Debug.Assert(reader.BytesRemaining == 0); return new CoseSign1Message(protectedHeader, unprotectedHeader, payload, signature, protectedHeaderAsBstr, tag.HasValue); } @@ -207,10 +214,20 @@ private static CoseMultiSignMessage DecodeCoseMultiSignCore(CborReader reader) throw new CryptographicException(SR.Format(SR.DecodeMultiSignIncorrectTag, tag)); } + ReadOnlyMemory coseSignArray = reader.ReadEncodedValue(); + + if (reader.BytesRemaining != 0) + { + throw new CryptographicException(SR.Format(SR.DecodeErrorWhileDecoding, SR.DecodeMessageContainedTrailingData)); + } + + reader = new CborReader(coseSignArray); + int? arrayLength = reader.ReadStartArray(); - if (arrayLength != 4) + if (arrayLength.HasValue ? arrayLength != CoseMultiSignMessage.MultiSignArrayLength : + HasIndefiniteLengthArrayIncorrectLength(coseSignArray, CoseMultiSignMessage.MultiSignArrayLength)) { - throw new CryptographicException(SR.Format(SR.DecodeErrorWhileDecoding, SR.DecodeSign1ArrayLengthMustBeFour)); + throw new CryptographicException(SR.Format(SR.DecodeErrorWhileDecoding, SR.DecodeMultiSignArrayLengthMustBeFour)); } var protectedHeaders = new CoseHeaderMap(); @@ -225,14 +242,10 @@ private static CoseMultiSignMessage DecodeCoseMultiSignCore(CborReader reader) } byte[]? payload = DecodePayload(reader); - List signatures = DecodeCoseSignaturesArray(reader, encodedProtectedHeaders); + List signatures = DecodeCoseSignaturesArray(reader); reader.ReadEndArray(); - - if (reader.BytesRemaining != 0) - { - throw new CryptographicException(SR.Format(SR.DecodeErrorWhileDecoding, SR.DecodeMessageContainedTrailingData)); - } + Debug.Assert(reader.BytesRemaining == 0); return new CoseMultiSignMessage(protectedHeaders, unprotectedHeaders, payload, signatures, encodedProtectedHeaders, tag.HasValue); } @@ -319,46 +332,77 @@ private static byte[] DecodeSignature(CborReader reader) return reader.ReadByteString(); } - private static List DecodeCoseSignaturesArray(CborReader reader, byte[] bodyProtected) + private static List DecodeCoseSignaturesArray(CborReader reader) { int? signaturesLength = reader.ReadStartArray(); + List signatures = new List(signaturesLength.GetValueOrDefault()); + + while (reader.PeekState() == CborReaderState.StartArray) + { + CoseSignature signature = DecodeCoseSignature(reader.ReadEncodedValue()); + signatures.Add(signature); + } + + reader.ReadEndArray(); - if (signaturesLength.GetValueOrDefault() < 1) + if (signatures.Count < 1) { throw new CryptographicException(SR.Format(SR.DecodeErrorWhileDecoding, SR.MultiSignMessageMustCarryAtLeastOneSignature)); } - List signatures = new List(signaturesLength!.Value); + return signatures; + } - for (int i = 0; i < signaturesLength; i++) + private static CoseSignature DecodeCoseSignature(ReadOnlyMemory coseSignature) + { + var reader = new CborReader(coseSignature); + int? length = reader.ReadStartArray(); + + if (length.HasValue ? length != CoseMultiSignMessage.CoseSignatureArrayLength : + HasIndefiniteLengthArrayIncorrectLength(coseSignature, CoseMultiSignMessage.CoseSignatureArrayLength)) { - int? length = reader.ReadStartArray(); + throw new CryptographicException(SR.Format(SR.DecodeErrorWhileDecoding, SR.DecodeCoseSignatureMustBeArrayOfThree)); + } - if (length != CoseMultiSignMessage.CoseSignatureArrayLength) - { - throw new CryptographicException(SR.Format(SR.DecodeErrorWhileDecoding, SR.DecodeCoseSignatureMustBeArrayOfThree)); - } + var protectedHeaders = new CoseHeaderMap(); + DecodeProtectedBucket(reader, protectedHeaders, out byte[] signProtected); - var protectedHeaders = new CoseHeaderMap(); - DecodeProtectedBucket(reader, protectedHeaders, out byte[] signProtected); + var unprotectedHeaders = new CoseHeaderMap(); + DecodeUnprotectedBucket(reader, unprotectedHeaders); - var unprotectedHeaders = new CoseHeaderMap(); - DecodeUnprotectedBucket(reader, unprotectedHeaders); + if (ContainDuplicateLabels(protectedHeaders, unprotectedHeaders)) + { + throw new CryptographicException(SR.Sign1SignHeaderDuplicateLabels); + } - if (ContainDuplicateLabels(protectedHeaders, unprotectedHeaders)) - { - throw new CryptographicException(SR.Sign1SignHeaderDuplicateLabels); - } + byte[] signatureBytes = DecodeSignature(reader); + reader.ReadEndArray(); - byte[] signatureBytes = DecodeSignature(reader); + return new CoseSignature(protectedHeaders, unprotectedHeaders, signProtected, signatureBytes); + } - signatures.Add(new CoseSignature(protectedHeaders, unprotectedHeaders, bodyProtected, signProtected, signatureBytes)); + private static bool HasIndefiniteLengthArrayIncorrectLength(ReadOnlyMemory encodedArray, int expectedLength) + { + var reader = new CborReader(encodedArray); + reader.ReadStartArray(); + int count = 0; - reader.ReadEndArray(); + while (reader.PeekState() != CborReaderState.EndArray) + { + reader.SkipValue(); + count++; + + if (count > expectedLength) + { + return true; + } } + + bool retVal = count != expectedLength; reader.ReadEndArray(); + Debug.Assert(reader.BytesRemaining == 0); - return signatures; + return retVal; } internal static void AppendToBeSigned( diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMultiSignMessage.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMultiSignMessage.cs index 3b0ecebc015f6e..351f987bd95300 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMultiSignMessage.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseMultiSignMessage.cs @@ -17,7 +17,7 @@ namespace System.Security.Cryptography.Cose /// public sealed class CoseMultiSignMessage : CoseMessage { - private const int MultiSignArrayLength = 4; + internal const int MultiSignArrayLength = 4; private const int MultiSignSizeOfCborTag = 2; internal const int CoseSignatureArrayLength = 3; @@ -804,7 +804,7 @@ private void AddSignatureCore(ReadOnlySpan contentBytes, Stream? contentSt bytesWritten = CoseHelpers.SignHash(signer, hasher, buffer); byte[] signature = bufferSpan.Slice(0, bytesWritten).ToArray(); - _signatures.Add(new CoseSignature(this, signProtectedHeaders, signer.UnprotectedHeaders, _protectedHeaderAsBstr, encodedSignProtected, signature)); + _signatures.Add(new CoseSignature(this, signProtectedHeaders, signer.UnprotectedHeaders, encodedSignProtected, signature)); } } finally @@ -877,7 +877,7 @@ private async Task AddSignatureCoreAsync(Stream content, CoseSigner signer, Read bytesWritten = CoseHelpers.SignHash(signer, hasher, buffer); byte[] signature = buffer.AsSpan(0, bytesWritten).ToArray(); - _signatures.Add(new CoseSignature(this, signProtectedHeaders, signer.UnprotectedHeaders, _protectedHeaderAsBstr, encodedSignProtected, signature)); + _signatures.Add(new CoseSignature(this, signProtectedHeaders, signer.UnprotectedHeaders, encodedSignProtected, signature)); } ArrayPool.Shared.Return(buffer, clearArray: true); diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSign1Message.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSign1Message.cs index a38a5847507dcc..4a4bdc5887b034 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSign1Message.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSign1Message.cs @@ -15,7 +15,7 @@ namespace System.Security.Cryptography.Cose /// public sealed class CoseSign1Message : CoseMessage { - private const int Sign1ArrayLength = 4; + internal const int Sign1ArrayLength = 4; private const int Sign1SizeOfCborTag = 1; private readonly byte[] _signature; diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSignature.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSignature.cs index c716e077124b2c..831c5c8f676bd2 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSignature.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseSignature.cs @@ -14,7 +14,6 @@ namespace System.Security.Cryptography.Cose /// public sealed class CoseSignature { - private readonly byte[] _encodedBodyProtectedHeaders; internal readonly byte[] _encodedSignProtectedHeaders; internal readonly byte[] _signature; private CoseMultiSignMessage? _message; @@ -43,17 +42,16 @@ public sealed class CoseSignature /// A region of memory that contains the digital signature. public ReadOnlyMemory Signature => _signature; - internal CoseSignature(CoseMultiSignMessage message, CoseHeaderMap protectedHeaders, CoseHeaderMap unprotectedHeaders, byte[] encodedBodyProtectedHeaders, byte[] encodedSignProtectedHeaders, byte[] signature) - : this(protectedHeaders, unprotectedHeaders, encodedBodyProtectedHeaders, encodedSignProtectedHeaders, signature) + internal CoseSignature(CoseMultiSignMessage message, CoseHeaderMap protectedHeaders, CoseHeaderMap unprotectedHeaders, byte[] encodedSignProtectedHeaders, byte[] signature) + : this(protectedHeaders, unprotectedHeaders, encodedSignProtectedHeaders, signature) { Message = message; } - internal CoseSignature(CoseHeaderMap protectedHeaders, CoseHeaderMap unprotectedHeaders, byte[] encodedBodyProtectedHeaders, byte[] encodedSignProtectedHeaders, byte[] signature) + internal CoseSignature(CoseHeaderMap protectedHeaders, CoseHeaderMap unprotectedHeaders, byte[] encodedSignProtectedHeaders, byte[] signature) { ProtectedHeaders = protectedHeaders; UnprotectedHeaders = unprotectedHeaders; - _encodedBodyProtectedHeaders = encodedBodyProtectedHeaders; _encodedSignProtectedHeaders = encodedSignProtectedHeaders; _signature = signature; } @@ -400,7 +398,7 @@ private async Task VerifyAsyncCore(AsymmetricAlgorithm key, Stream content { int bufferLength = CoseMessage.ComputeToBeSignedEncodedSize( SigStructureContext.Signature, - _encodedBodyProtectedHeaders.Length, + Message.RawProtectedHeaders.Length, _encodedSignProtectedHeaders.Length, associatedData.Length, contentLength: 0); @@ -408,7 +406,7 @@ private async Task VerifyAsyncCore(AsymmetricAlgorithm key, Stream content try { - await CoseMessage.AppendToBeSignedAsync(buffer, hasher, SigStructureContext.Signature, _encodedBodyProtectedHeaders, _encodedSignProtectedHeaders, associatedData, content, cancellationToken).ConfigureAwait(false); + await CoseMessage.AppendToBeSignedAsync(buffer, hasher, SigStructureContext.Signature, Message.RawProtectedHeaders, _encodedSignProtectedHeaders, associatedData, content, cancellationToken).ConfigureAwait(false); return VerifyHash(key, hasher, hashAlgorithm, keyType, padding); } finally @@ -432,7 +430,7 @@ private bool VerifyCore(AsymmetricAlgorithm key, ReadOnlySpan contentBytes { int bufferLength = CoseMessage.ComputeToBeSignedEncodedSize( SigStructureContext.Signature, - _encodedBodyProtectedHeaders.Length, + Message.RawProtectedHeaders.Length, _encodedSignProtectedHeaders.Length, associatedData.Length, contentLength: 0); @@ -440,7 +438,7 @@ private bool VerifyCore(AsymmetricAlgorithm key, ReadOnlySpan contentBytes try { - CoseMessage.AppendToBeSigned(buffer, hasher, SigStructureContext.Signature, _encodedBodyProtectedHeaders, _encodedSignProtectedHeaders, associatedData, contentBytes, contentStream); + CoseMessage.AppendToBeSigned(buffer, hasher, SigStructureContext.Signature, Message.RawProtectedHeaders.Span, _encodedSignProtectedHeaders, associatedData, contentBytes, contentStream); return VerifyHash(key, hasher, hashAlgorithm, keyType, padding); } finally diff --git a/src/libraries/System.Security.Cryptography.Cose/tests/CoseHeaderMapTests.cs b/src/libraries/System.Security.Cryptography.Cose/tests/CoseHeaderMapTests.cs index c21562ba690202..5af3af378d02fc 100644 --- a/src/libraries/System.Security.Cryptography.Cose/tests/CoseHeaderMapTests.cs +++ b/src/libraries/System.Security.Cryptography.Cose/tests/CoseHeaderMapTests.cs @@ -295,6 +295,41 @@ public void RemoveKeyValuePair_DoesNotMatchKeyOrValue(bool changeKey) Assert.Equal(1, map.Count); } + [Fact] + public void SetEncodedValue_CriticalHeaders_ThrowIf_ArrayEmpty() + { + // definite length + var writer = new CborWriter(); + writer.WriteStartArray(0); + writer.WriteEndArray(); + + Verify(writer.Encode()); + + // indefinite length + writer.Reset(); + writer.WriteStartArray(null); + writer.WriteEndArray(); + + Verify(writer.Encode()); + + void Verify(byte[] encodedValue) + { + CoseHeaderMap map = new(); + CoseHeaderValue value = CoseHeaderValue.FromEncodedValue(writer.Encode()); + Assert.Throws(() => map[CoseHeaderLabel.CriticalHeaders] = value); + } + } + + [Fact] + public void SetEncodedValue_CriticalHeaders_ThrowIf_IndefiniteLengthArrayMissingBreak() + { + byte[] encodedValue = GetDummyCritHeaderValue(useIndefiniteLength: true); + + CoseHeaderMap map = new(); + CoseHeaderValue value = CoseHeaderValue.FromEncodedValue(encodedValue.AsSpan(0, encodedValue.Length - 1)); + Assert.Throws(() => map[CoseHeaderLabel.CriticalHeaders] = value); + } + public enum SetValueMethod { ItemSet, @@ -493,7 +528,11 @@ public static IEnumerable KnownHeadersEncodedValues_TestData() writer.WriteInt32((int)ECDsaAlgorithm.ES256); yield return ReturnDataAndReset(KnownHeaderAlg, writer, setMethod, getMethod); - WriteDummyCritHeaderValue(writer); + WriteDummyCritHeaderValue(writer, useIndefiniteLength: false); + yield return ReturnDataAndReset(KnownHeaderCrit, writer, setMethod, getMethod); + + + WriteDummyCritHeaderValue(writer, useIndefiniteLength: true); yield return ReturnDataAndReset(KnownHeaderCrit, writer, setMethod, getMethod); writer.WriteTextString(ContentTypeDummyValue); diff --git a/src/libraries/System.Security.Cryptography.Cose/tests/CoseMessageTests.DecodeMultiSign.cs b/src/libraries/System.Security.Cryptography.Cose/tests/CoseMessageTests.DecodeMultiSign.cs index 4ba9403898e7d0..57fd753af4c011 100644 --- a/src/libraries/System.Security.Cryptography.Cose/tests/CoseMessageTests.DecodeMultiSign.cs +++ b/src/libraries/System.Security.Cryptography.Cose/tests/CoseMessageTests.DecodeMultiSign.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Collections.Generic; using System.Collections.ObjectModel; using System.Formats.Cbor; using Test.Cryptography; @@ -82,5 +83,66 @@ public void DecodeMultiSign_IncorrectStructure() writer.WriteEndArray(); Assert.Throws(() => CoseMessage.DecodeMultiSign(writer.Encode())); } + + [Theory] + // COSE_Sign is an indefinite-length array + [InlineData("D8629F40A054546869732069732074686520636F6E74656E742E818343A10126A1044231315840E2AEAFD40D69D19DFE6E52077C5D7FF4E408282CBEFB5D06CBF414AF2E19D982AC45AC98B8544C908B4507DE1E90B717C3D34816FE926A2B98F53AFD2FA0F30AFF")] + // [+COSE_Signature] + [InlineData("D8628440A054546869732069732074686520636F6E74656E742E9F8343A10126A1044231315840E2AEAFD40D69D19DFE6E52077C5D7FF4E408282CBEFB5D06CBF414AF2E19D982AC45AC98B8544C908B4507DE1E90B717C3D34816FE926A2B98F53AFD2FA0F30AFF")] + // COSE_Signature + [InlineData("D8628440A054546869732069732074686520636F6E74656E742E819F43A10126A1044231315840E2AEAFD40D69D19DFE6E52077C5D7FF4E408282CBEFB5D06CBF414AF2E19D982AC45AC98B8544C908B4507DE1E90B717C3D34816FE926A2B98F53AFD2FA0F30AFF")] + // All of them + [InlineData("D8629F40A054546869732069732074686520636F6E74656E742E9F9F43A10126A1044231315840E2AEAFD40D69D19DFE6E52077C5D7FF4E408282CBEFB5D06CBF414AF2E19D982AC45AC98B8544C908B4507DE1E90B717C3D34816FE926A2B98F53AFD2FA0F30AFFFFFF")] + public void DecodeMultiSign_IndefiniteLengthArray(string hexCborPayload) + { + byte[] cborPayload = ByteUtils.HexToByteArray(hexCborPayload); + CoseMultiSignMessage msg = CoseMessage.DecodeMultiSign(cborPayload); + + ReadOnlyCollection signatures = msg.Signatures; + Assert.Equal(1, signatures.Count); + Assert.True(signatures[0].VerifyEmbedded(DefaultKey)); + } + + [Theory] + // COSE_Sign + [InlineData("D8629F40A054546869732069732074686520636F6E74656E742E818343A10126A1044231315840E2AEAFD40D69D19DFE6E52077C5D7FF4E408282CBEFB5D06CBF414AF2E19D982AC45AC98B8544C908B4507DE1E90B717C3D34816FE926A2B98F53AFD2FA0F30A")] + // [+COSE_Signature] + [InlineData("D8628440A054546869732069732074686520636F6E74656E742E9F8343A10126A1044231315840E2AEAFD40D69D19DFE6E52077C5D7FF4E408282CBEFB5D06CBF414AF2E19D982AC45AC98B8544C908B4507DE1E90B717C3D34816FE926A2B98F53AFD2FA0F30A")] + // COSE_Signature + [InlineData("D8628440A054546869732069732074686520636F6E74656E742E819F43A10126A1044231315840E2AEAFD40D69D19DFE6E52077C5D7FF4E408282CBEFB5D06CBF414AF2E19D982AC45AC98B8544C908B4507DE1E90B717C3D34816FE926A2B98F53AFD2FA0F30A")] + public void DecodeMultiSign_IndefiniteLengthArray_MissingBreak(string hexCborPayload) + { + byte[] cborPayload = ByteUtils.HexToByteArray(hexCborPayload); + CryptographicException ex = Assert.Throws(() => CoseMessage.DecodeMultiSign(cborPayload)); + Assert.IsType(ex.InnerException); + } + + // All these payloads contain one extra element of type byte string. + [Theory] + // COSE_Sign + [InlineData("D8629F40A054546869732069732074686520636F6E74656E742E818343A10126A1044231315840E2AEAFD40D69D19DFE6E52077C5D7FF4E408282CBEFB5D06CBF414AF2E19D982AC45AC98B8544C908B4507DE1E90B717C3D34816FE926A2B98F53AFD2FA0F30A40FF")] + // [+COSE_Signature] - this structure does not have a fixed length required, but the byte string is unexpected. + [InlineData("D8628440A054546869732069732074686520636F6E74656E742E9F8343A10126A1044231315840E2AEAFD40D69D19DFE6E52077C5D7FF4E408282CBEFB5D06CBF414AF2E19D982AC45AC98B8544C908B4507DE1E90B717C3D34816FE926A2B98F53AFD2FA0F30A40FF")] + // COSE_Signature + [InlineData("D8628440A054546869732069732074686520636F6E74656E742E819F43A10126A1044231315840E2AEAFD40D69D19DFE6E52077C5D7FF4E408282CBEFB5D06CBF414AF2E19D982AC45AC98B8544C908B4507DE1E90B717C3D34816FE926A2B98F53AFD2FA0F30A40FF")] + public void DecodeMultiSign_IndefiniteLengthArray_LargerByOne(string hexCborPayload) + { + byte[] cborPayload = ByteUtils.HexToByteArray(hexCborPayload); + CryptographicException ex = Assert.Throws(() => CoseMessage.DecodeMultiSign(cborPayload)); + } + + [Theory] + // COSE_Sign + [InlineData("D8629F40A054546869732069732074686520636F6E74656E742EFF")] + // [+COSE_Signature] + [InlineData("D8628440A054546869732069732074686520636F6E74656E742E9FFF")] + // COSE_Signature + [InlineData("D8628440A054546869732069732074686520636F6E74656E742E819F43A10126A104423131FF")] + public void DecodeMultiSign_IndefiniteLengthArray_ShorterByOne(string hexCborPayload) + { + byte[] cborPayload = ByteUtils.HexToByteArray(hexCborPayload); + CryptographicException ex = Assert.Throws(() => CoseMessage.DecodeMultiSign(cborPayload)); + Assert.Null(ex.InnerException); + } } } diff --git a/src/libraries/System.Security.Cryptography.Cose/tests/CoseMessageTests.DecodeSign1.cs b/src/libraries/System.Security.Cryptography.Cose/tests/CoseMessageTests.DecodeSign1.cs index 129eec8dccf557..8d3fdb27ad5dea 100644 --- a/src/libraries/System.Security.Cryptography.Cose/tests/CoseMessageTests.DecodeSign1.cs +++ b/src/libraries/System.Security.Cryptography.Cose/tests/CoseMessageTests.DecodeSign1.cs @@ -69,5 +69,38 @@ public void DecodeSign1_IncorrectStructure() writer.WriteEndArray(); Assert.Throws(() => CoseMessage.DecodeSign1(writer.Encode())); } + + [Fact] + public void DecodeSign1_IndefiniteLengthArray() + { + byte[] cborPayload = ByteUtils.HexToByteArray("D29F43A10126A10442313154546869732069732074686520636F6E74656E742E58408EB33E4CA31D1C465AB05AAC34CC6B23D58FEF5C083106C4D25A91AEF0B0117E2AF9A291AA32E14AB834DC56ED2A223444547E01F11D3B0916E5A4C345CACB36FF"); + CoseSign1Message msg = CoseMessage.DecodeSign1(cborPayload); + + Assert.True(msg.VerifyEmbedded(DefaultKey)); + } + + [Fact] + public void DecodeSign1_IndefiniteLengthArray_MissingBreak() + { + byte[] cborPayload = ByteUtils.HexToByteArray("D29F43A10126A10442313154546869732069732074686520636F6E74656E742E58408EB33E4CA31D1C465AB05AAC34CC6B23D58FEF5C083106C4D25A91AEF0B0117E2AF9A291AA32E14AB834DC56ED2A223444547E01F11D3B0916E5A4C345CACB36"); + CryptographicException ex = Assert.Throws(() => CoseMessage.DecodeSign1(cborPayload)); + Assert.IsType(ex.InnerException); + } + + [Fact] + public void DecodeSign1_IndefiniteLengthArray_LargerByOne() + { + byte[] cborPayload = ByteUtils.HexToByteArray("D29F43A10126A10442313154546869732069732074686520636F6E74656E742E58408EB33E4CA31D1C465AB05AAC34CC6B23D58FEF5C083106C4D25A91AEF0B0117E2AF9A291AA32E14AB834DC56ED2A223444547E01F11D3B0916E5A4C345CACB3640FF"); + CryptographicException ex = Assert.Throws(() => CoseMessage.DecodeSign1(cborPayload)); + Assert.Null(ex.InnerException); + } + + [Fact] + public void DecodeSign1_IndefiniteLengthArray_ShorterByOne() + { + byte[] cborPayload = ByteUtils.HexToByteArray("D29F43A10126A10442313154546869732069732074686520636F6E74656E742EFF"); + CryptographicException ex = Assert.Throws(() => CoseMessage.DecodeSign1(cborPayload)); + Assert.Null(ex.InnerException); + } } } diff --git a/src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs b/src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs index 8716f3c34071b8..4eb5d7dba72dd5 100644 --- a/src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs +++ b/src/libraries/System.Security.Cryptography.Cose/tests/CoseTestHelpers.cs @@ -541,17 +541,17 @@ internal enum CoseMessageKind MultiSign = 98 } - internal static void WriteDummyCritHeaderValue(CborWriter writer) + internal static void WriteDummyCritHeaderValue(CborWriter writer, bool useIndefiniteLength = false) { - writer.WriteStartArray(1); + writer.WriteStartArray(useIndefiniteLength ? null : 1); writer.WriteInt32(42); writer.WriteEndArray(); } - internal static byte[] GetDummyCritHeaderValue() + internal static byte[] GetDummyCritHeaderValue(bool useIndefiniteLength = false) { var writer = new CborWriter(); - WriteDummyCritHeaderValue(writer); + WriteDummyCritHeaderValue(writer, useIndefiniteLength); return writer.Encode(); } From 78fa703bacbed0dba3466d2c05fcf1dd45dc9fd5 Mon Sep 17 00:00:00 2001 From: Meri Khamoyan <96171496+mkhamoyan@users.noreply.github.com> Date: Mon, 29 Aug 2022 19:53:45 +0400 Subject: [PATCH 011/107] #50866 enable configuration functional test on android (#74651) --- .../tests/FunctionalTests/ConfigurationTests.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/libraries/Microsoft.Extensions.Configuration/tests/FunctionalTests/ConfigurationTests.cs b/src/libraries/Microsoft.Extensions.Configuration/tests/FunctionalTests/ConfigurationTests.cs index 7c03f5f45f634a..aa91bc9d7b3d9a 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/tests/FunctionalTests/ConfigurationTests.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/tests/FunctionalTests/ConfigurationTests.cs @@ -814,7 +814,6 @@ await WaitForChange( } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50866", TestPlatforms.Android)] public void LoadIncorrectJsonFile_ThrowException() { var json = @"{ From 19e1035d6222231566a2a2c669d086c66e5b40d4 Mon Sep 17 00:00:00 2001 From: Meri Khamoyan <96171496+mkhamoyan@users.noreply.github.com> Date: Mon, 29 Aug 2022 19:55:18 +0400 Subject: [PATCH 012/107] #50868 enable configuration json tests on Android (#74647) --- .../tests/JsonConfigurationExtensionsTest.cs | 2 -- .../tests/JsonConfigurationTest.cs | 4 ---- 2 files changed, 6 deletions(-) diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/tests/JsonConfigurationExtensionsTest.cs b/src/libraries/Microsoft.Extensions.Configuration.Json/tests/JsonConfigurationExtensionsTest.cs index e1558d7efece03..ba37d44740b88e 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Json/tests/JsonConfigurationExtensionsTest.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Json/tests/JsonConfigurationExtensionsTest.cs @@ -12,7 +12,6 @@ public class JsonConfigurationExtensionsTest [Theory] [InlineData(null)] [InlineData("")] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50868", TestPlatforms.Android)] public void AddJsonFile_ThrowsIfFilePathIsNullOrEmpty(string path) { // Arrange @@ -25,7 +24,6 @@ public void AddJsonFile_ThrowsIfFilePathIsNullOrEmpty(string path) } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50868", TestPlatforms.Android)] public void AddJsonFile_ThrowsIfFileDoesNotExistAtPath() { // Arrange diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/tests/JsonConfigurationTest.cs b/src/libraries/Microsoft.Extensions.Configuration.Json/tests/JsonConfigurationTest.cs index dc17b5f82437ba..2e3fe00acb2305 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Json/tests/JsonConfigurationTest.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Json/tests/JsonConfigurationTest.cs @@ -152,7 +152,6 @@ public void SupportAndIgnoreTrailingCommas() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50868", TestPlatforms.Android)] public void ThrowExceptionWhenUnexpectedEndFoundBeforeFinishParsing() { var json = @"{ @@ -167,7 +166,6 @@ public void ThrowExceptionWhenUnexpectedEndFoundBeforeFinishParsing() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50868", TestPlatforms.Android)] public void ThrowExceptionWhenMissingCurlyBeforeFinishParsing() { var json = @" @@ -200,7 +198,6 @@ public void ThrowExceptionWhenPassingEmptyStringAsFilePath() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50868", TestPlatforms.Android)] public void JsonConfiguration_Throws_On_Missing_Configuration_File() { var config = new ConfigurationBuilder().AddJsonFile("NotExistingConfig.json", optional: false); @@ -217,7 +214,6 @@ public void JsonConfiguration_Does_Not_Throw_On_Optional_Configuration() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50868", TestPlatforms.Android)] public void ThrowFormatExceptionWhenFileIsEmpty() { var exception = Assert.Throws(() => LoadProvider(@"")); From 11351bc8dc10847201e161f07bededb5a252c723 Mon Sep 17 00:00:00 2001 From: Eric StJohn Date: Mon, 29 Aug 2022 09:10:47 -0700 Subject: [PATCH 013/107] Add Nick to fabric-bot config (#74666) --- .github/fabricbot.json | 481 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 428 insertions(+), 53 deletions(-) diff --git a/.github/fabricbot.json b/.github/fabricbot.json index 449cf4d51bc7b2..4124337c3031d9 100644 --- a/.github/fabricbot.json +++ b/.github/fabricbot.json @@ -13939,12 +13939,12 @@ "subCapability": "IssuesOnlyResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - Issue Triage] Moved to Another Area", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage] Moved to Another Area", "actions": [ { "name": "removeFromProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "isOrgProject": true } } @@ -14113,7 +14113,7 @@ { "name": "isInProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "isOrgProject": true } } @@ -14128,19 +14128,19 @@ "subCapability": "IssuesOnlyResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - Issue Triage] Needs Triage", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage] Needs Triage", "actions": [ { "name": "removeFromProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "isOrgProject": true } }, { "name": "addToProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "columnName": "Needs Triage", "isOrgProject": true } @@ -14362,7 +14362,7 @@ { "name": "isInProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "isOrgProject": true } } @@ -14371,7 +14371,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "isOrgProject": true, "columnName": "Triaged" } @@ -14389,19 +14389,19 @@ "subCapability": "IssueCommentResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - Issue Triage] Needs Further Triage", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage] Needs Further Triage", "actions": [ { "name": "removeFromProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "isOrgProject": true } }, { "name": "addToProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "columnName": "Needs Triage", "isOrgProject": true } @@ -14521,7 +14521,7 @@ { "name": "isInProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "isOrgProject": true } } @@ -14530,7 +14530,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "columnName": "Triaged", "isOrgProject": true } @@ -14548,12 +14548,12 @@ "subCapability": "IssuesOnlyResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - Issue Triage] Triaged", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage] Triaged", "actions": [ { "name": "addToProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "columnName": "Triaged", "isOrgProject": true } @@ -14575,7 +14575,7 @@ { "name": "isInProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "isOrgProject": true } }, @@ -14617,12 +14617,12 @@ "subCapability": "IssuesOnlyResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - Issue Triage] Maryam Updated Issue", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage] Maryam Updated Issue", "actions": [ { "name": "moveToProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "columnName": "Triage: Maryam", "isOrgProject": true } @@ -14638,7 +14638,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "isOrgProject": true, "columnName": "Needs Triage" } @@ -14695,12 +14695,12 @@ "subCapability": "IssueCommentResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - Issue Triage] Maryam Commented", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage] Maryam Commented", "actions": [ { "name": "moveToProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "columnName": "Triage: Maryam", "isOrgProject": true } @@ -14716,7 +14716,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "isOrgProject": true, "columnName": "Needs Triage" } @@ -14773,12 +14773,168 @@ "subCapability": "IssuesOnlyResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - Issue Triage] Tarek Updated Issue", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage] Nick Updated Issue", "actions": [ { "name": "moveToProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", + "columnName": "Triage: Nick", + "isOrgProject": true + } + } + ], + "eventType": "issue", + "eventNames": [ + "issues" + ], + "conditions": { + "operator": "and", + "operands": [ + { + "name": "isInProjectColumn", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", + "isOrgProject": true, + "columnName": "Needs Triage" + } + }, + { + "name": "isActivitySender", + "parameters": { + "user": "Nick-Stanton" + } + }, + { + "name": "isOpen", + "parameters": {} + }, + { + "operator": "not", + "operands": [ + { + "name": "isInMilestone", + "parameters": {} + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "needs-author-action" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "api-ready-for-review" + } + } + ] + } + ] + } + } + }, + { + "taskSource": "fabricbot-config", + "taskType": "trigger", + "capabilityId": "IssueResponder", + "subCapability": "IssueCommentResponder", + "version": "1.0", + "config": { + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage] Nick Commented", + "actions": [ + { + "name": "moveToProjectColumn", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", + "columnName": "Triage: Nick", + "isOrgProject": true + } + } + ], + "eventType": "issue", + "eventNames": [ + "issue_comment" + ], + "conditions": { + "operator": "and", + "operands": [ + { + "name": "isInProjectColumn", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", + "isOrgProject": true, + "columnName": "Needs Triage" + } + }, + { + "name": "isActivitySender", + "parameters": { + "user": "Nick-Stanton" + } + }, + { + "name": "isOpen", + "parameters": {} + }, + { + "operator": "not", + "operands": [ + { + "name": "isInMilestone", + "parameters": {} + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "needs-author-action" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "api-ready-for-review" + } + } + ] + } + ] + } + } + }, + { + "taskSource": "fabricbot-config", + "taskType": "trigger", + "capabilityId": "IssueResponder", + "subCapability": "IssuesOnlyResponder", + "version": "1.0", + "config": { + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage] Tarek Updated Issue", + "actions": [ + { + "name": "moveToProjectColumn", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "columnName": "Triage: Tarek", "isOrgProject": true } @@ -14794,7 +14950,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "isOrgProject": true, "columnName": "Needs Triage" } @@ -14851,12 +15007,12 @@ "subCapability": "IssueCommentResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - Issue Triage] Tarek Commented", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage] Tarek Commented", "actions": [ { "name": "moveToProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "columnName": "Triage: Tarek", "isOrgProject": true } @@ -14872,7 +15028,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - Issue Triage", "isOrgProject": true, "columnName": "Needs Triage" } @@ -14929,12 +15085,12 @@ "subCapability": "PullRequestResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - PRs] Closed, Merged, or Moved", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - PRs] Closed, Merged, or Moved", "actions": [ { "name": "moveToProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "columnName": "Done", "isOrgProject": true } @@ -14950,7 +15106,7 @@ { "name": "isInProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "isOrgProject": true } }, @@ -14960,7 +15116,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "columnName": "Done", "isOrgProject": true } @@ -15140,12 +15296,12 @@ "subCapability": "PullRequestResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - PRs] New PR Needs Champion", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - PRs] New PR Needs Champion", "actions": [ { "name": "addToProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "columnName": "Needs Champion", "isOrgProject": true } @@ -15296,6 +15452,30 @@ ] } ], + [ + { + "operator": "not", + "operands": [ + { + "name": "isAssignedToUser", + "parameters": { + "user": "Nick-Stanton" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "isActivitySender", + "parameters": { + "user": "Nick-Stanton" + } + } + ] + } + ], [ { "operator": "not", @@ -15330,7 +15510,7 @@ { "name": "isInProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "isOrgProject": true } } @@ -15339,7 +15519,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "columnName": "Done", "isOrgProject": true } @@ -15357,19 +15537,19 @@ "subCapability": "PullRequestResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - PRs] Updated PR Needs Champion", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - PRs] Updated PR Needs Champion", "actions": [ { "name": "removeFromProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "isOrgProject": true } }, { "name": "addToProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "columnName": "Needs Champion", "isOrgProject": true } @@ -15502,6 +15682,17 @@ } ] }, + { + "operator": "not", + "operands": [ + { + "name": "isAssignedToUser", + "parameters": { + "user": "Nick-Stanton" + } + } + ] + }, { "operator": "not", "operands": [ @@ -15522,7 +15713,7 @@ { "name": "isInProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "isOrgProject": true } } @@ -15531,7 +15722,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "columnName": "Done", "isOrgProject": true } @@ -15549,19 +15740,19 @@ "subCapability": "PullRequestResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - PRs] Maryam Assigned as Champion", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - PRs] Maryam Assigned as Champion", "actions": [ { "name": "removeFromProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "isOrgProject": true } }, { "name": "addToProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "columnName": "Champion: Maryam", "isOrgProject": true } @@ -15698,7 +15889,191 @@ { "name": "isInProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", + "isOrgProject": true + } + } + ] + }, + { + "name": "isInProjectColumn", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", + "columnName": "Needs Champion", + "isOrgProject": true + } + }, + { + "name": "isInProjectColumn", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", + "columnName": "Done", + "isOrgProject": true + } + } + ] + } + ] + } + } + }, + { + "taskSource": "fabricbot-config", + "taskType": "trigger", + "capabilityId": "IssueResponder", + "subCapability": "PullRequestResponder", + "version": "1.0", + "config": { + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - PRs] Nick Assigned as Champion", + "actions": [ + { + "name": "removeFromProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", + "isOrgProject": true + } + }, + { + "name": "addToProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", + "columnName": "Champion: Nick", + "isOrgProject": true + } + } + ], + "eventType": "pull_request", + "eventNames": [ + "pull_request" + ], + "conditions": { + "operator": "and", + "operands": [ + { + "name": "isOpen", + "parameters": {} + }, + { + "operator": "or", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-DependencyModel" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Caching" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Configuration" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-DependencyInjection" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Hosting" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Logging" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Options" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Primitives" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.ComponentModel" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.ComponentModel.Composition" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Composition" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Diagnostics.Activity" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Globalization" + } + } + ] + }, + { + "operator": "or", + "operands": [ + { + "name": "isAssignedToUser", + "parameters": { + "user": "Nick-Stanton" + } + }, + { + "operator": "and", + "operands": [ + { + "name": "isAction", + "parameters": { + "action": "opened" + } + }, + { + "name": "isActivitySender", + "parameters": { + "user": "Nick-Stanton" + } + } + ] + } + ] + }, + { + "operator": "or", + "operands": [ + { + "operator": "not", + "operands": [ + { + "name": "isInProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "isOrgProject": true } } @@ -15707,7 +16082,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "columnName": "Needs Champion", "isOrgProject": true } @@ -15715,7 +16090,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "columnName": "Done", "isOrgProject": true } @@ -15733,19 +16108,19 @@ "subCapability": "PullRequestResponder", "version": "1.0", "config": { - "taskName": "[Area Pod: Eric / Maryam / Tarek - PRs] Tarek Assigned as Champion", + "taskName": "[Area Pod: Eric / Maryam / Nick / Tarek - PRs] Tarek Assigned as Champion", "actions": [ { "name": "removeFromProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "isOrgProject": true } }, { "name": "addToProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "columnName": "Champion: Tarek", "isOrgProject": true } @@ -15882,7 +16257,7 @@ { "name": "isInProject", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "isOrgProject": true } } @@ -15891,7 +16266,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "columnName": "Needs Champion", "isOrgProject": true } @@ -15899,7 +16274,7 @@ { "name": "isInProjectColumn", "parameters": { - "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "projectName": "Area Pod: Eric / Maryam / Nick / Tarek - PRs", "columnName": "Done", "isOrgProject": true } From b11d401b1e1bbbb8aeb1d91c2dc40eccf6cb79e2 Mon Sep 17 00:00:00 2001 From: Alhad Deshpande <97085048+alhad-deshpande@users.noreply.github.com> Date: Mon, 29 Aug 2022 21:59:28 +0530 Subject: [PATCH 014/107] Ppc64le bug fixes (#74746) This PR fixes below 2 github issues: 1. Stack unwinding segmentation fault occurring in System.Runtime.Tests, fixed [74069](https://github.com/dotnet/runtime/issues/74069) 2. Conditional branching g_assert occurring in PCR2 tests[74057](https://github.com/dotnet/runtime/issues/74057) Fixes #74069 Fixes #74057 Co-authored-by: Sapana Khemkar Co-authored-by: Sapana-Khemkar <94051076+Sapana-Khemkar@users.noreply.github.com> Co-authored-by: vikasgupta8 --- src/mono/mono/mini/exceptions-ppc.c | 4 ++-- src/mono/mono/mini/mini-ppc.c | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/mono/mono/mini/exceptions-ppc.c b/src/mono/mono/mini/exceptions-ppc.c index 99dc4b447d2128..69f6c490c13cb5 100644 --- a/src/mono/mono/mini/exceptions-ppc.c +++ b/src/mono/mono/mini/exceptions-ppc.c @@ -564,9 +564,9 @@ mono_arch_unwind_frame (MonoJitTlsData *jit_tls, unwind_info = mono_jinfo_get_unwind_info (ji, &unwind_info_len); - sframe = (MonoPPCStackFrame*)MONO_CONTEXT_GET_SP (ctx); - MONO_CONTEXT_SET_BP (new_ctx, sframe->sp); if (!ji->is_trampoline && jinfo_get_method (ji)->save_lmf) { + sframe = (MonoPPCStackFrame*)MONO_CONTEXT_GET_SP (ctx); + MONO_CONTEXT_SET_BP (new_ctx, sframe->sp); /* sframe->sp points just past the end of the LMF */ guint8 *lmf_addr = (guint8*)sframe->sp - sizeof (MonoLMF); memcpy (&new_ctx->fregs [MONO_PPC_FIRST_SAVED_FREG], lmf_addr + G_STRUCT_OFFSET (MonoLMF, fregs), sizeof (double) * MONO_SAVED_FREGS); diff --git a/src/mono/mono/mini/mini-ppc.c b/src/mono/mono/mini/mini-ppc.c index cf8f045f992371..d1b8fc97907833 100644 --- a/src/mono/mono/mini/mini-ppc.c +++ b/src/mono/mono/mini/mini-ppc.c @@ -1891,7 +1891,7 @@ typedef struct { if (0 && ins->inst_true_bb->native_offset) { \ ppc_bc (code, (b0), (b1), (code - cfg->native_code + ins->inst_true_bb->native_offset) & 0xffff); \ } else { \ - int br_disp = ins->inst_true_bb->max_offset - offset; \ + int br_disp = ins->inst_true_bb->max_offset - cpos; \ if (!ppc_is_imm16 (br_disp + 8 * 1024) || !ppc_is_imm16 (br_disp - 8 * 1024)) { \ MonoOvfJump *ovfj = mono_mempool_alloc (cfg->mempool, sizeof (MonoOvfJump)); \ ovfj->data.bb = ins->inst_true_bb; \ @@ -1915,7 +1915,7 @@ if (0 && ins->inst_true_bb->native_offset) { \ */ #define EMIT_COND_SYSTEM_EXCEPTION_FLAGS(b0,b1,exc_name) \ do { \ - int br_disp = cfg->bb_exit->max_offset - offset; \ + int br_disp = cfg->bb_exit->max_offset - cpos; \ if (!ppc_is_imm16 (br_disp + 1024) || ! ppc_is_imm16 (ppc_is_imm16 (br_disp - 1024))) { \ MonoOvfJump *ovfj = mono_mempool_alloc (cfg->mempool, sizeof (MonoOvfJump)); \ ovfj->data.exception = (exc_name); \ From d9cfbb4d5e2e861a36a974ca36b62a2f98a611ca Mon Sep 17 00:00:00 2001 From: Filip Navara Date: Mon, 29 Aug 2022 18:56:01 +0200 Subject: [PATCH 015/107] Disable KerberosExecutor on LinuxBionic, it doesn't have GSSAPI libraries (#74709) --- .../tests/System/Net/Security/Kerberos/KerberosExecutor.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/libraries/Common/tests/System/Net/Security/Kerberos/KerberosExecutor.cs b/src/libraries/Common/tests/System/Net/Security/Kerberos/KerberosExecutor.cs index 6cb36e463da1f6..e034e82bd864a8 100644 --- a/src/libraries/Common/tests/System/Net/Security/Kerberos/KerberosExecutor.cs +++ b/src/libraries/Common/tests/System/Net/Security/Kerberos/KerberosExecutor.cs @@ -29,7 +29,9 @@ public class KerberosExecutor : IDisposable private readonly ITestOutputHelper _testOutputHelper; public static bool IsSupported { get; } = - RemoteExecutor.IsSupported && (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()); + RemoteExecutor.IsSupported && + !PlatformDetection.IsLinuxBionic && + (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS()); public const string DefaultAdminPassword = "PLACEHOLDERadmin."; public const string DefaultUserPassword = "PLACEHOLDERcorrect20"; From a5e9811b1d503af5c83b2ecac1eca6f4fbeec1b3 Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Mon, 29 Aug 2022 13:54:48 -0400 Subject: [PATCH 016/107] [wasm] Disable firefox debugger tests for rolling builds (#74753) .. because they are unstable right now. They will still be run on PRs though. Fixes https://github.com/dotnet/runtime/issues/74640 . --- eng/pipelines/runtime-extra-platforms-wasm.yml | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/eng/pipelines/runtime-extra-platforms-wasm.yml b/eng/pipelines/runtime-extra-platforms-wasm.yml index c4465c1194d88c..f1eaae46b9fe65 100644 --- a/eng/pipelines/runtime-extra-platforms-wasm.yml +++ b/eng/pipelines/runtime-extra-platforms-wasm.yml @@ -47,15 +47,15 @@ jobs: alwaysRun: true # Wasm Debugger tests - firefox - - template: /eng/pipelines/common/templates/wasm-debugger-tests.yml - parameters: - platforms: - - Browser_wasm_firefox - browser: firefox - # ff tests are unstable currently - shouldContinueOnError: true - alwaysRun: true - + # - disabled from rolling builds + #- template: /eng/pipelines/common/templates/wasm-debugger-tests.yml + #parameters: + #platforms: + #- Browser_wasm_firefox + #browser: firefox + ## ff tests are unstable currently + #shouldContinueOnError: true + #alwaysRun: true # Disabled for now #- template: /eng/pipelines/coreclr/perf-wasm-jobs.yml From 1d27c3da294df541478a78ae977d7629b17ae710 Mon Sep 17 00:00:00 2001 From: Vladimir Sadov Date: Mon, 29 Aug 2022 11:09:35 -0700 Subject: [PATCH 017/107] [NativeAOT] enable background GC on Unix (#74735) * enable for unix+arm64 * include softwarewritewatch.cpp * make the unix crst recursive * enable ww on Unix x64 * enabled card bundles * comment --- src/coreclr/nativeaot/Runtime/CMakeLists.txt | 7 ++ .../nativeaot/Runtime/amd64/WriteBarriers.S | 83 ++++++++++++++----- .../nativeaot/Runtime/arm64/WriteBarriers.S | 32 ++++--- src/coreclr/nativeaot/Runtime/gcrhenv.cpp | 4 +- .../nativeaot/Runtime/unix/PalRedhawkUnix.cpp | 17 +++- 5 files changed, 102 insertions(+), 41 deletions(-) diff --git a/src/coreclr/nativeaot/Runtime/CMakeLists.txt b/src/coreclr/nativeaot/Runtime/CMakeLists.txt index 4ccefca81f5328..2e37b1708d195e 100644 --- a/src/coreclr/nativeaot/Runtime/CMakeLists.txt +++ b/src/coreclr/nativeaot/Runtime/CMakeLists.txt @@ -50,6 +50,7 @@ set(COMMON_RUNTIME_SOURCES ${GC_DIR}/handletablecore.cpp ${GC_DIR}/handletablescan.cpp ${GC_DIR}/objecthandle.cpp + ${GC_DIR}/softwarewritewatch.cpp ) set(SERVER_GC_SOURCES @@ -206,6 +207,12 @@ include_directories(${ARCH_SOURCES_DIR}) add_definitions(-DFEATURE_BASICFREEZE) add_definitions(-DFEATURE_CONSERVATIVE_GC) + +if(CLR_CMAKE_TARGET_UNIX) + add_definitions(-DFEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP) + add_definitions(-DFEATURE_MANUALLY_MANAGED_CARD_BUNDLES) +endif() + add_definitions(-DFEATURE_CUSTOM_IMPORTS) add_definitions(-DFEATURE_DYNAMIC_CODE) add_compile_definitions($<$,$>:FEATURE_GC_STRESS>) diff --git a/src/coreclr/nativeaot/Runtime/amd64/WriteBarriers.S b/src/coreclr/nativeaot/Runtime/amd64/WriteBarriers.S index 4ec18c7d8864eb..c31a95c9bec5a3 100644 --- a/src/coreclr/nativeaot/Runtime/amd64/WriteBarriers.S +++ b/src/coreclr/nativeaot/Runtime/amd64/WriteBarriers.S @@ -84,6 +84,21 @@ LOCAL_LABEL(\BASENAME\()_UpdateShadowHeap_Done_\REFREG): // we're in a debug build and write barrier checking has been enabled). UPDATE_GC_SHADOW \BASENAME, \REFREG, rdi +#ifdef FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP + mov r11, [C_VAR(g_write_watch_table)] + cmp r11, 0x0 + je LOCAL_LABEL(\BASENAME\()_CheckCardTable_\REFREG) + + mov r10, rdi + shr r10, 0xC // SoftwareWriteWatch::AddressToTableByteIndexShift + add r10, r11 + cmp byte ptr [r10], 0x0 + jne LOCAL_LABEL(\BASENAME\()_CheckCardTable_\REFREG) + mov byte ptr [r10], 0xFF +#endif + +LOCAL_LABEL(\BASENAME\()_CheckCardTable_\REFREG): + // If the reference is to an object that's not in an ephemeral generation we have no need to track it // (since the object won't be collected or moved by an ephemeral collection). cmp \REFREG, [C_VAR(g_ephemeral_low)] @@ -95,17 +110,25 @@ LOCAL_LABEL(\BASENAME\()_UpdateShadowHeap_Done_\REFREG): // track this write. The location address is translated into an offset in the card table bitmap. We set // an entire byte in the card table since it's quicker than messing around with bitmasks and we only write // the byte if it hasn't already been done since writes are expensive and impact scaling. - shr rdi, 11 - add rdi, [C_VAR(g_card_table)] - cmp byte ptr [rdi], 0x0FF - jne LOCAL_LABEL(\BASENAME\()_UpdateCardTable_\REFREG) - -LOCAL_LABEL(\BASENAME\()_NoBarrierRequired_\REFREG): - ret + shr rdi, 0x0B + mov r10, [C_VAR(g_card_table)] + cmp byte ptr [rdi + r10], 0x0FF + je LOCAL_LABEL(\BASENAME\()_NoBarrierRequired_\REFREG) // We get here if it's necessary to update the card table. -LOCAL_LABEL(\BASENAME\()_UpdateCardTable_\REFREG): - mov byte ptr [rdi], 0x0FF + mov byte ptr [rdi + r10], 0xFF + +#ifdef FEATURE_MANUALLY_MANAGED_CARD_BUNDLES + // Shift rdi by 0x0A more to get the card bundle byte (we shifted by 0x0B already) + shr rdi, 0x0A + add rdi, [C_VAR(g_card_bundle_table)] + cmp byte ptr [rdi], 0xFF + je LOCAL_LABEL(\BASENAME\()_NoBarrierRequired_\REFREG) + + mov byte ptr [rdi], 0xFF +#endif + +LOCAL_LABEL(\BASENAME\()_NoBarrierRequired_\REFREG): ret .endm @@ -252,6 +275,21 @@ LEAF_ENTRY RhpByRefAssignRef, _TEXT // we're in a debug build and write barrier checking has been enabled). UPDATE_GC_SHADOW BASENAME, rcx, rdi +#ifdef FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP + mov r11, [C_VAR(g_write_watch_table)] + cmp r11, 0x0 + je LOCAL_LABEL(RhpByRefAssignRef_CheckCardTable) + + mov r10, rdi + shr r10, 0xC // SoftwareWriteWatch::AddressToTableByteIndexShift + add r10, r11 + cmp byte ptr [r10], 0x0 + jne LOCAL_LABEL(RhpByRefAssignRef_CheckCardTable) + mov byte ptr [r10], 0xFF +#endif + +LOCAL_LABEL(RhpByRefAssignRef_CheckCardTable): + // If the reference is to an object that's not in an ephemeral generation we have no need to track it // (since the object won't be collected or moved by an ephemeral collection). cmp rcx, [C_VAR(g_ephemeral_low)] @@ -259,25 +297,30 @@ LEAF_ENTRY RhpByRefAssignRef, _TEXT cmp rcx, [C_VAR(g_ephemeral_high)] jae LOCAL_LABEL(RhpByRefAssignRef_NotInHeap) - // move current rdi value into rcx and then increment the pointers + // move current rdi value into rcx, we need to keep rdi and eventually increment by 8 mov rcx, rdi - add rsi, 0x8 - add rdi, 0x8 // We have a location on the GC heap being updated with a reference to an ephemeral object so we must // track this write. The location address is translated into an offset in the card table bitmap. We set // an entire byte in the card table since it's quicker than messing around with bitmasks and we only write // the byte if it hasn't already been done since writes are expensive and impact scaling. - shr rcx, 11 - add rcx, [C_VAR(g_card_table)] - cmp byte ptr [rcx], 0x0FF - jne LOCAL_LABEL(RhpByRefAssignRef_UpdateCardTable) - ret + shr rcx, 0x0B + mov r10, [C_VAR(g_card_table)] + cmp byte ptr [rcx + r10], 0x0FF + je LOCAL_LABEL(RhpByRefAssignRef_NotInHeap) // We get here if it's necessary to update the card table. -LOCAL_LABEL(RhpByRefAssignRef_UpdateCardTable): - mov byte ptr [rcx], 0x0FF - ret + mov byte ptr [rcx + r10], 0xFF + +#ifdef FEATURE_MANUALLY_MANAGED_CARD_BUNDLES + // Shift rcx by 0x0A more to get the card bundle byte (we shifted by 0x0B already) + shr rcx, 0x0A + add rcx, [C_VAR(g_card_bundle_table)] + cmp byte ptr [rcx], 0xFF + je LOCAL_LABEL(RhpByRefAssignRef_NotInHeap) + + mov byte ptr [rcx], 0xFF +#endif LOCAL_LABEL(RhpByRefAssignRef_NotInHeap): // Increment the pointers before leaving diff --git a/src/coreclr/nativeaot/Runtime/arm64/WriteBarriers.S b/src/coreclr/nativeaot/Runtime/arm64/WriteBarriers.S index 4a3c3edf1e25b1..8d908d993aebf4 100644 --- a/src/coreclr/nativeaot/Runtime/arm64/WriteBarriers.S +++ b/src/coreclr/nativeaot/Runtime/arm64/WriteBarriers.S @@ -92,12 +92,11 @@ // destReg: location to be updated // refReg: objectref to be stored // trash: register nr than can be trashed - // trash2: register than can be trashed // // On exit: // destReg: trashed // - .macro INSERT_UNCHECKED_WRITE_BARRIER_CORE destReg, refReg, trash, trash2 + .macro INSERT_UNCHECKED_WRITE_BARRIER_CORE destReg, refReg, trash // Update the shadow copy of the heap with the same value just written to the same heap. (A no-op unless // we are in a debug build and write barrier checking has been enabled). @@ -129,27 +128,27 @@ // Set this objects card, if it has not already been set. PREPARE_EXTERNAL_VAR_INDIRECT g_card_table, x\trash - add \trash2, x\trash, \destReg, lsr #11 + add x17, x\trash, \destReg, lsr #11 // Check that this card has not already been written. Avoiding useless writes is a big win on // multi-proc systems since it avoids cache thrashing. - ldrb w\trash, [\trash2] + ldrb w\trash, [x17] cmp x\trash, 0xFF beq 0f mov x\trash, 0xFF - strb w\trash, [\trash2] + strb w\trash, [x17] #ifdef FEATURE_MANUALLY_MANAGED_CARD_BUNDLES // Check if we need to update the card bundle table PREPARE_EXTERNAL_VAR_INDIRECT g_card_bundle_table, x\trash - add \trash2, x\trash, \destReg, lsr #21 - ldrb w\trash, [\trash2] + add x17, x\trash, \destReg, lsr #21 + ldrb w\trash, [x17] cmp x\trash, 0xFF beq 0f mov x\trash, 0xFF - strb w\trash, [\trash2] + strb w\trash, [x17] #endif 0: @@ -160,12 +159,11 @@ // destReg: location to be updated // refReg: objectref to be stored // trash: register nr than can be trashed - // trash2: register than can be trashed // // On exit: // destReg: trashed // - .macro INSERT_CHECKED_WRITE_BARRIER_CORE destReg, refReg, trash, trash2 + .macro INSERT_CHECKED_WRITE_BARRIER_CORE destReg, refReg, trash // The "check" of this checked write barrier - is destReg // within the heap? if no, early out. @@ -180,7 +178,7 @@ ccmp \destReg, x\trash, #0x2, hs bhs 0f - INSERT_UNCHECKED_WRITE_BARRIER_CORE \destReg, \refReg, \trash, \trash2 + INSERT_UNCHECKED_WRITE_BARRIER_CORE \destReg, \refReg, \trash 0: // Exit label @@ -265,7 +263,7 @@ CmpXchgRetry: // The following barrier code takes the destination in x0 and the value in x1 so the arguments are // already correctly set up. - INSERT_CHECKED_WRITE_BARRIER_CORE x0, x1, 9, x0 + INSERT_CHECKED_WRITE_BARRIER_CORE x0, x1, 9 CmpXchgNoUpdate: // x10 still contains the original value. @@ -307,7 +305,7 @@ ExchangeRetry: // The following barrier code takes the destination in x0 and the value in x1 so the arguments are // already correctly set up. - INSERT_CHECKED_WRITE_BARRIER_CORE x0, x1, 9, x0 + INSERT_CHECKED_WRITE_BARRIER_CORE x0, x1, 9 // x10 still contains the original value. mov x0, x10 @@ -321,7 +319,7 @@ LEAF_ENTRY RhpAssignRefArm64, _TEXT ALTERNATE_ENTRY RhpAssignRefX1AVLocation stlr x15, [x14] - INSERT_UNCHECKED_WRITE_BARRIER_CORE x14, x15, 12, X14 + INSERT_UNCHECKED_WRITE_BARRIER_CORE x14, x15, 12 ret LEAF_END RhpAssignRefArm64, _TEXT @@ -343,9 +341,7 @@ LEAF_ENTRY RhpCheckedAssignRefArm64, _TEXT stlr x15, [x14] - INSERT_CHECKED_WRITE_BARRIER_CORE x14, x15, 12, X15 - - add x14, x14, #8 + INSERT_CHECKED_WRITE_BARRIER_CORE x14, x15, 12 ret LEAF_END RhpCheckedAssignRefArm64, _TEXT @@ -366,7 +362,7 @@ LEAF_ENTRY RhpByRefAssignRefArm64, _TEXT ldr x15, [x13] stlr x15, [x14] - INSERT_CHECKED_WRITE_BARRIER_CORE x14, x15, 12, X15 + INSERT_CHECKED_WRITE_BARRIER_CORE x14, x15, 12 add X13, x13, #8 add x14, x14, #8 diff --git a/src/coreclr/nativeaot/Runtime/gcrhenv.cpp b/src/coreclr/nativeaot/Runtime/gcrhenv.cpp index f3d3010ff5a0c2..b81422dc0d0d95 100644 --- a/src/coreclr/nativeaot/Runtime/gcrhenv.cpp +++ b/src/coreclr/nativeaot/Runtime/gcrhenv.cpp @@ -1018,8 +1018,8 @@ void GCToEEInterface::DiagWalkBGCSurvivors(void* gcContext) #endif // FEATURE_EVENT_TRACE } -#if defined(FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP) && (!defined(TARGET_ARM64) || !defined(TARGET_UNIX)) -#error FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP is only implemented for ARM64 and UNIX +#if defined(FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP) && !defined(TARGET_UNIX) +#error FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP is only implemented for UNIX #endif void GCToEEInterface::StompWriteBarrier(WriteBarrierParameters* args) diff --git a/src/coreclr/nativeaot/Runtime/unix/PalRedhawkUnix.cpp b/src/coreclr/nativeaot/Runtime/unix/PalRedhawkUnix.cpp index 526810177a5ed7..7ef38f6d464a06 100644 --- a/src/coreclr/nativeaot/Runtime/unix/PalRedhawkUnix.cpp +++ b/src/coreclr/nativeaot/Runtime/unix/PalRedhawkUnix.cpp @@ -869,7 +869,22 @@ extern "C" UInt32_BOOL DuplicateHandle( extern "C" UInt32_BOOL InitializeCriticalSection(CRITICAL_SECTION * lpCriticalSection) { - return pthread_mutex_init(&lpCriticalSection->mutex, NULL) == 0; + pthread_mutexattr_t mutexAttributes; + int st = pthread_mutexattr_init(&mutexAttributes); + if (st != 0) + { + return false; + } + + st = pthread_mutexattr_settype(&mutexAttributes, PTHREAD_MUTEX_RECURSIVE); + if (st == 0) + { + st = pthread_mutex_init(&lpCriticalSection->mutex, &mutexAttributes); + } + + pthread_mutexattr_destroy(&mutexAttributes); + + return (st == 0); } extern "C" UInt32_BOOL InitializeCriticalSectionEx(CRITICAL_SECTION * lpCriticalSection, uint32_t arg2, uint32_t arg3) From 012f474d2f72454ddf20ff20bafda1365a49e8f7 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Mon, 29 Aug 2022 22:04:17 +0300 Subject: [PATCH 018/107] Move distributed transaction test to OleTxTests (#74747) NonMsdtcPromoterTests.PSPENonMsdtcGetPromoterTypeMSDTC was triggering an MSDTC distributed transaction on Windows, but without the proper checks/resiliency. Moved to OleTxTests. Fixes #74170 --- .../tests/NonMsdtcPromoterTests.cs | 65 +------------------ .../tests/OleTxNonWindowsUnsupportedTests.cs | 11 +++- .../tests/OleTxTests.cs | 28 ++++++++ 3 files changed, 37 insertions(+), 67 deletions(-) diff --git a/src/libraries/System.Transactions.Local/tests/NonMsdtcPromoterTests.cs b/src/libraries/System.Transactions.Local/tests/NonMsdtcPromoterTests.cs index dc2ba01f63bcbb..6313200e46ada0 100644 --- a/src/libraries/System.Transactions.Local/tests/NonMsdtcPromoterTests.cs +++ b/src/libraries/System.Transactions.Local/tests/NonMsdtcPromoterTests.cs @@ -21,7 +21,6 @@ public class NonMsdtcPromoterTests : IDisposable private static MethodInfo s_setDistributedTransactionIdentifierMethodInfo; private static MethodInfo s_getPromotedTokenMethodInfo; private static PropertyInfo s_promoterTypePropertyInfo; - private static FieldInfo s_promoterTypeDtcFieldInfo; public NonMsdtcPromoterTests() { @@ -51,17 +50,12 @@ private static void VerifySoftDependencies() // And the PropertyInfo objects for PromoterType s_promoterTypePropertyInfo = typeof(Transaction).GetTypeInfo().GetProperty("PromoterType", typeof(Guid)); - - // And the FieldInfo for TransactionInterop.PromoterTypeDtc - s_promoterTypeDtcFieldInfo = typeof(TransactionInterop).GetTypeInfo().GetField("PromoterTypeDtc", BindingFlags.Public | BindingFlags.Static); } bool allMethodsAreThere = ((s_enlistPromotableSinglePhaseMethodInfo != null) && (s_setDistributedTransactionIdentifierMethodInfo != null) && (s_getPromotedTokenMethodInfo != null) && - (s_promoterTypePropertyInfo != null) && - (s_promoterTypeDtcFieldInfo != null) - ); + (s_promoterTypePropertyInfo != null)); Assert.True(allMethodsAreThere, "At least one of the expected new methods or properties is not implemented by the available System.Transactions."); } @@ -339,14 +333,6 @@ private static byte[] TxPromotedToken(Transaction txToGet) return (byte[])s_getPromotedTokenMethodInfo.Invoke(txToGet, null); } - private static Guid PromoterTypeDtc - { - get - { - return (Guid)s_promoterTypeDtcFieldInfo.GetValue(null); - } - } - #endregion #region NonMSDTCPromoterEnlistment @@ -1706,45 +1692,6 @@ private static void TestCase_PromoterType() TestPassed(); } - private static void TestCase_PromoterTypeMSDTC() - { - string testCaseDescription = "TestCase_PromoterTypeMSDTC"; - - Trace("**** " + testCaseDescription + " ****"); - - AutoResetEvent volCompleted = new AutoResetEvent(false); - MyEnlistment vol = null; - - try - { - using (TransactionScope ts = new TransactionScope()) - { - Assert.Equal(Guid.Empty, TxPromoterType(Transaction.Current)); - - vol = CreateVolatileEnlistment(volCompleted); - - // Force MSDTC promotion. - TransactionInterop.GetDtcTransaction(Transaction.Current); - - // TransactionInterop.PromoterTypeDtc - Assert.Equal(PromoterTypeDtc, TxPromoterType(Transaction.Current)); - - ts.Complete(); - } - } - catch (Exception ex) - { - Trace(string.Format("Caught unexpected exception {0}:{1}", ex.GetType().ToString(), ex.ToString())); - return; - } - - Assert.True(volCompleted.WaitOne(TimeSpan.FromSeconds(5))); - - Assert.True(vol.CommittedOutcome); - - TestPassed(); - } - private static void TestCase_FailPromotableSinglePhaseNotificationCalls() { string testCaseDescription = "TestCase_FailPromotableSinglePhaseNotificationCalls"; @@ -2133,16 +2080,6 @@ public void PSPENonMsdtcGetPromoterType() TestCase_PromoterType(); } - /// - /// PSPE Non-MSDTC Get PromoterType. - /// - [Fact] - public void PSPENonMsdtcGetPromoterTypeMSDTC() - { - // get_PromoterType - TestCase_PromoterTypeMSDTC(); - } - /// /// PSPE Non-MSDTC Fail PromotableSinglePhaseNotification Calls. /// diff --git a/src/libraries/System.Transactions.Local/tests/OleTxNonWindowsUnsupportedTests.cs b/src/libraries/System.Transactions.Local/tests/OleTxNonWindowsUnsupportedTests.cs index fc753cef0e2d0a..bcf50d06c31738 100644 --- a/src/libraries/System.Transactions.Local/tests/OleTxNonWindowsUnsupportedTests.cs +++ b/src/libraries/System.Transactions.Local/tests/OleTxNonWindowsUnsupportedTests.cs @@ -55,10 +55,15 @@ public void TransmitterPropagationToken() [Fact] public void GetWhereabouts() - => Assert.Throws(() => TransactionInterop.GetWhereabouts()); + => Assert.Throws(TransactionInterop.GetWhereabouts); [Fact] public void GetExportCookie() - => Assert.Throws(() => TransactionInterop.GetExportCookie( - new CommittableTransaction(), new byte[200])); + => Assert.Throws(() => + TransactionInterop.GetExportCookie(new CommittableTransaction(), new byte[200])); + + [Fact] + public void GetDtcTransaction() + => Assert.Throws(() => + TransactionInterop.GetDtcTransaction(new CommittableTransaction())); } diff --git a/src/libraries/System.Transactions.Local/tests/OleTxTests.cs b/src/libraries/System.Transactions.Local/tests/OleTxTests.cs index 6a97aed542a13f..e646c09a59326c 100644 --- a/src/libraries/System.Transactions.Local/tests/OleTxTests.cs +++ b/src/libraries/System.Transactions.Local/tests/OleTxTests.cs @@ -433,6 +433,34 @@ public void GetExportCookie() Assert.Equal(tx.TransactionInformation.DistributedIdentifier, tx2.TransactionInformation.DistributedIdentifier); }); + // Test currently skipped, #74745 + private void GetDtcTransaction() + => Test(() => + { + using var tx = new CommittableTransaction(); + + var outcomeReceived = new AutoResetEvent(false); + + var enlistment = new TestEnlistment( + Phase1Vote.Prepared, EnlistmentOutcome.Committed, outcomeReceived: outcomeReceived); + + Assert.Equal(Guid.Empty, tx.PromoterType); + + tx.EnlistVolatile(enlistment, EnlistmentOptions.None); + + // Forces promotion to MSDTC, returns an ITransaction for use only with System.EnterpriseServices. + _ = TransactionInterop.GetDtcTransaction(tx); + + Assert.Equal(TransactionStatus.Active, tx.TransactionInformation.Status); + Assert.Equal(TransactionInterop.PromoterTypeDtc, tx.PromoterType); + + tx.Commit(); + + Assert.True(outcomeReceived.WaitOne(Timeout)); + Assert.Equal(EnlistmentOutcome.Committed, enlistment.Outcome); + Retry(() => Assert.Equal(TransactionStatus.Committed, tx.TransactionInformation.Status)); + }); + private static void Test(Action action) { // Temporarily skip on 32-bit where we have an issue. From 0d3257e1a85c6e5d3743f9eafd55291acc9b469a Mon Sep 17 00:00:00 2001 From: Eirik Tsarpalis Date: Mon, 29 Aug 2022 21:29:12 +0100 Subject: [PATCH 019/107] Add missing System.Collections API docs (#74767) --- .../Immutable/ImmutableArray_1.Builder.cs | 4 + .../Collections/Immutable/ImmutableArray_1.cs | 2 + .../Immutable/ImmutableList_1.Builder.cs | 1 + .../System.Collections/System.Collections.sln | 129 +++++++++--------- .../System/Collections/Generic/SortedList.cs | 21 ++- 5 files changed, 93 insertions(+), 64 deletions(-) diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs index 0fd2dec819e5cd..205b4162a9b5bd 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.Builder.cs @@ -350,6 +350,7 @@ public void AddRange(params T[] items) /// /// Adds the specified items to the end of the array. /// + /// The type that derives from the type of item already in the array. /// The items. public void AddRange(TDerived[] items) where TDerived : T { @@ -416,6 +417,7 @@ public void AddRange(ReadOnlySpan items) /// /// Adds the specified items to the end of the array. /// + /// The type that derives from the type of item already in the array. /// The items to add at the end of the array. public void AddRange(ReadOnlySpan items) where TDerived : T { @@ -432,6 +434,7 @@ public void AddRange(ReadOnlySpan items) where TDerived : T /// /// Adds the specified items to the end of the array. /// + /// The type that derives from the type of item already in the array. /// The items to add at the end of the array. public void AddRange(ImmutableArray items) where TDerived : T { @@ -454,6 +457,7 @@ public void AddRange(Builder items) /// /// Adds the specified items to the end of the array. /// + /// The type that derives from the type of item already in the array. /// The items to add at the end of the array. public void AddRange(ImmutableArray.Builder items) where TDerived : T { diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs index 73a0b69bfb16dc..7fd48a50fd15dc 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs @@ -449,6 +449,7 @@ public ImmutableArray AddRange(T[] items, int length) /// /// Adds the specified items to the end of the array. /// + /// The type that derives from the type of item already in the array. /// The values to add. /// A new list with the elements added. public ImmutableArray AddRange(TDerived[] items) where TDerived : T @@ -493,6 +494,7 @@ public ImmutableArray AddRange(ImmutableArray items, int length) /// /// Adds the specified items to the end of the array. /// + /// The type that derives from the type of item already in the array. /// The values to add. /// A new list with the elements added. public ImmutableArray AddRange(ImmutableArray items) where TDerived : T diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs index 1b4494eb4b2f49..620a9568469baf 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs @@ -758,6 +758,7 @@ public int RemoveAll(Predicate match) /// The equality comparer to use in the search. /// If null, is used. /// + /// A value indicating whether the specified element was found and removed from the collection. public bool Remove(T item, IEqualityComparer? equalityComparer) { int index = this.IndexOf(item, 0, this.Count, equalityComparer); diff --git a/src/libraries/System.Collections/System.Collections.sln b/src/libraries/System.Collections/System.Collections.sln index 3651f1f2efa5da..45f36f8be14757 100644 --- a/src/libraries/System.Collections/System.Collections.sln +++ b/src/libraries/System.Collections/System.Collections.sln @@ -1,4 +1,8 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.4.32804.182 +MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib", "..\..\coreclr\System.Private.CoreLib\System.Private.CoreLib.csproj", "{4385739F-14A1-4F21-96E3-12EA90580575}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{38D8F258-655E-459B-B2CE-0DED144AFBF7}" @@ -27,17 +31,23 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{B958B834-96D EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution + Checked|Any CPU = Checked|Any CPU + Checked|x64 = Checked|x64 + Checked|x86 = Checked|x86 Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 - Checked|Any CPU = Checked|Any CPU - Checked|x64 = Checked|x64 - Checked|x86 = Checked|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4385739F-14A1-4F21-96E3-12EA90580575}.Checked|Any CPU.ActiveCfg = Checked|x64 + {4385739F-14A1-4F21-96E3-12EA90580575}.Checked|Any CPU.Build.0 = Checked|x64 + {4385739F-14A1-4F21-96E3-12EA90580575}.Checked|x64.ActiveCfg = Checked|x64 + {4385739F-14A1-4F21-96E3-12EA90580575}.Checked|x64.Build.0 = Checked|x64 + {4385739F-14A1-4F21-96E3-12EA90580575}.Checked|x86.ActiveCfg = Checked|x86 + {4385739F-14A1-4F21-96E3-12EA90580575}.Checked|x86.Build.0 = Checked|x86 {4385739F-14A1-4F21-96E3-12EA90580575}.Debug|Any CPU.ActiveCfg = Debug|x64 {4385739F-14A1-4F21-96E3-12EA90580575}.Debug|Any CPU.Build.0 = Debug|x64 {4385739F-14A1-4F21-96E3-12EA90580575}.Debug|x64.ActiveCfg = Debug|x64 @@ -50,12 +60,12 @@ Global {4385739F-14A1-4F21-96E3-12EA90580575}.Release|x64.Build.0 = Release|x64 {4385739F-14A1-4F21-96E3-12EA90580575}.Release|x86.ActiveCfg = Release|x86 {4385739F-14A1-4F21-96E3-12EA90580575}.Release|x86.Build.0 = Release|x86 - {4385739F-14A1-4F21-96E3-12EA90580575}.Checked|Any CPU.ActiveCfg = Checked|x64 - {4385739F-14A1-4F21-96E3-12EA90580575}.Checked|Any CPU.Build.0 = Checked|x64 - {4385739F-14A1-4F21-96E3-12EA90580575}.Checked|x64.ActiveCfg = Checked|x64 - {4385739F-14A1-4F21-96E3-12EA90580575}.Checked|x64.Build.0 = Checked|x64 - {4385739F-14A1-4F21-96E3-12EA90580575}.Checked|x86.ActiveCfg = Checked|x86 - {4385739F-14A1-4F21-96E3-12EA90580575}.Checked|x86.Build.0 = Checked|x86 + {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Checked|Any CPU.ActiveCfg = Debug|Any CPU + {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Checked|Any CPU.Build.0 = Debug|Any CPU + {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Checked|x64.ActiveCfg = Debug|Any CPU + {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Checked|x64.Build.0 = Debug|Any CPU + {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Checked|x86.ActiveCfg = Debug|Any CPU + {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Checked|x86.Build.0 = Debug|Any CPU {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Debug|Any CPU.Build.0 = Debug|Any CPU {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -68,12 +78,12 @@ Global {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Release|x64.Build.0 = Release|Any CPU {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Release|x86.ActiveCfg = Release|Any CPU {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Release|x86.Build.0 = Release|Any CPU - {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Checked|Any CPU.ActiveCfg = Debug|Any CPU - {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Checked|Any CPU.Build.0 = Debug|Any CPU - {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Checked|x64.ActiveCfg = Debug|Any CPU - {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Checked|x64.Build.0 = Debug|Any CPU - {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Checked|x86.ActiveCfg = Debug|Any CPU - {38D8F258-655E-459B-B2CE-0DED144AFBF7}.Checked|x86.Build.0 = Debug|Any CPU + {77E9C47D-4AC4-4402-8613-40DF427174BD}.Checked|Any CPU.ActiveCfg = Debug|Any CPU + {77E9C47D-4AC4-4402-8613-40DF427174BD}.Checked|Any CPU.Build.0 = Debug|Any CPU + {77E9C47D-4AC4-4402-8613-40DF427174BD}.Checked|x64.ActiveCfg = Debug|Any CPU + {77E9C47D-4AC4-4402-8613-40DF427174BD}.Checked|x64.Build.0 = Debug|Any CPU + {77E9C47D-4AC4-4402-8613-40DF427174BD}.Checked|x86.ActiveCfg = Debug|Any CPU + {77E9C47D-4AC4-4402-8613-40DF427174BD}.Checked|x86.Build.0 = Debug|Any CPU {77E9C47D-4AC4-4402-8613-40DF427174BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {77E9C47D-4AC4-4402-8613-40DF427174BD}.Debug|Any CPU.Build.0 = Debug|Any CPU {77E9C47D-4AC4-4402-8613-40DF427174BD}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -86,12 +96,12 @@ Global {77E9C47D-4AC4-4402-8613-40DF427174BD}.Release|x64.Build.0 = Release|Any CPU {77E9C47D-4AC4-4402-8613-40DF427174BD}.Release|x86.ActiveCfg = Release|Any CPU {77E9C47D-4AC4-4402-8613-40DF427174BD}.Release|x86.Build.0 = Release|Any CPU - {77E9C47D-4AC4-4402-8613-40DF427174BD}.Checked|Any CPU.ActiveCfg = Debug|Any CPU - {77E9C47D-4AC4-4402-8613-40DF427174BD}.Checked|Any CPU.Build.0 = Debug|Any CPU - {77E9C47D-4AC4-4402-8613-40DF427174BD}.Checked|x64.ActiveCfg = Debug|Any CPU - {77E9C47D-4AC4-4402-8613-40DF427174BD}.Checked|x64.Build.0 = Debug|Any CPU - {77E9C47D-4AC4-4402-8613-40DF427174BD}.Checked|x86.ActiveCfg = Debug|Any CPU - {77E9C47D-4AC4-4402-8613-40DF427174BD}.Checked|x86.Build.0 = Debug|Any CPU + {DF501250-4105-4F79-A508-90B3A13A975A}.Checked|Any CPU.ActiveCfg = Debug|Any CPU + {DF501250-4105-4F79-A508-90B3A13A975A}.Checked|Any CPU.Build.0 = Debug|Any CPU + {DF501250-4105-4F79-A508-90B3A13A975A}.Checked|x64.ActiveCfg = Debug|Any CPU + {DF501250-4105-4F79-A508-90B3A13A975A}.Checked|x64.Build.0 = Debug|Any CPU + {DF501250-4105-4F79-A508-90B3A13A975A}.Checked|x86.ActiveCfg = Debug|Any CPU + {DF501250-4105-4F79-A508-90B3A13A975A}.Checked|x86.Build.0 = Debug|Any CPU {DF501250-4105-4F79-A508-90B3A13A975A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DF501250-4105-4F79-A508-90B3A13A975A}.Debug|Any CPU.Build.0 = Debug|Any CPU {DF501250-4105-4F79-A508-90B3A13A975A}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -104,12 +114,12 @@ Global {DF501250-4105-4F79-A508-90B3A13A975A}.Release|x64.Build.0 = Release|Any CPU {DF501250-4105-4F79-A508-90B3A13A975A}.Release|x86.ActiveCfg = Release|Any CPU {DF501250-4105-4F79-A508-90B3A13A975A}.Release|x86.Build.0 = Release|Any CPU - {DF501250-4105-4F79-A508-90B3A13A975A}.Checked|Any CPU.ActiveCfg = Debug|Any CPU - {DF501250-4105-4F79-A508-90B3A13A975A}.Checked|Any CPU.Build.0 = Debug|Any CPU - {DF501250-4105-4F79-A508-90B3A13A975A}.Checked|x64.ActiveCfg = Debug|Any CPU - {DF501250-4105-4F79-A508-90B3A13A975A}.Checked|x64.Build.0 = Debug|Any CPU - {DF501250-4105-4F79-A508-90B3A13A975A}.Checked|x86.ActiveCfg = Debug|Any CPU - {DF501250-4105-4F79-A508-90B3A13A975A}.Checked|x86.Build.0 = Debug|Any CPU + {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Checked|Any CPU.ActiveCfg = Debug|Any CPU + {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Checked|Any CPU.Build.0 = Debug|Any CPU + {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Checked|x64.ActiveCfg = Debug|Any CPU + {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Checked|x64.Build.0 = Debug|Any CPU + {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Checked|x86.ActiveCfg = Debug|Any CPU + {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Checked|x86.Build.0 = Debug|Any CPU {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Debug|Any CPU.Build.0 = Debug|Any CPU {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -122,12 +132,12 @@ Global {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Release|x64.Build.0 = Release|Any CPU {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Release|x86.ActiveCfg = Release|Any CPU {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Release|x86.Build.0 = Release|Any CPU - {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Checked|Any CPU.ActiveCfg = Debug|Any CPU - {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Checked|Any CPU.Build.0 = Debug|Any CPU - {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Checked|x64.ActiveCfg = Debug|Any CPU - {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Checked|x64.Build.0 = Debug|Any CPU - {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Checked|x86.ActiveCfg = Debug|Any CPU - {BB54ED9D-FF71-4D91-B7C0-984AB0976798}.Checked|x86.Build.0 = Debug|Any CPU + {F2E57833-4968-430D-8149-733DE03A7314}.Checked|Any CPU.ActiveCfg = Debug|Any CPU + {F2E57833-4968-430D-8149-733DE03A7314}.Checked|Any CPU.Build.0 = Debug|Any CPU + {F2E57833-4968-430D-8149-733DE03A7314}.Checked|x64.ActiveCfg = Debug|Any CPU + {F2E57833-4968-430D-8149-733DE03A7314}.Checked|x64.Build.0 = Debug|Any CPU + {F2E57833-4968-430D-8149-733DE03A7314}.Checked|x86.ActiveCfg = Debug|Any CPU + {F2E57833-4968-430D-8149-733DE03A7314}.Checked|x86.Build.0 = Debug|Any CPU {F2E57833-4968-430D-8149-733DE03A7314}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F2E57833-4968-430D-8149-733DE03A7314}.Debug|Any CPU.Build.0 = Debug|Any CPU {F2E57833-4968-430D-8149-733DE03A7314}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -140,12 +150,12 @@ Global {F2E57833-4968-430D-8149-733DE03A7314}.Release|x64.Build.0 = Release|Any CPU {F2E57833-4968-430D-8149-733DE03A7314}.Release|x86.ActiveCfg = Release|Any CPU {F2E57833-4968-430D-8149-733DE03A7314}.Release|x86.Build.0 = Release|Any CPU - {F2E57833-4968-430D-8149-733DE03A7314}.Checked|Any CPU.ActiveCfg = Debug|Any CPU - {F2E57833-4968-430D-8149-733DE03A7314}.Checked|Any CPU.Build.0 = Debug|Any CPU - {F2E57833-4968-430D-8149-733DE03A7314}.Checked|x64.ActiveCfg = Debug|Any CPU - {F2E57833-4968-430D-8149-733DE03A7314}.Checked|x64.Build.0 = Debug|Any CPU - {F2E57833-4968-430D-8149-733DE03A7314}.Checked|x86.ActiveCfg = Debug|Any CPU - {F2E57833-4968-430D-8149-733DE03A7314}.Checked|x86.Build.0 = Debug|Any CPU + {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Checked|Any CPU.ActiveCfg = Debug|Any CPU + {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Checked|Any CPU.Build.0 = Debug|Any CPU + {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Checked|x64.ActiveCfg = Debug|Any CPU + {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Checked|x64.Build.0 = Debug|Any CPU + {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Checked|x86.ActiveCfg = Debug|Any CPU + {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Checked|x86.Build.0 = Debug|Any CPU {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Debug|Any CPU.Build.0 = Debug|Any CPU {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -158,12 +168,12 @@ Global {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Release|x64.Build.0 = Release|Any CPU {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Release|x86.ActiveCfg = Release|Any CPU {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Release|x86.Build.0 = Release|Any CPU - {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Checked|Any CPU.ActiveCfg = Debug|Any CPU - {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Checked|Any CPU.Build.0 = Debug|Any CPU - {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Checked|x64.ActiveCfg = Debug|Any CPU - {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Checked|x64.Build.0 = Debug|Any CPU - {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Checked|x86.ActiveCfg = Debug|Any CPU - {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A}.Checked|x86.Build.0 = Debug|Any CPU + {00398A78-1620-4996-9922-C82D1AF84714}.Checked|Any CPU.ActiveCfg = Debug|Any CPU + {00398A78-1620-4996-9922-C82D1AF84714}.Checked|Any CPU.Build.0 = Debug|Any CPU + {00398A78-1620-4996-9922-C82D1AF84714}.Checked|x64.ActiveCfg = Debug|Any CPU + {00398A78-1620-4996-9922-C82D1AF84714}.Checked|x64.Build.0 = Debug|Any CPU + {00398A78-1620-4996-9922-C82D1AF84714}.Checked|x86.ActiveCfg = Debug|Any CPU + {00398A78-1620-4996-9922-C82D1AF84714}.Checked|x86.Build.0 = Debug|Any CPU {00398A78-1620-4996-9922-C82D1AF84714}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {00398A78-1620-4996-9922-C82D1AF84714}.Debug|Any CPU.Build.0 = Debug|Any CPU {00398A78-1620-4996-9922-C82D1AF84714}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -176,12 +186,12 @@ Global {00398A78-1620-4996-9922-C82D1AF84714}.Release|x64.Build.0 = Release|Any CPU {00398A78-1620-4996-9922-C82D1AF84714}.Release|x86.ActiveCfg = Release|Any CPU {00398A78-1620-4996-9922-C82D1AF84714}.Release|x86.Build.0 = Release|Any CPU - {00398A78-1620-4996-9922-C82D1AF84714}.Checked|Any CPU.ActiveCfg = Debug|Any CPU - {00398A78-1620-4996-9922-C82D1AF84714}.Checked|Any CPU.Build.0 = Debug|Any CPU - {00398A78-1620-4996-9922-C82D1AF84714}.Checked|x64.ActiveCfg = Debug|Any CPU - {00398A78-1620-4996-9922-C82D1AF84714}.Checked|x64.Build.0 = Debug|Any CPU - {00398A78-1620-4996-9922-C82D1AF84714}.Checked|x86.ActiveCfg = Debug|Any CPU - {00398A78-1620-4996-9922-C82D1AF84714}.Checked|x86.Build.0 = Debug|Any CPU + {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Checked|Any CPU.ActiveCfg = Debug|Any CPU + {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Checked|Any CPU.Build.0 = Debug|Any CPU + {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Checked|x64.ActiveCfg = Debug|Any CPU + {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Checked|x64.Build.0 = Debug|Any CPU + {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Checked|x86.ActiveCfg = Debug|Any CPU + {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Checked|x86.Build.0 = Debug|Any CPU {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Debug|Any CPU.Build.0 = Debug|Any CPU {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -194,28 +204,25 @@ Global {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Release|x64.Build.0 = Release|Any CPU {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Release|x86.ActiveCfg = Release|Any CPU {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Release|x86.Build.0 = Release|Any CPU - {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Checked|Any CPU.ActiveCfg = Debug|Any CPU - {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Checked|Any CPU.Build.0 = Debug|Any CPU - {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Checked|x64.ActiveCfg = Debug|Any CPU - {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Checked|x64.Build.0 = Debug|Any CPU - {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Checked|x86.ActiveCfg = Debug|Any CPU - {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA}.Checked|x86.Build.0 = Debug|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {4385739F-14A1-4F21-96E3-12EA90580575} = {C848C534-DD16-4A69-81FF-894456E4B099} - {DF501250-4105-4F79-A508-90B3A13A975A} = {C848C534-DD16-4A69-81FF-894456E4B099} {38D8F258-655E-459B-B2CE-0DED144AFBF7} = {6CD2C5E3-B5BA-4219-B8EF-9B5D486BF805} - {BB54ED9D-FF71-4D91-B7C0-984AB0976798} = {6CD2C5E3-B5BA-4219-B8EF-9B5D486BF805} {77E9C47D-4AC4-4402-8613-40DF427174BD} = {06AE90FB-F007-4E70-BCD2-5CAD106A7C97} - {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA} = {06AE90FB-F007-4E70-BCD2-5CAD106A7C97} + {DF501250-4105-4F79-A508-90B3A13A975A} = {C848C534-DD16-4A69-81FF-894456E4B099} + {BB54ED9D-FF71-4D91-B7C0-984AB0976798} = {6CD2C5E3-B5BA-4219-B8EF-9B5D486BF805} {F2E57833-4968-430D-8149-733DE03A7314} = {B958B834-96D2-4B18-AA42-22B312BE9925} {389B3CD7-FF7C-4004-A6BA-29B39B4BDF3A} = {B958B834-96D2-4B18-AA42-22B312BE9925} {00398A78-1620-4996-9922-C82D1AF84714} = {B958B834-96D2-4B18-AA42-22B312BE9925} + {EE21C87C-5515-45E1-9F94-F11BE4CEE2CA} = {06AE90FB-F007-4E70-BCD2-5CAD106A7C97} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {FDD40D53-AF3E-4A20-BE17-7555EB5494F9} EndGlobalSection + GlobalSection(SharedMSBuildProjectFiles) = preSolution + ..\System.Private.CoreLib\src\System.Private.CoreLib.Shared.projitems*{4385739f-14a1-4f21-96e3-12ea90580575}*SharedItemsImports = 5 + EndGlobalSection EndGlobal diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs index 358858636985d9..3560806d4e4153 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedList.cs @@ -516,7 +516,12 @@ private void EnsureCapacity(int min) Capacity = newCapacity; } - // Returns the value of the entry at the given index. + /// + /// Gets the value corresponding to the specified index. + /// + /// The zero-based index of the value within the entire . + /// The value corresponding to the specified index. + /// The specified index was out of range. public TValue GetValueAtIndex(int index) { if (index < 0 || index >= _size) @@ -524,7 +529,12 @@ public TValue GetValueAtIndex(int index) return values[index]; } - // Sets the value of the entry at the given index. + /// + /// Updates the value corresponding to the specified index. + /// + /// The zero-based index of the value within the entire . + /// The value with which to replace the entry at the specified index. + /// The specified index was out of range. public void SetValueAtIndex(int index, TValue value) { if (index < 0 || index >= _size) @@ -553,7 +563,12 @@ IEnumerator IEnumerable.GetEnumerator() return new Enumerator(this, Enumerator.KeyValuePair); } - // Returns the key of the entry at the given index. + /// + /// Gets the key corresponding to the specified index. + /// + /// The zero-based index of the key within the entire . + /// The key corresponding to the specified index. + /// The specified index is out of range. public TKey GetKeyAtIndex(int index) { if (index < 0 || index >= _size) From ca92d88c3065c24ba8c9221da177a1a94b321b53 Mon Sep 17 00:00:00 2001 From: Eirik Tsarpalis Date: Mon, 29 Aug 2022 21:29:56 +0100 Subject: [PATCH 020/107] Add missing System.Net.Http.Json API docs (#74770) * Add missing System.Net.Http.Json API docs * Update src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> * Update src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> * Update src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> * Update src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> * Update src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> * Update src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> * Update src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> * Update src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> * Update src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> * Update src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> * Update src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> * Update src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> Co-authored-by: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> --- .../Json/HttpClientJsonExtensions.Delete.cs | 116 ++++++++++++++++++ 1 file changed, 116 insertions(+) diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs index a62364e677325c..5df4010442347f 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.Delete.cs @@ -15,6 +15,16 @@ namespace System.Net.Http.Json /// public static partial class HttpClientJsonExtensions { + /// + /// Sends a DELETE request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. + /// + /// The client used to send the request. + /// The Uri the request is sent to. + /// The type of the object to deserialize to and return. + /// Options to control the behavior during serialization. The default options are those specified by . + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// The task object representing the asynchronous operation. + /// The is . [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task DeleteFromJsonAsync(this HttpClient client, [StringSyntax("Uri")] string? requestUri, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken = default) @@ -28,6 +38,16 @@ public static partial class HttpClientJsonExtensions return DeleteFromJsonAsyncCore(taskResponse, type, options, cancellationToken); } + /// + /// Sends a DELETE request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. + /// + /// The client used to send the request. + /// The Uri the request is sent to. + /// The type of the object to deserialize to and return. + /// Options to control the behavior during serialization. The default options are those specified by . + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// The task object representing the asynchronous operation. + /// The is . [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task DeleteFromJsonAsync(this HttpClient client, Uri? requestUri, Type type, JsonSerializerOptions? options, CancellationToken cancellationToken = default) @@ -41,6 +61,16 @@ public static partial class HttpClientJsonExtensions return DeleteFromJsonAsyncCore(taskResponse, type, options, cancellationToken); } + /// + /// Sends a DELETE request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. + /// + /// The target type to deserialize to. + /// The client used to send the request. + /// The Uri the request is sent to. + /// Options to control the behavior during serialization. The default options are those specified by . + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// The task object representing the asynchronous operation. + /// The is . [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task DeleteFromJsonAsync(this HttpClient client, [StringSyntax("Uri")] string? requestUri, JsonSerializerOptions? options, CancellationToken cancellationToken = default) @@ -54,6 +84,16 @@ public static partial class HttpClientJsonExtensions return DeleteFromJsonAsyncCore(taskResponse, options, cancellationToken); } + /// + /// Sends a DELETE request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. + /// + /// The target type to deserialize to. + /// The client used to send the request. + /// The Uri the request is sent to. + /// Options to control the behavior during serialization. The default options are those specified by . + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// The task object representing the asynchronous operation. + /// The is . [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task DeleteFromJsonAsync(this HttpClient client, Uri? requestUri, JsonSerializerOptions? options, CancellationToken cancellationToken = default) @@ -67,6 +107,16 @@ public static partial class HttpClientJsonExtensions return DeleteFromJsonAsyncCore(taskResponse, options, cancellationToken); } + /// + /// Sends a DELETE request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. + /// + /// The client used to send the request. + /// The Uri the request is sent to. + /// The type of the object to deserialize to and return. + /// Source generated JsonSerializerContext used to control the deserialization behavior. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// The task object representing the asynchronous operation. + /// The is . public static Task DeleteFromJsonAsync(this HttpClient client, [StringSyntax("Uri")] string? requestUri, Type type, JsonSerializerContext context, CancellationToken cancellationToken = default) { if (client is null) @@ -78,6 +128,16 @@ public static partial class HttpClientJsonExtensions return DeleteFromJsonAsyncCore(taskResponse, type, context, cancellationToken); } + /// + /// Sends a DELETE request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. + /// + /// The client used to send the request. + /// The Uri the request is sent to. + /// The type of the object to deserialize to and return. + /// Source generated JsonSerializerContext used to control the deserialization behavior. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// The task object representing the asynchronous operation. + /// The is . public static Task DeleteFromJsonAsync(this HttpClient client, Uri? requestUri, Type type, JsonSerializerContext context, CancellationToken cancellationToken = default) { if (client is null) @@ -89,6 +149,16 @@ public static partial class HttpClientJsonExtensions return DeleteFromJsonAsyncCore(taskResponse, type, context, cancellationToken); } + /// + /// Sends a DELETE request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. + /// + /// The target type to deserialize to. + /// The client used to send the request. + /// The Uri the request is sent to. + /// Source generated JsonTypeInfo to control the behavior during deserialization. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// The task object representing the asynchronous operation. + /// The is . public static Task DeleteFromJsonAsync(this HttpClient client, [StringSyntax("Uri")] string? requestUri, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { if (client is null) @@ -100,6 +170,16 @@ public static partial class HttpClientJsonExtensions return DeleteFromJsonAsyncCore(taskResponse, jsonTypeInfo, cancellationToken); } + /// + /// Sends a DELETE request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. + /// + /// The target type to deserialize to. + /// The client used to send the request. + /// The Uri the request is sent to. + /// Source generated JsonTypeInfo to control the behavior during deserialization. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// The task object representing the asynchronous operation. + /// The is . public static Task DeleteFromJsonAsync(this HttpClient client, Uri? requestUri, JsonTypeInfo jsonTypeInfo, CancellationToken cancellationToken = default) { if (client is null) @@ -111,21 +191,57 @@ public static partial class HttpClientJsonExtensions return DeleteFromJsonAsyncCore(taskResponse, jsonTypeInfo, cancellationToken); } + /// + /// Sends a DELETE request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. + /// + /// The client used to send the request. + /// The Uri the request is sent to. + /// The type of the object to deserialize to and return. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// The task object representing the asynchronous operation. + /// The is . [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task DeleteFromJsonAsync(this HttpClient client, [StringSyntax("Uri")] string? requestUri, Type type, CancellationToken cancellationToken = default) => client.DeleteFromJsonAsync(requestUri, type, options: null, cancellationToken); + /// + /// Sends a DELETE request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. + /// + /// The client used to send the request. + /// The Uri the request is sent to. + /// The type of the object to deserialize to and return. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// The task object representing the asynchronous operation. + /// The is . [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task DeleteFromJsonAsync(this HttpClient client, Uri? requestUri, Type type, CancellationToken cancellationToken = default) => client.DeleteFromJsonAsync(requestUri, type, options: null, cancellationToken); + /// + /// Sends a DELETE request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. + /// + /// The target type to deserialize to. + /// The client used to send the request. + /// The Uri the request is sent to. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// The task object representing the asynchronous operation. + /// The is . [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task DeleteFromJsonAsync(this HttpClient client, [StringSyntax("Uri")] string? requestUri, CancellationToken cancellationToken = default) => client.DeleteFromJsonAsync(requestUri, options: null, cancellationToken); + /// + /// Sends a DELETE request to the specified Uri and returns the value that results from deserializing the response body as JSON in an asynchronous operation. + /// + /// The target type to deserialize to. + /// The client used to send the request. + /// The Uri the request is sent to. + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// The task object representing the asynchronous operation. + /// The is . [RequiresUnreferencedCode(HttpContentJsonExtensions.SerializationUnreferencedCodeMessage)] [RequiresDynamicCode(HttpContentJsonExtensions.SerializationDynamicCodeMessage)] public static Task DeleteFromJsonAsync(this HttpClient client, Uri? requestUri, CancellationToken cancellationToken = default) From ba3ee97687cd0d0c441cd154955e40eb9515ef94 Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Mon, 29 Aug 2022 17:34:35 -0400 Subject: [PATCH 021/107] [wasm] Move `src/tests/BuildWasmApps/*` to `src/mono/wasm` (#74698) - This will help simplifying the path subsets in `eng/pipelines/common/evaluate-default-paths.yml`, which would then help to avoid a lot of unrelated non-wasm builds on PRs --- .github/CODEOWNERS | 3 ++- docs/workflow/testing/testing-workloads.md | 2 +- eng/pipelines/common/evaluate-default-paths.yml | 10 +++++----- .../coreclr/perf-wasm-prepare-artifacts-steps.yml | 2 +- src/libraries/tests.proj | 4 ++-- src/mono/wasm/Makefile | 4 ++-- .../Wasm.Build.Tests/BlazorWasmBuildPublishTests.cs | 0 .../wasm}/Wasm.Build.Tests/BlazorWasmTests.cs | 0 .../wasm}/Wasm.Build.Tests/BrowserRunner.cs | 0 .../wasm}/Wasm.Build.Tests/BuildAndRunAttribute.cs | 0 .../wasm}/Wasm.Build.Tests/BuildEnvironment.cs | 0 .../wasm}/Wasm.Build.Tests/BuildPublishTests.cs | 0 .../wasm}/Wasm.Build.Tests/BuildTestBase.cs | 0 .../wasm}/Wasm.Build.Tests/CleanTests.cs | 0 .../wasm}/Wasm.Build.Tests/CommandResult.cs | 0 .../wasm}/Wasm.Build.Tests/ConfigSrcTests.cs | 0 .../wasm/Wasm.Build.Tests/Directory.Build.props | 10 ++++++++++ .../wasm/Wasm.Build.Tests}/Directory.Build.targets | 2 +- .../wasm}/Wasm.Build.Tests/DotNetCommand.cs | 0 .../wasm}/Wasm.Build.Tests/EnvironmentVariables.cs | 0 .../wasm}/Wasm.Build.Tests/HelperExtensions.cs | 0 .../Wasm.Build.Tests/InvariantGlobalizationTests.cs | 0 .../wasm}/Wasm.Build.Tests/MainWithArgsTests.cs | 0 .../wasm}/Wasm.Build.Tests/NativeBuildTests.cs | 0 .../wasm}/Wasm.Build.Tests/NativeLibraryTests.cs | 0 .../NativeRebuildTests/FlagsChangeRebuildTest.cs | 0 .../NativeRebuildTests/NativeRebuildTestsBase.cs | 0 .../NativeRebuildTests/NoopNativeRebuildTest.cs | 0 .../ReferenceNewAssemblyRebuildTest.cs | 0 .../SimpleSourceChangeRebuildTest.cs | 0 .../Wasm.Build.Tests/PInvokeTableGeneratorTests.cs | 0 .../wasm}/Wasm.Build.Tests/ProcessExtensions.cs | 0 .../wasm}/Wasm.Build.Tests/README.md | 2 +- .../wasm}/Wasm.Build.Tests/RebuildTests.cs | 0 .../wasm}/Wasm.Build.Tests/RunCommand.cs | 0 .../wasm}/Wasm.Build.Tests/RunHost.cs | 0 .../Wasm.Build.Tests/SatelliteAssembliesTests.cs | 0 .../SharedBuildPerTestClassFixture.cs | 0 .../wasm}/Wasm.Build.Tests/ToolCommand.cs | 0 .../wasm}/Wasm.Build.Tests/Utils.cs | 0 .../wasm}/Wasm.Build.Tests/Wasm.Build.Tests.csproj | 0 .../wasm}/Wasm.Build.Tests/WasmBuildAppTest.cs | 0 .../Wasm.Build.Tests/WasmNativeDefaultsTests.cs | 0 .../Wasm.Build.Tests/WasmRunOutOfAppBundleTests.cs | 0 .../wasm}/Wasm.Build.Tests/WasmSIMDTests.cs | 0 .../wasm}/Wasm.Build.Tests/WasmTemplateTests.cs | 0 .../wasm}/Wasm.Build.Tests/WorkloadTests.cs | 0 .../data/Blazor.Directory.Build.props | 0 .../data/Blazor.Directory.Build.targets | 0 .../data/Blazor.Local.Directory.Build.props | 0 .../data/Blazor.Local.Directory.Build.targets | 0 .../data/Local.Directory.Build.props | 0 .../data/Local.Directory.Build.targets | 0 .../Wasm.Build.Tests/data/RunScriptTemplate.cmd | 0 .../Wasm.Build.Tests/data/RunScriptTemplate.sh | 0 .../data/Workloads.Directory.Build.props | 0 .../data/Workloads.Directory.Build.targets | 0 .../wasm}/Wasm.Build.Tests/data/nuget7.config | 0 .../DebuggerTestSuite/DebuggerTestSuite.csproj | 2 +- src/mono/wasm/debugger/README.md | 5 +++++ .../Wasm.Debugger.Tests/Directory.Build.props | 7 +++++++ .../Wasm.Debugger.Tests/Directory.Build.targets | 9 +++++++++ .../Wasm.Debugger.Tests/Wasm.Debugger.Tests.csproj | 2 +- .../Wasm.Debugger.Tests/data/RunScriptTemplate.cmd | 0 .../Wasm.Debugger.Tests/data/RunScriptTemplate.sh | 0 src/mono/wasm/runtime/workers/README.md | 2 +- src/mono/wasm/sln/WasmBuild.sln | 2 +- .../wasm}/testassets/AppUsingNativeLib/Program.cs | 0 .../testassets/AppUsingNativeLib/native-lib.cpp | 0 .../wasm}/testassets/AppUsingNativeLib/native-lib.h | 0 .../wasm}/testassets/AppUsingSkiaSharp/Program.cs | 0 .../wasm}/testassets/Blazor_net50/App.razor | 0 .../testassets/Blazor_net50/Blazor_net50.csproj | 0 .../testassets/Blazor_net50/Pages/Counter.razor | 0 .../testassets/Blazor_net50/Pages/FetchData.razor | 0 .../wasm}/testassets/Blazor_net50/Pages/Index.razor | 0 .../wasm}/testassets/Blazor_net50/Program.cs | 0 .../testassets/Blazor_net50/Shared/MainLayout.razor | 0 .../Blazor_net50/Shared/MainLayout.razor.css | 0 .../testassets/Blazor_net50/Shared/NavMenu.razor | 0 .../Blazor_net50/Shared/NavMenu.razor.css | 0 .../Blazor_net50/Shared/SurveyPrompt.razor | 0 .../wasm}/testassets/Blazor_net50/_Imports.razor | 0 .../LibraryWithResources/Class1.cs | 0 .../LibraryWithResources.csproj | 0 .../LibraryWithResources/resx/words.es-ES.resx | 0 .../LibraryWithResources/resx/words.ja-JP.resx | 0 .../LibraryWithResources/resx/words.resx | 0 .../SatelliteAssemblyInMain/resx/words.es-ES.resx | 0 .../SatelliteAssemblyInMain/resx/words.ja-JP.resx | 0 .../SatelliteAssemblyInMain/resx/words.resx | 0 .../BuildWasmApps => mono/wasm}/testassets/mono.png | Bin .../wasm}/testassets/native-libs/native-lib.o | Bin .../wasm}/testassets/native-libs/simple.c | 0 .../wasm}/testassets/native-libs/variadic.c | 0 .../wasm}/testassets/native-libs/variadic.o | Bin .../wasm}/testassets/resx/words.es-ES.resx | 0 .../wasm}/testassets/resx/words.ja-JP.resx | 0 .../wasm}/testassets/resx/words.resx | 0 src/tests/BuildWasmApps/Directory.Build.props | 3 --- .../Wasm.Build.Tests/Directory.Build.props | 8 -------- src/tests/Common/dirs.proj | 1 - 102 files changed, 50 insertions(+), 30 deletions(-) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/BlazorWasmBuildPublishTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/BlazorWasmTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/BrowserRunner.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/BuildAndRunAttribute.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/BuildEnvironment.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/BuildPublishTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/BuildTestBase.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/CleanTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/CommandResult.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/ConfigSrcTests.cs (100%) create mode 100644 src/mono/wasm/Wasm.Build.Tests/Directory.Build.props rename src/{tests/BuildWasmApps => mono/wasm/Wasm.Build.Tests}/Directory.Build.targets (82%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/DotNetCommand.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/EnvironmentVariables.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/HelperExtensions.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/InvariantGlobalizationTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/MainWithArgsTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/NativeBuildTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/NativeLibraryTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/NativeRebuildTests/FlagsChangeRebuildTest.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/NativeRebuildTests/NativeRebuildTestsBase.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/NativeRebuildTests/NoopNativeRebuildTest.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/NativeRebuildTests/ReferenceNewAssemblyRebuildTest.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/NativeRebuildTests/SimpleSourceChangeRebuildTest.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/PInvokeTableGeneratorTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/ProcessExtensions.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/README.md (92%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/RebuildTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/RunCommand.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/RunHost.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/SatelliteAssembliesTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/SharedBuildPerTestClassFixture.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/ToolCommand.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/Utils.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/Wasm.Build.Tests.csproj (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/WasmBuildAppTest.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/WasmNativeDefaultsTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/WasmRunOutOfAppBundleTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/WasmSIMDTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/WasmTemplateTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/WorkloadTests.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/data/Blazor.Directory.Build.props (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/data/Blazor.Directory.Build.targets (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/data/Blazor.Local.Directory.Build.props (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/data/Blazor.Local.Directory.Build.targets (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/data/Local.Directory.Build.props (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/data/Local.Directory.Build.targets (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/data/RunScriptTemplate.cmd (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/data/RunScriptTemplate.sh (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/data/Workloads.Directory.Build.props (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/data/Workloads.Directory.Build.targets (100%) rename src/{tests/BuildWasmApps => mono/wasm}/Wasm.Build.Tests/data/nuget7.config (100%) create mode 100644 src/mono/wasm/debugger/Wasm.Debugger.Tests/Directory.Build.props create mode 100644 src/mono/wasm/debugger/Wasm.Debugger.Tests/Directory.Build.targets rename src/{tests/BuildWasmApps => mono/wasm/debugger}/Wasm.Debugger.Tests/Wasm.Debugger.Tests.csproj (97%) rename src/{tests/BuildWasmApps => mono/wasm/debugger}/Wasm.Debugger.Tests/data/RunScriptTemplate.cmd (100%) rename src/{tests/BuildWasmApps => mono/wasm/debugger}/Wasm.Debugger.Tests/data/RunScriptTemplate.sh (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/AppUsingNativeLib/Program.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/AppUsingNativeLib/native-lib.cpp (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/AppUsingNativeLib/native-lib.h (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/AppUsingSkiaSharp/Program.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/Blazor_net50/App.razor (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/Blazor_net50/Blazor_net50.csproj (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/Blazor_net50/Pages/Counter.razor (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/Blazor_net50/Pages/FetchData.razor (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/Blazor_net50/Pages/Index.razor (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/Blazor_net50/Program.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/Blazor_net50/Shared/MainLayout.razor (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/Blazor_net50/Shared/MainLayout.razor.css (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/Blazor_net50/Shared/NavMenu.razor (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/Blazor_net50/Shared/NavMenu.razor.css (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/Blazor_net50/Shared/SurveyPrompt.razor (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/Blazor_net50/_Imports.razor (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/SatelliteAssemblyFromProjectRef/LibraryWithResources/Class1.cs (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/SatelliteAssemblyFromProjectRef/LibraryWithResources/LibraryWithResources.csproj (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/SatelliteAssemblyFromProjectRef/LibraryWithResources/resx/words.es-ES.resx (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/SatelliteAssemblyFromProjectRef/LibraryWithResources/resx/words.ja-JP.resx (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/SatelliteAssemblyFromProjectRef/LibraryWithResources/resx/words.resx (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/SatelliteAssemblyInMain/resx/words.es-ES.resx (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/SatelliteAssemblyInMain/resx/words.ja-JP.resx (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/SatelliteAssemblyInMain/resx/words.resx (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/mono.png (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/native-libs/native-lib.o (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/native-libs/simple.c (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/native-libs/variadic.c (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/native-libs/variadic.o (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/resx/words.es-ES.resx (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/resx/words.ja-JP.resx (100%) rename src/{tests/BuildWasmApps => mono/wasm}/testassets/resx/words.resx (100%) delete mode 100644 src/tests/BuildWasmApps/Directory.Build.props delete mode 100644 src/tests/BuildWasmApps/Wasm.Build.Tests/Directory.Build.props diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index e3aa63b7c0ffad..d00f62f3c25290 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -74,7 +74,8 @@ /src/mono/nuget/*Workload.Mono.Toolchain*/ @lewing @radical /src/mono/nuget/*MonoAOTCompiler*/ @lewing @radical -/src/tests/BuildWasmApps/ @radical +/src/mono/wasm/Wasm* @radical +/src/mono/wasm/testassets @radical /src/tasks/WasmAppBuilder/ @radical /src/tasks/WorkloadBuildTasks/ @radical /src/tasks/AotCompilerTask/ @radical diff --git a/docs/workflow/testing/testing-workloads.md b/docs/workflow/testing/testing-workloads.md index 4bb29e96ec6570..d8241485182cfd 100644 --- a/docs/workflow/testing/testing-workloads.md +++ b/docs/workflow/testing/testing-workloads.md @@ -21,7 +21,7 @@ Example for wasm: VersionBand="$(SdkBandVersion)" /> ``` -- Currently, this is used only by `src/tests/BuildWasmApps/Wasm.Build.Tests` +- Currently, this is used only by `src/mono/wasm/Wasm.Build.Tests` ## Multiple runtime packs diff --git a/eng/pipelines/common/evaluate-default-paths.yml b/eng/pipelines/common/evaluate-default-paths.yml index 6191449eee03d2..75361e1d2c58f8 100644 --- a/eng/pipelines/common/evaluate-default-paths.yml +++ b/eng/pipelines/common/evaluate-default-paths.yml @@ -74,7 +74,7 @@ jobs: exclude: # wasm runtime changes will trigger all wasm jobs anyway - src/mono/wasm/* - - src/tests/BuildWasmApps/* + - src/mono/wasm/* - eng/pipelines/common/evaluate-default-paths.yml - subset: installer include: @@ -116,8 +116,8 @@ jobs: - subset: wasmbuildtests include: - src/tasks/* - - src/tests/BuildWasmApps/Directory.Build* - - src/tests/BuildWasmApps/Wasm.Build.Tests/* + - src/mono/wasm/Directory.Build* + - src/mono/wasm/Wasm.Build.Tests/* - src/mono/wasm/build/* - src/mono/wasm/host/* - src/mono/wasm/runtime/* @@ -141,8 +141,8 @@ jobs: include: - src/mono/wasm/debugger/* - src/mono/wasm/runtime/* - - src/tests/BuildWasmApps/Directory.Build* - - src/tests/BuildWasmApps/Wasm.Debugger.Tests/* + - src/mono/wasm/Directory.Build* + - src/mono/wasm/debugger/Wasm.Debugger.Tests/* - eng/testing/ProvisioningVersions.props - src/mono/mono/* exclude: diff --git a/eng/pipelines/coreclr/perf-wasm-prepare-artifacts-steps.yml b/eng/pipelines/coreclr/perf-wasm-prepare-artifacts-steps.yml index 54c4baf70a366e..96f61a17ce3c8d 100644 --- a/eng/pipelines/coreclr/perf-wasm-prepare-artifacts-steps.yml +++ b/eng/pipelines/coreclr/perf-wasm-prepare-artifacts-steps.yml @@ -7,7 +7,7 @@ steps: /p:Configuration=${{ parameters.configForBuild }} /p:ContinuousIntegrationBuild=true /t:InstallWorkloadUsingArtifacts - $(Build.SourcesDirectory)/src/tests/BuildWasmApps/Wasm.Build.Tests/Wasm.Build.Tests.csproj + $(Build.SourcesDirectory)/src/mono/wasm/Wasm.Build.Tests/Wasm.Build.Tests.csproj displayName: "Install workload using artifacts" - script: >- diff --git a/src/libraries/tests.proj b/src/libraries/tests.proj index 221bbde38aca11..cbcd14ccb89e4e 100644 --- a/src/libraries/tests.proj +++ b/src/libraries/tests.proj @@ -581,14 +581,14 @@ - - + + + BuildWasmApps + true + Wasm.Build.Tests + + + + diff --git a/src/tests/BuildWasmApps/Directory.Build.targets b/src/mono/wasm/Wasm.Build.Tests/Directory.Build.targets similarity index 82% rename from src/tests/BuildWasmApps/Directory.Build.targets rename to src/mono/wasm/Wasm.Build.Tests/Directory.Build.targets index 68e5c1b8ef20a7..43eea04f9888d0 100644 --- a/src/tests/BuildWasmApps/Directory.Build.targets +++ b/src/mono/wasm/Wasm.Build.Tests/Directory.Build.targets @@ -1,5 +1,5 @@ - + $(OutDir) diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/DotNetCommand.cs b/src/mono/wasm/Wasm.Build.Tests/DotNetCommand.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/DotNetCommand.cs rename to src/mono/wasm/Wasm.Build.Tests/DotNetCommand.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/EnvironmentVariables.cs b/src/mono/wasm/Wasm.Build.Tests/EnvironmentVariables.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/EnvironmentVariables.cs rename to src/mono/wasm/Wasm.Build.Tests/EnvironmentVariables.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/HelperExtensions.cs b/src/mono/wasm/Wasm.Build.Tests/HelperExtensions.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/HelperExtensions.cs rename to src/mono/wasm/Wasm.Build.Tests/HelperExtensions.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/InvariantGlobalizationTests.cs b/src/mono/wasm/Wasm.Build.Tests/InvariantGlobalizationTests.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/InvariantGlobalizationTests.cs rename to src/mono/wasm/Wasm.Build.Tests/InvariantGlobalizationTests.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/MainWithArgsTests.cs b/src/mono/wasm/Wasm.Build.Tests/MainWithArgsTests.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/MainWithArgsTests.cs rename to src/mono/wasm/Wasm.Build.Tests/MainWithArgsTests.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/NativeBuildTests.cs b/src/mono/wasm/Wasm.Build.Tests/NativeBuildTests.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/NativeBuildTests.cs rename to src/mono/wasm/Wasm.Build.Tests/NativeBuildTests.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/NativeLibraryTests.cs b/src/mono/wasm/Wasm.Build.Tests/NativeLibraryTests.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/NativeLibraryTests.cs rename to src/mono/wasm/Wasm.Build.Tests/NativeLibraryTests.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/NativeRebuildTests/FlagsChangeRebuildTest.cs b/src/mono/wasm/Wasm.Build.Tests/NativeRebuildTests/FlagsChangeRebuildTest.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/NativeRebuildTests/FlagsChangeRebuildTest.cs rename to src/mono/wasm/Wasm.Build.Tests/NativeRebuildTests/FlagsChangeRebuildTest.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/NativeRebuildTests/NativeRebuildTestsBase.cs b/src/mono/wasm/Wasm.Build.Tests/NativeRebuildTests/NativeRebuildTestsBase.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/NativeRebuildTests/NativeRebuildTestsBase.cs rename to src/mono/wasm/Wasm.Build.Tests/NativeRebuildTests/NativeRebuildTestsBase.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/NativeRebuildTests/NoopNativeRebuildTest.cs b/src/mono/wasm/Wasm.Build.Tests/NativeRebuildTests/NoopNativeRebuildTest.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/NativeRebuildTests/NoopNativeRebuildTest.cs rename to src/mono/wasm/Wasm.Build.Tests/NativeRebuildTests/NoopNativeRebuildTest.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/NativeRebuildTests/ReferenceNewAssemblyRebuildTest.cs b/src/mono/wasm/Wasm.Build.Tests/NativeRebuildTests/ReferenceNewAssemblyRebuildTest.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/NativeRebuildTests/ReferenceNewAssemblyRebuildTest.cs rename to src/mono/wasm/Wasm.Build.Tests/NativeRebuildTests/ReferenceNewAssemblyRebuildTest.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/NativeRebuildTests/SimpleSourceChangeRebuildTest.cs b/src/mono/wasm/Wasm.Build.Tests/NativeRebuildTests/SimpleSourceChangeRebuildTest.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/NativeRebuildTests/SimpleSourceChangeRebuildTest.cs rename to src/mono/wasm/Wasm.Build.Tests/NativeRebuildTests/SimpleSourceChangeRebuildTest.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/PInvokeTableGeneratorTests.cs b/src/mono/wasm/Wasm.Build.Tests/PInvokeTableGeneratorTests.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/PInvokeTableGeneratorTests.cs rename to src/mono/wasm/Wasm.Build.Tests/PInvokeTableGeneratorTests.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/ProcessExtensions.cs b/src/mono/wasm/Wasm.Build.Tests/ProcessExtensions.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/ProcessExtensions.cs rename to src/mono/wasm/Wasm.Build.Tests/ProcessExtensions.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/README.md b/src/mono/wasm/Wasm.Build.Tests/README.md similarity index 92% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/README.md rename to src/mono/wasm/Wasm.Build.Tests/README.md index 79a0a8945a89d9..60d8dced9b81e2 100644 --- a/src/tests/BuildWasmApps/Wasm.Build.Tests/README.md +++ b/src/mono/wasm/Wasm.Build.Tests/README.md @@ -13,7 +13,7 @@ being generated. - Running: Linux/macOS: `$ make -C src/mono/wasm run-build-tests` -Windows: `.\dotnet.cmd build .\src\tests\BuildWasmApps\Wasm.Build.Tests\Wasm.Build.Tests.csproj -c Release -t:Test -p:TargetOS=Browser -p:TargetArchitecture=wasm` +Windows: `.\dotnet.cmd build .\src\mono\wasm\BuildWasmApps\Wasm.Build.Tests\Wasm.Build.Tests.csproj -c Release -t:Test -p:TargetOS=Browser -p:TargetArchitecture=wasm` - Specific tests can be run via `XUnitClassName`, and `XUnitMethodName` - eg. `XUnitClassName=Wasm.Build.Tests.BlazorWasmTests` diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/RebuildTests.cs b/src/mono/wasm/Wasm.Build.Tests/RebuildTests.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/RebuildTests.cs rename to src/mono/wasm/Wasm.Build.Tests/RebuildTests.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/RunCommand.cs b/src/mono/wasm/Wasm.Build.Tests/RunCommand.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/RunCommand.cs rename to src/mono/wasm/Wasm.Build.Tests/RunCommand.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/RunHost.cs b/src/mono/wasm/Wasm.Build.Tests/RunHost.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/RunHost.cs rename to src/mono/wasm/Wasm.Build.Tests/RunHost.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/SatelliteAssembliesTests.cs b/src/mono/wasm/Wasm.Build.Tests/SatelliteAssembliesTests.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/SatelliteAssembliesTests.cs rename to src/mono/wasm/Wasm.Build.Tests/SatelliteAssembliesTests.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/SharedBuildPerTestClassFixture.cs b/src/mono/wasm/Wasm.Build.Tests/SharedBuildPerTestClassFixture.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/SharedBuildPerTestClassFixture.cs rename to src/mono/wasm/Wasm.Build.Tests/SharedBuildPerTestClassFixture.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/ToolCommand.cs b/src/mono/wasm/Wasm.Build.Tests/ToolCommand.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/ToolCommand.cs rename to src/mono/wasm/Wasm.Build.Tests/ToolCommand.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/Utils.cs b/src/mono/wasm/Wasm.Build.Tests/Utils.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/Utils.cs rename to src/mono/wasm/Wasm.Build.Tests/Utils.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/Wasm.Build.Tests.csproj b/src/mono/wasm/Wasm.Build.Tests/Wasm.Build.Tests.csproj similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/Wasm.Build.Tests.csproj rename to src/mono/wasm/Wasm.Build.Tests/Wasm.Build.Tests.csproj diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/WasmBuildAppTest.cs b/src/mono/wasm/Wasm.Build.Tests/WasmBuildAppTest.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/WasmBuildAppTest.cs rename to src/mono/wasm/Wasm.Build.Tests/WasmBuildAppTest.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/WasmNativeDefaultsTests.cs b/src/mono/wasm/Wasm.Build.Tests/WasmNativeDefaultsTests.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/WasmNativeDefaultsTests.cs rename to src/mono/wasm/Wasm.Build.Tests/WasmNativeDefaultsTests.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/WasmRunOutOfAppBundleTests.cs b/src/mono/wasm/Wasm.Build.Tests/WasmRunOutOfAppBundleTests.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/WasmRunOutOfAppBundleTests.cs rename to src/mono/wasm/Wasm.Build.Tests/WasmRunOutOfAppBundleTests.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/WasmSIMDTests.cs b/src/mono/wasm/Wasm.Build.Tests/WasmSIMDTests.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/WasmSIMDTests.cs rename to src/mono/wasm/Wasm.Build.Tests/WasmSIMDTests.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/WasmTemplateTests.cs b/src/mono/wasm/Wasm.Build.Tests/WasmTemplateTests.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/WasmTemplateTests.cs rename to src/mono/wasm/Wasm.Build.Tests/WasmTemplateTests.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/WorkloadTests.cs b/src/mono/wasm/Wasm.Build.Tests/WorkloadTests.cs similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/WorkloadTests.cs rename to src/mono/wasm/Wasm.Build.Tests/WorkloadTests.cs diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/data/Blazor.Directory.Build.props b/src/mono/wasm/Wasm.Build.Tests/data/Blazor.Directory.Build.props similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/data/Blazor.Directory.Build.props rename to src/mono/wasm/Wasm.Build.Tests/data/Blazor.Directory.Build.props diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/data/Blazor.Directory.Build.targets b/src/mono/wasm/Wasm.Build.Tests/data/Blazor.Directory.Build.targets similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/data/Blazor.Directory.Build.targets rename to src/mono/wasm/Wasm.Build.Tests/data/Blazor.Directory.Build.targets diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/data/Blazor.Local.Directory.Build.props b/src/mono/wasm/Wasm.Build.Tests/data/Blazor.Local.Directory.Build.props similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/data/Blazor.Local.Directory.Build.props rename to src/mono/wasm/Wasm.Build.Tests/data/Blazor.Local.Directory.Build.props diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/data/Blazor.Local.Directory.Build.targets b/src/mono/wasm/Wasm.Build.Tests/data/Blazor.Local.Directory.Build.targets similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/data/Blazor.Local.Directory.Build.targets rename to src/mono/wasm/Wasm.Build.Tests/data/Blazor.Local.Directory.Build.targets diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/data/Local.Directory.Build.props b/src/mono/wasm/Wasm.Build.Tests/data/Local.Directory.Build.props similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/data/Local.Directory.Build.props rename to src/mono/wasm/Wasm.Build.Tests/data/Local.Directory.Build.props diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/data/Local.Directory.Build.targets b/src/mono/wasm/Wasm.Build.Tests/data/Local.Directory.Build.targets similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/data/Local.Directory.Build.targets rename to src/mono/wasm/Wasm.Build.Tests/data/Local.Directory.Build.targets diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/data/RunScriptTemplate.cmd b/src/mono/wasm/Wasm.Build.Tests/data/RunScriptTemplate.cmd similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/data/RunScriptTemplate.cmd rename to src/mono/wasm/Wasm.Build.Tests/data/RunScriptTemplate.cmd diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/data/RunScriptTemplate.sh b/src/mono/wasm/Wasm.Build.Tests/data/RunScriptTemplate.sh similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/data/RunScriptTemplate.sh rename to src/mono/wasm/Wasm.Build.Tests/data/RunScriptTemplate.sh diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/data/Workloads.Directory.Build.props b/src/mono/wasm/Wasm.Build.Tests/data/Workloads.Directory.Build.props similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/data/Workloads.Directory.Build.props rename to src/mono/wasm/Wasm.Build.Tests/data/Workloads.Directory.Build.props diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/data/Workloads.Directory.Build.targets b/src/mono/wasm/Wasm.Build.Tests/data/Workloads.Directory.Build.targets similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/data/Workloads.Directory.Build.targets rename to src/mono/wasm/Wasm.Build.Tests/data/Workloads.Directory.Build.targets diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/data/nuget7.config b/src/mono/wasm/Wasm.Build.Tests/data/nuget7.config similarity index 100% rename from src/tests/BuildWasmApps/Wasm.Build.Tests/data/nuget7.config rename to src/mono/wasm/Wasm.Build.Tests/data/nuget7.config diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj b/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj index 18812234973ee1..2b4e7bee7a5a69 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj +++ b/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj @@ -26,7 +26,7 @@ - + diff --git a/src/mono/wasm/debugger/README.md b/src/mono/wasm/debugger/README.md index dad724cdb0c13f..938e8c037bcf37 100644 --- a/src/mono/wasm/debugger/README.md +++ b/src/mono/wasm/debugger/README.md @@ -3,3 +3,8 @@ ## Debug proxy - Protocol messages are truncated when logged, to 64k, by default. But this can be changed by setting `WASM_DONT_TRUNCATE_LOG_MESSAGES=1`. + +## Projects + +- `DebuggerTestSuite` - project with all the tests, and the test harness +- `Wasm.Debugger.Tests` - a wrapper project to fit in the global build diff --git a/src/mono/wasm/debugger/Wasm.Debugger.Tests/Directory.Build.props b/src/mono/wasm/debugger/Wasm.Debugger.Tests/Directory.Build.props new file mode 100644 index 00000000000000..0909239ceb7771 --- /dev/null +++ b/src/mono/wasm/debugger/Wasm.Debugger.Tests/Directory.Build.props @@ -0,0 +1,7 @@ + + + true + + + + diff --git a/src/mono/wasm/debugger/Wasm.Debugger.Tests/Directory.Build.targets b/src/mono/wasm/debugger/Wasm.Debugger.Tests/Directory.Build.targets new file mode 100644 index 00000000000000..be4716c527cf75 --- /dev/null +++ b/src/mono/wasm/debugger/Wasm.Debugger.Tests/Directory.Build.targets @@ -0,0 +1,9 @@ + + + + + $(OutDir) + $(OutDir)\RunTests.sh + $(OutDir)\RunTests.cmd + + diff --git a/src/tests/BuildWasmApps/Wasm.Debugger.Tests/Wasm.Debugger.Tests.csproj b/src/mono/wasm/debugger/Wasm.Debugger.Tests/Wasm.Debugger.Tests.csproj similarity index 97% rename from src/tests/BuildWasmApps/Wasm.Debugger.Tests/Wasm.Debugger.Tests.csproj rename to src/mono/wasm/debugger/Wasm.Debugger.Tests/Wasm.Debugger.Tests.csproj index 19fbd1aa03698d..8a0a2e95de496c 100644 --- a/src/tests/BuildWasmApps/Wasm.Debugger.Tests/Wasm.Debugger.Tests.csproj +++ b/src/mono/wasm/debugger/Wasm.Debugger.Tests/Wasm.Debugger.Tests.csproj @@ -24,7 +24,7 @@ - - - diff --git a/src/tests/BuildWasmApps/Wasm.Build.Tests/Directory.Build.props b/src/tests/BuildWasmApps/Wasm.Build.Tests/Directory.Build.props deleted file mode 100644 index a48db59c3af3bb..00000000000000 --- a/src/tests/BuildWasmApps/Wasm.Build.Tests/Directory.Build.props +++ /dev/null @@ -1,8 +0,0 @@ - - - - BuildWasmApps - - - - diff --git a/src/tests/Common/dirs.proj b/src/tests/Common/dirs.proj index 1ead56f57b64be..2233c0702c81fd 100644 --- a/src/tests/Common/dirs.proj +++ b/src/tests/Common/dirs.proj @@ -10,7 +10,6 @@ - From ca916f28b7a8251ef1d118722f18114b1f42d447 Mon Sep 17 00:00:00 2001 From: Eric StJohn Date: Mon, 29 Aug 2022 15:15:14 -0700 Subject: [PATCH 022/107] Add Nick to area-owners.json (#74761) --- docs/area-owners.json | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/docs/area-owners.json b/docs/area-owners.json index be3b338b7e09f0..55724212139d76 100644 --- a/docs/area-owners.json +++ b/docs/area-owners.json @@ -206,12 +206,13 @@ }, { "lead": "ericstj", - "pod": "eric-maryam-tarek", + "pod": "eric-maryam-nick-tarek", "owners": [ "eerhardt", "ericstj", "jeffhandley", "maryamariyan", + "Nick-Stanton", "tarekgh", "dotnet/area-dependencymodel" ], @@ -248,12 +249,13 @@ }, { "lead": "ericstj", - "pod": "eric-maryam-tarek", + "pod": "eric-maryam-nick-tarek", "owners": [ "eerhardt", "ericstj", "jeffhandley", "maryamariyan", + "Nick-Stanton", "tarekgh", "dotnet/area-extensions-caching" ], @@ -261,12 +263,13 @@ }, { "lead": "ericstj", - "pod": "eric-maryam-tarek", + "pod": "eric-maryam-nick-tarek", "owners": [ "eerhardt", "ericstj", "jeffhandley", "maryamariyan", + "Nick-Stanton", "tarekgh", "dotnet/area-extensions-configuration" ], @@ -274,12 +277,13 @@ }, { "lead": "ericstj", - "pod": "eric-maryam-tarek", + "pod": "eric-maryam-nick-tarek", "owners": [ "eerhardt", "ericstj", "jeffhandley", "maryamariyan", + "Nick-Stanton", "tarekgh", "dotnet/area-extensions-dependencyinjection" ], @@ -301,12 +305,13 @@ }, { "lead": "ericstj", - "pod": "eric-maryam-tarek", + "pod": "eric-maryam-nick-tarek", "owners": [ "eerhardt", "ericstj", "jeffhandley", "maryamariyan", + "Nick-Stanton", "tarekgh", "dotnet/area-extensions-hosting" ], @@ -331,12 +336,13 @@ }, { "lead": "ericstj", - "pod": "eric-maryam-tarek", + "pod": "eric-maryam-nick-tarek", "owners": [ "eerhardt", "ericstj", "jeffhandley", "maryamariyan", + "Nick-Stanton", "tarekgh", "dotnet/area-extensions-logging" ], @@ -344,12 +350,13 @@ }, { "lead": "ericstj", - "pod": "eric-maryam-tarek", + "pod": "eric-maryam-nick-tarek", "owners": [ "eerhardt", "ericstj", "jeffhandley", "maryamariyan", + "Nick-Stanton", "tarekgh", "dotnet/area-extensions-options" ], @@ -357,12 +364,13 @@ }, { "lead": "ericstj", - "pod": "eric-maryam-tarek", + "pod": "eric-maryam-nick-tarek", "owners": [ "eerhardt", "ericstj", "jeffhandley", "maryamariyan", + "Nick-Stanton", "tarekgh", "dotnet/area-extensions-primitives" ], @@ -645,12 +653,13 @@ }, { "lead": "ericstj", - "pod": "eric-maryam-tarek", + "pod": "eric-maryam-nick-tarek", "owners": [ "eerhardt", "ericstj", "jeffhandley", "maryamariyan", + "Nick-Stanton", "tarekgh", "dotnet/area-system-componentmodel" ], @@ -658,12 +667,13 @@ }, { "lead": "ericstj", - "pod": "eric-maryam-tarek", + "pod": "eric-maryam-nick-tarek", "owners": [ "eerhardt", "ericstj", "jeffhandley", "maryamariyan", + "Nick-Stanton", "tarekgh", "dotnet/area-system-componentmodel-composition" ], @@ -679,12 +689,13 @@ }, { "lead": "ericstj", - "pod": "eric-maryam-tarek", + "pod": "eric-maryam-nick-tarek", "owners": [ "eerhardt", "ericstj", "jeffhandley", "maryamariyan", + "Nick-Stanton", "tarekgh", "dotnet/area-system-composition" ], @@ -906,12 +917,13 @@ }, { "lead": "ericstj", - "pod": "eric-maryam-tarek", + "pod": "eric-maryam-nick-tarek", "owners": [ "eerhardt", "ericstj", "jeffhandley", "maryamariyan", + "Nick-Stanton", "tarekgh", "dotnet/area-system-globalization" ], From bc9c37105c87b1f763692a33c0304e4e81fbbb92 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Mon, 29 Aug 2022 17:52:21 -0700 Subject: [PATCH 023/107] Refactor marshalling info parser to split overall logic from ordering (#72687) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Refactor marshalling info parser to split overall logic from ordering Split our marshalling attribute parser into separate classes for each attribute and category and make the parser itself only handle executing the various different stages of marshalling info parsing. All logic for parsing a given attribute is handled now by the separate classes. This PR allows the JS marshaller to reuse the core of our parsing and opt-in to more of the logic as they see fit. * Add doc comments for all of the new APIs * Fix failing test * Make the JS known managed type info hang off the JS marshalling info instead of inheriting from ManagedTypeInfo. ManagedTypeInfo is meant to represent just enough info from an ITypeSymbol that we can accurately generate code based on any language/typesystem rules. It is not meant for storing generator-specific marshalling info. * Create JSTypeInfo based on symbols, not type name string parsing. * Apply suggestions from code review Co-authored-by: Marek Fišera * PR feedback. * Add comments Co-authored-by: Marek Fišera --- .../FallbackJSMarshallingInfoProvider.cs | 22 + .../JSExportCodeGenerator.cs | 4 +- .../JSImportGenerator/JSGeneratorFactory.cs | 31 +- .../JSImportCodeGenerator.cs | 4 +- .../JSImportGenerator/JSImportStubContext.cs | 22 +- .../JSImportGenerator/JSManagedTypeInfo.cs | 277 +++---- .../JSMarshallAsAttributeInfoParser.cs | 67 ++ .../JSMarshallingAttributeInfoParser.cs | 86 -- .../JSImportGenerator/JSMarshallingInfo.cs | 16 +- .../Marshaling/FuncJSGenerator.cs | 4 +- .../Marshaling/TaskJSGenerator.cs | 14 +- .../ConvertToLibraryImportAnalyzer.cs | 4 +- .../LibraryImportGenerator.cs | 2 +- .../ArrayMarshallingInfoProvider.cs | 87 +++ .../BlittableTypeMarshallingInfoProvider.cs | 45 ++ .../BooleanMarshallingInfoProvider.cs | 28 + .../CharMarshallingInfoProvider.cs | 32 + .../CustomMarshallingInfoHelper.cs | 111 +++ .../MarshalAsAttributeParser.cs | 158 ++++ .../MarshalUsingAttributeParser.cs | 114 +++ .../Marshalling/MarshallerHelpers.cs | 14 +- .../MarshallingAttributeInfo.cs | 735 +----------------- .../MarshallingInfoParser.cs | 367 +++++++++ .../MethodSignatureElementInfoProvider.cs | 78 ++ .../NativeMarshallingAttributeParser.cs | 49 ++ .../SafeHandleMarshallingInfoProvider.cs | 65 ++ .../SignatureContext.cs | 34 +- .../StringMarshallingInfoProvider.cs | 96 +++ .../UseSiteAttributeProvider.cs | 101 +++ .../CompileFails.cs | 4 +- 30 files changed, 1656 insertions(+), 1015 deletions(-) create mode 100644 src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/FallbackJSMarshallingInfoProvider.cs create mode 100644 src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSMarshallAsAttributeInfoParser.cs delete mode 100644 src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSMarshallingAttributeInfoParser.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ArrayMarshallingInfoProvider.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/BlittableTypeMarshallingInfoProvider.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/BooleanMarshallingInfoProvider.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/CharMarshallingInfoProvider.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/CustomMarshallingInfoHelper.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalAsAttributeParser.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalUsingAttributeParser.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallingInfoParser.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MethodSignatureElementInfoProvider.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/NativeMarshallingAttributeParser.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/SafeHandleMarshallingInfoProvider.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/StringMarshallingInfoProvider.cs create mode 100644 src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/UseSiteAttributeProvider.cs diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/FallbackJSMarshallingInfoProvider.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/FallbackJSMarshallingInfoProvider.cs new file mode 100644 index 00000000000000..58ed34812e7df0 --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/FallbackJSMarshallingInfoProvider.cs @@ -0,0 +1,22 @@ +// 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.Text; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop.JavaScript +{ + /// + /// Always returns a JSMissingMarshallingInfo. + /// + internal sealed class FallbackJSMarshallingInfoProvider : ITypeBasedMarshallingInfoProvider + { + public bool CanProvideMarshallingInfoForType(ITypeSymbol type) => true; + public MarshallingInfo GetMarshallingInfo(ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + return new JSMissingMarshallingInfo(JSTypeInfo.CreateJSTypeInfoForTypeSymbol(type)); + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSExportCodeGenerator.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSExportCodeGenerator.cs index 1318358bea4632..0dba53f9bf0b63 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSExportCodeGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSExportCodeGenerator.cs @@ -40,9 +40,9 @@ public JSExportCodeGenerator( } // validate task + span mix - if (_marshallers.ManagedReturnMarshaller.TypeInfo.ManagedType is JSTaskTypeInfo) + if (_marshallers.ManagedReturnMarshaller.TypeInfo.MarshallingAttributeInfo is JSMarshallingInfo(_, JSTaskTypeInfo)) { - BoundGenerator spanArg = _marshallers.AllMarshallers.FirstOrDefault(m => m.TypeInfo.ManagedType is JSSpanTypeInfo); + BoundGenerator spanArg = _marshallers.AllMarshallers.FirstOrDefault(m => m.TypeInfo.MarshallingAttributeInfo is JSMarshallingInfo(_, JSSpanTypeInfo)); if (spanArg != default) { marshallingNotSupportedCallback(spanArg.TypeInfo, new MarshallingNotSupportedException(spanArg.TypeInfo, _context) diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSGeneratorFactory.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSGeneratorFactory.cs index f908872318b5f0..7c000011bf0462 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSGeneratorFactory.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSGeneratorFactory.cs @@ -7,6 +7,7 @@ using Microsoft.CodeAnalysis; using System.Collections.Generic; using System.Diagnostics; +using System.Data; namespace Microsoft.Interop.JavaScript { @@ -34,51 +35,51 @@ Exception fail(string failReason) } bool isToJs = info.ManagedIndex != TypePositionInfo.ReturnIndex ^ context is JSExportCodeContext; - switch (info) + switch (jsMarshalingInfo) { // invalid - case { ManagedType: JSInvalidTypeInfo }: + case { TypeInfo: JSInvalidTypeInfo }: throw new MarshallingNotSupportedException(info, context); // void - case { ManagedType: SpecialTypeInfo sd } when sd.SpecialType == SpecialType.System_Void && jsMarshalingInfo.JSType == JSTypeFlags.Discard: - case { ManagedType: SpecialTypeInfo sv } when sv.SpecialType == SpecialType.System_Void && jsMarshalingInfo.JSType == JSTypeFlags.Void: - case { ManagedType: SpecialTypeInfo sn } when sn.SpecialType == SpecialType.System_Void && jsMarshalingInfo.JSType == JSTypeFlags.None: - case { ManagedType: SpecialTypeInfo sm } when sm.SpecialType == SpecialType.System_Void && jsMarshalingInfo.JSType == JSTypeFlags.Missing: + case { TypeInfo: JSSimpleTypeInfo(KnownManagedType.Void), JSType: JSTypeFlags.Discard }: + case { TypeInfo: JSSimpleTypeInfo(KnownManagedType.Void), JSType: JSTypeFlags.Void }: + case { TypeInfo: JSSimpleTypeInfo(KnownManagedType.Void), JSType: JSTypeFlags.None }: + case { TypeInfo: JSSimpleTypeInfo(KnownManagedType.Void), JSType: JSTypeFlags.Missing }: return new VoidGenerator(jsMarshalingInfo.JSType == JSTypeFlags.Void ? MarshalerType.Void : MarshalerType.Discard); // discard no void - case { } when jsMarshalingInfo.JSType == JSTypeFlags.Discard: + case { JSType: JSTypeFlags.Discard }: throw fail(SR.DiscardOnlyVoid); // primitive - case { ManagedType: JSSimpleTypeInfo simple }: + case { TypeInfo: JSSimpleTypeInfo simple }: return Create(info, isToJs, simple.KnownType, Array.Empty(), jsMarshalingInfo.JSType, Array.Empty(), fail); // nullable - case { ManagedType: JSNullableTypeInfo nullable }: + case { TypeInfo: JSNullableTypeInfo nullable }: return Create(info, isToJs, nullable.KnownType, new[] { nullable.ResultTypeInfo.KnownType }, jsMarshalingInfo.JSType, null, fail); // array - case { ManagedType: JSArrayTypeInfo array }: + case { TypeInfo: JSArrayTypeInfo array }: return Create(info, isToJs, array.KnownType, new[] { array.ElementTypeInfo.KnownType }, jsMarshalingInfo.JSType, jsMarshalingInfo.JSTypeArguments, fail); // array segment - case { ManagedType: JSArraySegmentTypeInfo segment }: + case { TypeInfo: JSArraySegmentTypeInfo segment }: return Create(info, isToJs, segment.KnownType, new[] { segment.ElementTypeInfo.KnownType }, jsMarshalingInfo.JSType, jsMarshalingInfo.JSTypeArguments, fail); // span - case { ManagedType: JSSpanTypeInfo span }: + case { TypeInfo: JSSpanTypeInfo span }: return Create(info, isToJs, span.KnownType, new[] { span.ElementTypeInfo.KnownType }, jsMarshalingInfo.JSType, jsMarshalingInfo.JSTypeArguments, fail); // task - case { ManagedType: JSTaskTypeInfo task } when task.ResultTypeInfo is JSSimpleTypeInfo taskRes && taskRes.FullTypeName == "void": + case { TypeInfo: JSTaskTypeInfo(JSSimpleTypeInfo(KnownManagedType.Void)) task }: return Create(info, isToJs, task.KnownType, Array.Empty(), jsMarshalingInfo.JSType, jsMarshalingInfo.JSTypeArguments, fail); - case { ManagedType: JSTaskTypeInfo task }: + case { TypeInfo: JSTaskTypeInfo task }: return Create(info, isToJs, task.KnownType, new[] { task.ResultTypeInfo.KnownType }, jsMarshalingInfo.JSType, jsMarshalingInfo.JSTypeArguments, fail); // action + function - case { ManagedType: JSFunctionTypeInfo function }: + case { TypeInfo: JSFunctionTypeInfo function }: return Create(info, isToJs, function.KnownType, function.ArgsTypeInfo.Select(a => a.KnownType).ToArray(), jsMarshalingInfo.JSType, jsMarshalingInfo.JSTypeArguments, fail); default: diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportCodeGenerator.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportCodeGenerator.cs index 7bed0e9df4ea53..9c10b08ef87570 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportCodeGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportCodeGenerator.cs @@ -47,9 +47,9 @@ public JSImportCodeGenerator( } // validate task + span mix - if (_marshallers.ManagedReturnMarshaller.TypeInfo.ManagedType is JSTaskTypeInfo) + if (_marshallers.ManagedReturnMarshaller.TypeInfo.MarshallingAttributeInfo is JSMarshallingInfo(_, JSTaskTypeInfo)) { - BoundGenerator spanArg = _marshallers.AllMarshallers.FirstOrDefault(m => m.TypeInfo.ManagedType is JSSpanTypeInfo); + BoundGenerator spanArg = _marshallers.AllMarshallers.FirstOrDefault(m => m.TypeInfo.MarshallingAttributeInfo is JSMarshallingInfo(_, JSSpanTypeInfo)); if (spanArg != default) { marshallingNotSupportedCallback(spanArg.TypeInfo, new MarshallingNotSupportedException(spanArg.TypeInfo, _context) diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportStubContext.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportStubContext.cs index 055e81315e68e4..84d3cc2b692fdb 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportStubContext.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportStubContext.cs @@ -145,19 +145,22 @@ public static JSSignatureContext Create( private static (ImmutableArray, IMarshallingGeneratorFactory) GenerateTypeInformation(IMethodSymbol method, GeneratorDiagnostics diagnostics, StubEnvironment env) { - var jsMarshallingAttributeParser = new JSMarshallingAttributeInfoParser(env.Compilation, diagnostics, method); + ImmutableArray useSiteAttributeParsers = ImmutableArray.Create(new JSMarshalAsAttributeParser(env.Compilation)); + var jsMarshallingAttributeParser = new MarshallingInfoParser( + diagnostics, + new MethodSignatureElementInfoProvider(env.Compilation, diagnostics, method, useSiteAttributeParsers), + useSiteAttributeParsers, + ImmutableArray.Create(new JSMarshalAsAttributeParser(env.Compilation)), + ImmutableArray.Create(new FallbackJSMarshallingInfoProvider())); // Determine parameter and return types ImmutableArray.Builder typeInfos = ImmutableArray.CreateBuilder(); for (int i = 0; i < method.Parameters.Length; i++) { IParameterSymbol param = method.Parameters[i]; - MarshallingInfo marshallingInfo = NoMarshallingInfo.Instance; - MarshallingInfo jsMarshallingInfo = jsMarshallingAttributeParser.ParseMarshallingInfo(param.Type, param.GetAttributes(), marshallingInfo); + MarshallingInfo jsMarshallingInfo = jsMarshallingAttributeParser.ParseMarshallingInfo(param.Type, param.GetAttributes()); - var typeInfo = TypePositionInfo.CreateForParameter(param, marshallingInfo, env.Compilation); - typeInfo = JSTypeInfo.CreateForType(typeInfo, param.Type, jsMarshallingInfo, env.Compilation); - typeInfo = typeInfo with + var typeInfo = TypePositionInfo.CreateForParameter(param, jsMarshallingInfo, env.Compilation) with { ManagedIndex = i, NativeIndex = typeInfos.Count, @@ -165,12 +168,9 @@ private static (ImmutableArray, IMarshallingGeneratorFactory) typeInfos.Add(typeInfo); } - MarshallingInfo retMarshallingInfo = NoMarshallingInfo.Instance; - MarshallingInfo retJSMarshallingInfo = jsMarshallingAttributeParser.ParseMarshallingInfo(method.ReturnType, method.GetReturnTypeAttributes(), retMarshallingInfo); + MarshallingInfo retJSMarshallingInfo = jsMarshallingAttributeParser.ParseMarshallingInfo(method.ReturnType, method.GetReturnTypeAttributes()); - var retTypeInfo = new TypePositionInfo(ManagedTypeInfo.CreateTypeInfoForTypeSymbol(method.ReturnType), retMarshallingInfo); - retTypeInfo = JSTypeInfo.CreateForType(retTypeInfo, method.ReturnType, retJSMarshallingInfo, env.Compilation); - retTypeInfo = retTypeInfo with + var retTypeInfo = new TypePositionInfo(ManagedTypeInfo.CreateTypeInfoForTypeSymbol(method.ReturnType), retJSMarshallingInfo) { ManagedIndex = TypePositionInfo.ReturnIndex, NativeIndex = TypePositionInfo.ReturnIndex, diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSManagedTypeInfo.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSManagedTypeInfo.cs index 0eedd0aa873e55..0f9084a01e8416 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSManagedTypeInfo.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSManagedTypeInfo.cs @@ -4,185 +4,192 @@ using System; using System.Linq; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.Interop.JavaScript { - internal abstract record JSTypeInfo(string FullTypeName, string DiagnosticFormattedName, KnownManagedType KnownType) : ManagedTypeInfo(FullTypeName, DiagnosticFormattedName) + internal abstract record JSTypeInfo(KnownManagedType KnownType) { - public static ManagedTypeInfo CreateJSTypeInfoForTypeSymbol(ITypeSymbol type) + public static JSTypeInfo CreateJSTypeInfoForTypeSymbol(ITypeSymbol type) { string fullTypeName = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); - if (fullTypeName == "void") + switch (type) { - return SpecialTypeInfo.Void; - } - string diagnosticFormattedName = type.ToDisplayString(); - return CreateJSTypeInfoForTypeSymbol(fullTypeName, diagnosticFormattedName); - } - - public static ManagedTypeInfo CreateJSTypeInfoForTypeSymbol(string fullTypeName, string diagnosticFormattedName) - { - switch (fullTypeName.Trim()) - { - case "global::System.Void": - case "void": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.Void); - case "global::System.Boolean": - case "bool": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.Boolean); - case "global::System.Byte": - case "byte": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.Byte); - case "global::System.Char": - case "char": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.Char); - case "global::System.Int16": - case "short": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.Int16); - case "global::System.Int32": - case "int": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.Int32); - case "global::System.Int64": - case "long": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.Int64); - case "global::System.Single": - case "float": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.Single); - case "global::System.Double": - case "double": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.Double); - case "global::System.IntPtr": - case "nint": - case "void*": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.IntPtr); - case "global::System.DateTime": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.DateTime); - case "global::System.DateTimeOffset": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.DateTimeOffset); - case "global::System.Exception": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.Exception); - case "global::System.Object": - case "object": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.Object); - case "global::System.String": - case "string": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.String); - case "global::System.Runtime.InteropServices.JavaScript.JSObject": - return new JSSimpleTypeInfo(fullTypeName, diagnosticFormattedName, KnownManagedType.JSObject); + case { SpecialType: SpecialType.System_Void }: + return new JSSimpleTypeInfo(KnownManagedType.Void) + { + Syntax = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)) + }; + case { SpecialType: SpecialType.System_Boolean }: + return new JSSimpleTypeInfo(KnownManagedType.Boolean) + { + Syntax = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)) + }; + case { SpecialType: SpecialType.System_Byte }: + return new JSSimpleTypeInfo(KnownManagedType.Byte) + { + Syntax = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword)) + }; + case { SpecialType: SpecialType.System_Char }: + return new JSSimpleTypeInfo(KnownManagedType.Char) + { + Syntax = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword)) + }; + case { SpecialType: SpecialType.System_Int16 }: + return new JSSimpleTypeInfo(KnownManagedType.Int16) + { + Syntax = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword)) + }; + case { SpecialType: SpecialType.System_Int32 }: + return new JSSimpleTypeInfo(KnownManagedType.Int32) + { + Syntax = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)) + }; + case { SpecialType: SpecialType.System_Int64 }: + return new JSSimpleTypeInfo(KnownManagedType.Int64) + { + Syntax = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword)) + }; + case { SpecialType: SpecialType.System_Single }: + return new JSSimpleTypeInfo(KnownManagedType.Single) + { + Syntax = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.FloatKeyword)) + }; + case { SpecialType: SpecialType.System_Double }: + return new JSSimpleTypeInfo(KnownManagedType.Double) + { + Syntax = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword)) + }; + case { SpecialType: SpecialType.System_IntPtr }: + case IPointerTypeSymbol { PointedAtType.SpecialType: SpecialType.System_Void }: + return new JSSimpleTypeInfo(KnownManagedType.IntPtr) + { + Syntax = SyntaxFactory.IdentifierName("nint") + }; + case { SpecialType: SpecialType.System_DateTime }: + return new JSSimpleTypeInfo(KnownManagedType.DateTime) + { + Syntax = SyntaxFactory.ParseTypeName(fullTypeName.Trim()) + }; + case ITypeSymbol when fullTypeName == "global::System.DateTimeOffset": + return new JSSimpleTypeInfo(KnownManagedType.DateTimeOffset) + { + Syntax = SyntaxFactory.ParseTypeName(fullTypeName.Trim()) + }; + case ITypeSymbol when fullTypeName == "global::System.Exception": + return new JSSimpleTypeInfo(KnownManagedType.Exception) + { + Syntax = SyntaxFactory.ParseTypeName(fullTypeName.Trim()) + }; + case { SpecialType: SpecialType.System_Object }: + return new JSSimpleTypeInfo(KnownManagedType.Object) + { + Syntax = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)) + }; + case { SpecialType: SpecialType.System_String }: + return new JSSimpleTypeInfo(KnownManagedType.String) + { + Syntax = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)) + }; + case ITypeSymbol when fullTypeName == "global::System.Runtime.InteropServices.JavaScript.JSObject": + return new JSSimpleTypeInfo(KnownManagedType.JSObject) + { + Syntax = SyntaxFactory.ParseTypeName(fullTypeName.Trim()) + }; //nullable - case string ftn when ftn.EndsWith("?"): - var ut = fullTypeName.Remove(fullTypeName.Length - 1); - if (CreateJSTypeInfoForTypeSymbol(ut, diagnosticFormattedName) is JSSimpleTypeInfo uti) + case INamedTypeSymbol { ConstructedFrom.SpecialType: SpecialType.System_Nullable_T } nullable: + if (CreateJSTypeInfoForTypeSymbol(nullable.TypeArguments[0]) is JSSimpleTypeInfo uti) { - return new JSNullableTypeInfo(fullTypeName, diagnosticFormattedName, uti); + return new JSNullableTypeInfo(uti); } - return new JSInvalidTypeInfo(fullTypeName, diagnosticFormattedName); + return new JSInvalidTypeInfo(); // array - case string ftn when ftn.EndsWith("[]"): - var et = fullTypeName.Remove(fullTypeName.Length - 2); - if (CreateJSTypeInfoForTypeSymbol(et, diagnosticFormattedName) is JSSimpleTypeInfo eti) + case IArrayTypeSymbol { IsSZArray: true, ElementType: ITypeSymbol elementType }: + if (CreateJSTypeInfoForTypeSymbol(elementType) is JSSimpleTypeInfo eti) { - return new JSArrayTypeInfo(fullTypeName, diagnosticFormattedName, eti); + return new JSArrayTypeInfo(eti); } - return new JSInvalidTypeInfo(fullTypeName, diagnosticFormattedName); + return new JSInvalidTypeInfo(); // task - case Constants.TaskGlobal: - return new JSTaskTypeInfo(fullTypeName, diagnosticFormattedName, (JSSimpleTypeInfo)CreateJSTypeInfoForTypeSymbol("void", diagnosticFormattedName)); - case string ft when ft.StartsWith(Constants.TaskGlobal): - var rt = fullTypeName.Substring(Constants.TaskGlobal.Length + 1, fullTypeName.Length - Constants.TaskGlobal.Length - 2); - if (CreateJSTypeInfoForTypeSymbol(rt, diagnosticFormattedName) is JSSimpleTypeInfo rti) + case ITypeSymbol when fullTypeName == Constants.TaskGlobal: + return new JSTaskTypeInfo(new JSSimpleTypeInfo(KnownManagedType.Void, SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)))); + case INamedTypeSymbol { TypeArguments.Length: 1 } taskType when fullTypeName.StartsWith(Constants.TaskGlobal, StringComparison.Ordinal): + if (CreateJSTypeInfoForTypeSymbol(taskType.TypeArguments[0]) is JSSimpleTypeInfo rti) { - return new JSTaskTypeInfo(fullTypeName, diagnosticFormattedName, rti); + return new JSTaskTypeInfo(rti); } - return new JSInvalidTypeInfo(fullTypeName, diagnosticFormattedName); + return new JSInvalidTypeInfo(); // span - case string ft when ft.StartsWith(Constants.SpanGlobal): - var st = fullTypeName.Substring(Constants.SpanGlobal.Length + 1, fullTypeName.Length - Constants.SpanGlobal.Length - 2); - if (CreateJSTypeInfoForTypeSymbol(st, diagnosticFormattedName) is JSSimpleTypeInfo sti) + case INamedTypeSymbol { TypeArguments.Length: 1 } spanType when fullTypeName.StartsWith(Constants.SpanGlobal, StringComparison.Ordinal): + if (CreateJSTypeInfoForTypeSymbol(spanType.TypeArguments[0]) is JSSimpleTypeInfo sti) { - return new JSSpanTypeInfo(fullTypeName, diagnosticFormattedName, sti); + return new JSSpanTypeInfo(sti); } - return new JSInvalidTypeInfo(fullTypeName, diagnosticFormattedName); + return new JSInvalidTypeInfo(); // array segment - case string ft when ft.StartsWith(Constants.ArraySegmentGlobal): - var gt = fullTypeName.Substring(Constants.ArraySegmentGlobal.Length + 1, fullTypeName.Length - Constants.ArraySegmentGlobal.Length - 2); - if (CreateJSTypeInfoForTypeSymbol(gt, diagnosticFormattedName) is JSSimpleTypeInfo gti) + case INamedTypeSymbol { TypeArguments.Length: 1 } arraySegmentType when fullTypeName.StartsWith(Constants.ArraySegmentGlobal, StringComparison.Ordinal): + if (CreateJSTypeInfoForTypeSymbol(arraySegmentType.TypeArguments[0]) is JSSimpleTypeInfo gti) { - return new JSArraySegmentTypeInfo(fullTypeName, diagnosticFormattedName, gti); + return new JSArraySegmentTypeInfo(gti); } - return new JSInvalidTypeInfo(fullTypeName, diagnosticFormattedName); + return new JSInvalidTypeInfo(); // action - case Constants.ActionGlobal: - return new JSFunctionTypeInfo(fullTypeName, diagnosticFormattedName, true, Array.Empty()); - case string ft when ft.StartsWith(Constants.ActionGlobal): - var argNames = fullTypeName.Substring(Constants.ActionGlobal.Length + 1, fullTypeName.Length - Constants.ActionGlobal.Length - 2); - if (!argNames.Contains("<")) - { - var ga = argNames.Split(',') - .Select(argName => CreateJSTypeInfoForTypeSymbol(argName, diagnosticFormattedName) as JSSimpleTypeInfo) - .ToArray(); - if (ga.Any(x => x == null)) - { - return new JSInvalidTypeInfo(fullTypeName, diagnosticFormattedName); - } - return new JSFunctionTypeInfo(fullTypeName, diagnosticFormattedName, true, ga); + case ITypeSymbol when fullTypeName == Constants.ActionGlobal: + return new JSFunctionTypeInfo(true, Array.Empty()); + case INamedTypeSymbol actionType when fullTypeName.StartsWith(Constants.ActionGlobal, StringComparison.Ordinal): + var argumentTypes = actionType.TypeArguments + .Select(arg => CreateJSTypeInfoForTypeSymbol(arg) as JSSimpleTypeInfo) + .ToArray(); + if (argumentTypes.Any(x => x is null)) + { + return new JSInvalidTypeInfo(); } - return new JSInvalidTypeInfo(fullTypeName, diagnosticFormattedName); + return new JSFunctionTypeInfo(true, argumentTypes); // function - case string ft when ft.StartsWith(Constants.FuncGlobal): - var fargNames = fullTypeName.Substring(Constants.FuncGlobal.Length + 1, fullTypeName.Length - Constants.FuncGlobal.Length - 2); - if (!fargNames.Contains("<")) - { - var ga = fargNames.Split(',') - .Select(argName => CreateJSTypeInfoForTypeSymbol(argName, diagnosticFormattedName) as JSSimpleTypeInfo) - .ToArray(); - if (ga.Any(x => x == null)) - { - return new JSInvalidTypeInfo(fullTypeName, diagnosticFormattedName); - } - return new JSFunctionTypeInfo(fullTypeName, diagnosticFormattedName, false, ga); + case INamedTypeSymbol funcType when fullTypeName.StartsWith(Constants.FuncGlobal, StringComparison.Ordinal): + var signatureTypes = funcType.TypeArguments + .Select(argName => CreateJSTypeInfoForTypeSymbol(argName) as JSSimpleTypeInfo) + .ToArray(); + if (signatureTypes.Any(x => x is null)) + { + return new JSInvalidTypeInfo(); } - return new JSInvalidTypeInfo(fullTypeName, diagnosticFormattedName); + return new JSFunctionTypeInfo(false, signatureTypes); default: - return new JSInvalidTypeInfo(fullTypeName, diagnosticFormattedName); + return new JSInvalidTypeInfo(); } } + } - public static TypePositionInfo CreateForType(TypePositionInfo inner, ITypeSymbol type, MarshallingInfo jsMarshallingInfo, Compilation compilation) - { - ManagedTypeInfo jsTypeInfo = CreateJSTypeInfoForTypeSymbol(type); - var typeInfo = new TypePositionInfo(jsTypeInfo, jsMarshallingInfo) - { - InstanceIdentifier = inner.InstanceIdentifier, - RefKind = inner.RefKind, - RefKindSyntax = inner.RefKindSyntax, - ByValueContentsMarshalKind = inner.ByValueContentsMarshalKind - }; + internal sealed record JSInvalidTypeInfo() : JSSimpleTypeInfo(KnownManagedType.None); - return typeInfo; + internal record JSSimpleTypeInfo(KnownManagedType KnownType) : JSTypeInfo(KnownType) + { + public JSSimpleTypeInfo(KnownManagedType knownType, TypeSyntax syntax) + : this(knownType) + { + Syntax = syntax; } + public TypeSyntax Syntax { get; init; } } - internal sealed record JSInvalidTypeInfo(string FullTypeName, string DiagnosticFormattedName) : JSSimpleTypeInfo(FullTypeName, DiagnosticFormattedName, KnownManagedType.None); - - internal record JSSimpleTypeInfo(string FullTypeName, string DiagnosticFormattedName, KnownManagedType KnownType) : JSTypeInfo(FullTypeName, DiagnosticFormattedName, KnownType); - - internal sealed record JSArrayTypeInfo(string FullTypeName, string DiagnosticFormattedName, JSSimpleTypeInfo ElementTypeInfo) : JSTypeInfo(FullTypeName, DiagnosticFormattedName, KnownManagedType.Array); + internal sealed record JSArrayTypeInfo(JSSimpleTypeInfo ElementTypeInfo) : JSTypeInfo(KnownManagedType.Array); - internal sealed record JSSpanTypeInfo(string FullTypeName, string DiagnosticFormattedName, JSSimpleTypeInfo ElementTypeInfo) : JSTypeInfo(FullTypeName, DiagnosticFormattedName, KnownManagedType.Span); + internal sealed record JSSpanTypeInfo(JSSimpleTypeInfo ElementTypeInfo) : JSTypeInfo(KnownManagedType.Span); - internal sealed record JSArraySegmentTypeInfo(string FullTypeName, string DiagnosticFormattedName, JSSimpleTypeInfo ElementTypeInfo) : JSTypeInfo(FullTypeName, DiagnosticFormattedName, KnownManagedType.ArraySegment); + internal sealed record JSArraySegmentTypeInfo(JSSimpleTypeInfo ElementTypeInfo) : JSTypeInfo(KnownManagedType.ArraySegment); - internal sealed record JSTaskTypeInfo(string FullTypeName, string DiagnosticFormattedName, JSSimpleTypeInfo ResultTypeInfo) : JSTypeInfo(FullTypeName, DiagnosticFormattedName, KnownManagedType.Task); + internal sealed record JSTaskTypeInfo(JSSimpleTypeInfo ResultTypeInfo) : JSTypeInfo(KnownManagedType.Task); - internal sealed record JSNullableTypeInfo(string FullTypeName, string DiagnosticFormattedName, JSSimpleTypeInfo ResultTypeInfo) : JSTypeInfo(FullTypeName, DiagnosticFormattedName, KnownManagedType.Nullable); + internal sealed record JSNullableTypeInfo(JSSimpleTypeInfo ResultTypeInfo) : JSTypeInfo(KnownManagedType.Nullable); - internal sealed record JSFunctionTypeInfo(string FullTypeName, string DiagnosticFormattedName, bool IsAction, JSSimpleTypeInfo[] ArgsTypeInfo) : JSTypeInfo(FullTypeName, DiagnosticFormattedName, (IsAction ? KnownManagedType.Action : KnownManagedType.Function)); + internal sealed record JSFunctionTypeInfo(bool IsAction, JSSimpleTypeInfo[] ArgsTypeInfo) : JSTypeInfo(IsAction ? KnownManagedType.Action : KnownManagedType.Function); } diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSMarshallAsAttributeInfoParser.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSMarshallAsAttributeInfoParser.cs new file mode 100644 index 00000000000000..179cc065f03ed4 --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSMarshallAsAttributeInfoParser.cs @@ -0,0 +1,67 @@ +// 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.Data; +using System.Linq; +using System.Runtime.InteropServices.JavaScript; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop.JavaScript +{ + internal sealed class JSMarshalAsAttributeParser : IMarshallingInfoAttributeParser, IUseSiteAttributeParser + { + private readonly INamedTypeSymbol _jsMarshalAsAttribute; + + public JSMarshalAsAttributeParser(Compilation compilation) + { + _jsMarshalAsAttribute = compilation.GetTypeByMetadataName(Constants.JSMarshalAsAttribute)!.ConstructUnboundGenericType(); + } + public bool CanParseAttributeType(INamedTypeSymbol attributeType) => attributeType.IsGenericType && SymbolEqualityComparer.Default.Equals(_jsMarshalAsAttribute, attributeType.ConstructUnboundGenericType()); + public MarshallingInfo ParseAttribute(AttributeData attributeData, ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + JSTypeFlags jsType = JSTypeFlags.None; + List jsTypeArguments = new List(); + INamedTypeSymbol? jsTypeArgs = attributeData.AttributeClass.TypeArguments[0] as INamedTypeSymbol; + if (jsTypeArgs.IsGenericType) + { + string gt = jsTypeArgs.ConstructUnboundGenericType().ToDisplayString(); + string name = gt.Substring(gt.IndexOf("JSType") + "JSType.".Length); + name = name.Substring(0, name.IndexOf("<")); + + Enum.TryParse(name, out jsType); + + foreach (var ta in jsTypeArgs.TypeArguments.Cast().Select(x => x.ToDisplayString())) + { + string argName = ta.Substring(ta.IndexOf("JSType") + "JSType.".Length); + JSTypeFlags jsTypeArg = JSTypeFlags.None; + Enum.TryParse(argName, out jsTypeArg); + jsTypeArguments.Add(jsTypeArg); + } + } + else + { + string st = jsTypeArgs.ToDisplayString(); + string name = st.Substring(st.IndexOf("JSType") + "JSType.".Length); + Enum.TryParse(name, out jsType); + } + + if (jsType == JSTypeFlags.None) + { + return new JSMissingMarshallingInfo(JSTypeInfo.CreateJSTypeInfoForTypeSymbol(type)); + } + + return new JSMarshallingInfo(NoMarshallingInfo.Instance, JSTypeInfo.CreateJSTypeInfoForTypeSymbol(type)) + { + JSType = jsType, + JSTypeArguments = jsTypeArguments.ToArray(), + }; + } + + UseSiteAttributeData IUseSiteAttributeParser.ParseAttribute(AttributeData attributeData, IElementInfoProvider elementInfoProvider, GetMarshallingInfoCallback marshallingInfoCallback) + { + return new UseSiteAttributeData(0, NoCountInfo.Instance, attributeData); + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSMarshallingAttributeInfoParser.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSMarshallingAttributeInfoParser.cs deleted file mode 100644 index b6fdaa576b5783..00000000000000 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSMarshallingAttributeInfoParser.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.InteropServices.JavaScript; -using Microsoft.CodeAnalysis; - -namespace Microsoft.Interop.JavaScript -{ - public sealed class JSMarshallingAttributeInfoParser - { - private readonly ITypeSymbol _jsMarshalAsAttribute; - private readonly ITypeSymbol _marshalUsingAttribute; - - public JSMarshallingAttributeInfoParser( - Compilation compilation, - IGeneratorDiagnostics diagnostics, - ISymbol contextSymbol) - { - _jsMarshalAsAttribute = compilation.GetTypeByMetadataName(Constants.JSMarshalAsAttribute)!.ConstructUnboundGenericType(); - _marshalUsingAttribute = compilation.GetTypeByMetadataName(Constants.MarshalUsingAttribute)!; - } - - public MarshallingInfo ParseMarshallingInfo( - ITypeSymbol managedType, - IEnumerable useSiteAttributes, - MarshallingInfo inner) - { - JSTypeFlags jsType = JSTypeFlags.None; - List jsTypeArguments = new List(); - - foreach (AttributeData useSiteAttribute in useSiteAttributes) - { - INamedTypeSymbol attributeClass = useSiteAttribute.AttributeClass!; - if (attributeClass.IsGenericType && SymbolEqualityComparer.Default.Equals(_jsMarshalAsAttribute, attributeClass.ConstructUnboundGenericType())) - { - INamedTypeSymbol? jsTypeArgs = attributeClass.TypeArguments[0] as INamedTypeSymbol; - if (jsTypeArgs.IsGenericType) - { - string gt = jsTypeArgs.ConstructUnboundGenericType().ToDisplayString(); - string name = gt.Substring(gt.IndexOf("JSType") + "JSType.".Length); - name = name.Substring(0, name.IndexOf("<")); - - Enum.TryParse(name, out jsType); - - foreach (var ta in jsTypeArgs.TypeArguments.Cast().Select(x => x.ToDisplayString())) - { - string argName = ta.Substring(ta.IndexOf("JSType") + "JSType.".Length); - JSTypeFlags jsTypeArg = JSTypeFlags.None; - Enum.TryParse(argName, out jsTypeArg); - jsTypeArguments.Add(jsTypeArg); - } - } - else - { - string st = jsTypeArgs.ToDisplayString(); - string name = st.Substring(st.IndexOf("JSType") + "JSType.".Length); - Enum.TryParse(name, out jsType); - } - - } - if (SymbolEqualityComparer.Default.Equals(_marshalUsingAttribute, attributeClass)) - { - return new JSMarshallingInfo(inner) - { - JSType = JSTypeFlags.Array, - JSTypeArguments = Array.Empty(), - }; - } - } - - if (jsType == JSTypeFlags.None) - { - return new JSMissingMarshallingInfo(); - } - - return new JSMarshallingInfo(inner) - { - JSType = jsType, - JSTypeArguments = jsTypeArguments.ToArray(), - }; - } - } -} diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSMarshallingInfo.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSMarshallingInfo.cs index d18f67b47928cd..edeb7961aadb1e 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSMarshallingInfo.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSMarshallingInfo.cs @@ -6,26 +6,24 @@ namespace Microsoft.Interop.JavaScript { - internal record JSMarshallingInfo : MarshallingInfo + internal record JSMarshallingInfo(MarshallingInfo Inner, JSTypeInfo TypeInfo) : MarshallingInfo { - public MarshallingInfo Inner; - public JSTypeFlags JSType; - public JSTypeFlags[] JSTypeArguments; - public JSMarshallingInfo(MarshallingInfo inner) - { - Inner = inner; - } protected JSMarshallingInfo() + :this(NoMarshallingInfo.Instance, new JSInvalidTypeInfo()) { Inner = null; } + + public JSTypeFlags JSType { get; init; } + public JSTypeFlags[] JSTypeArguments { get; init; } } internal sealed record JSMissingMarshallingInfo : JSMarshallingInfo { - public JSMissingMarshallingInfo() + public JSMissingMarshallingInfo(JSTypeInfo typeInfo) { JSType = JSTypeFlags.Missing; + TypeInfo = typeInfo; } } } diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/FuncJSGenerator.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/FuncJSGenerator.cs index fed51dde6d6f6c..ecbb1fcaa76c9e 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/FuncJSGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/FuncJSGenerator.cs @@ -48,9 +48,9 @@ public override IEnumerable Generate(TypePositionInfo info, Stu ? Argument(IdentifierName(context.GetIdentifiers(info).native)) : _inner.AsArgument(info, context); - var jsty = (JSFunctionTypeInfo)info.ManagedType; + var jsty = (JSFunctionTypeInfo)((JSMarshallingInfo)info.MarshallingAttributeInfo).TypeInfo; var sourceTypes = jsty.ArgsTypeInfo - .Select(a => ParseTypeName(a.FullTypeName)) + .Select(a => a.Syntax) .ToArray(); if (context.CurrentStage == StubCodeContext.Stage.Unmarshal && context.Direction == CustomTypeMarshallingDirection.In && info.IsManagedReturnPosition) diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/TaskJSGenerator.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/TaskJSGenerator.cs index 86162f0e62c945..df9cee6af62ba2 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/TaskJSGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/Marshaling/TaskJSGenerator.cs @@ -20,8 +20,8 @@ public TaskJSGenerator(MarshalerType resultMarshalerType) public override IEnumerable GenerateBind(TypePositionInfo info, StubCodeContext context) { - var jsty = (JSTaskTypeInfo)info.ManagedType; - if (jsty.ResultTypeInfo.FullTypeName == "void") + var jsty = (JSTaskTypeInfo)((JSMarshallingInfo)info.MarshallingAttributeInfo).TypeInfo; + if (jsty.ResultTypeInfo is JSSimpleTypeInfo(KnownManagedType.Void)) { yield return InvocationExpression(MarshalerTypeName(MarshalerType.Task), ArgumentList()); } @@ -34,7 +34,7 @@ public override IEnumerable GenerateBind(TypePositionInfo info public override IEnumerable Generate(TypePositionInfo info, StubCodeContext context) { - var jsty = (JSTaskTypeInfo)info.ManagedType; + var jsty = (JSTaskTypeInfo)((JSMarshallingInfo)info.MarshallingAttributeInfo).TypeInfo; string argName = context.GetAdditionalIdentifier(info, "js_arg"); var target = info.IsManagedReturnPosition @@ -47,14 +47,14 @@ public override IEnumerable Generate(TypePositionInfo info, Stu if (context.CurrentStage == StubCodeContext.Stage.Unmarshal && context.Direction == CustomTypeMarshallingDirection.In && info.IsManagedReturnPosition) { - yield return jsty.ResultTypeInfo.FullTypeName == "void" + yield return jsty.ResultTypeInfo is JSSimpleTypeInfo(KnownManagedType.Void) ? ToManagedMethodVoid(target, source) : ToManagedMethod(target, source, jsty.ResultTypeInfo.Syntax); } if (context.CurrentStage == StubCodeContext.Stage.Marshal && context.Direction == CustomTypeMarshallingDirection.Out && info.IsManagedReturnPosition) { - yield return jsty.ResultTypeInfo.FullTypeName == "void" + yield return jsty.ResultTypeInfo is JSSimpleTypeInfo(KnownManagedType.Void) ? ToJSMethodVoid(target, source) : ToJSMethod(target, source, jsty.ResultTypeInfo.Syntax); } @@ -66,14 +66,14 @@ public override IEnumerable Generate(TypePositionInfo info, Stu if (context.CurrentStage == StubCodeContext.Stage.Invoke && context.Direction == CustomTypeMarshallingDirection.In && !info.IsManagedReturnPosition) { - yield return jsty.ResultTypeInfo.FullTypeName == "void" + yield return jsty.ResultTypeInfo is JSSimpleTypeInfo(KnownManagedType.Void) ? ToJSMethodVoid(target, source) : ToJSMethod(target, source, jsty.ResultTypeInfo.Syntax); } if (context.CurrentStage == StubCodeContext.Stage.Unmarshal && context.Direction == CustomTypeMarshallingDirection.Out && !info.IsManagedReturnPosition) { - yield return jsty.ResultTypeInfo.FullTypeName == "void" + yield return jsty.ResultTypeInfo is JSSimpleTypeInfo(KnownManagedType.Void) ? ToManagedMethodVoid(target, source) : ToManagedMethod(target, source, jsty.ResultTypeInfo.Syntax); } diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ConvertToLibraryImportAnalyzer.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ConvertToLibraryImportAnalyzer.cs index 204709cf60c86c..be23c9e3e555c5 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ConvertToLibraryImportAnalyzer.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ConvertToLibraryImportAnalyzer.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; @@ -86,7 +87,8 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbo // later user work. AnyDiagnosticsSink diagnostics = new(); StubEnvironment env = context.Compilation.CreateStubEnvironment(); - SignatureContext targetSignatureContext = SignatureContext.Create(method, CreateInteropAttributeDataFromDllImport(dllImportData), env, diagnostics, typeof(ConvertToLibraryImportAnalyzer).Assembly); + AttributeData dllImportAttribute = method.GetAttributes().First(attr => attr.AttributeClass.ToDisplayString() == TypeNames.DllImportAttribute); + SignatureContext targetSignatureContext = SignatureContext.Create(method, CreateInteropAttributeDataFromDllImport(dllImportData), env, diagnostics, dllImportAttribute, typeof(ConvertToLibraryImportAnalyzer).Assembly); var generatorFactoryKey = LibraryImportGeneratorHelpers.CreateGeneratorFactory(env, new LibraryImportGeneratorOptions(context.Options.AnalyzerConfigOptionsProvider.GlobalOptions)); diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs index 1da4dbd49afeca..f74db2f8d845ea 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.cs @@ -312,7 +312,7 @@ private static IncrementalStubGenerationContext CalculateStubInformation( } // Create the stub. - var signatureContext = SignatureContext.Create(symbol, libraryImportData, environment, generatorDiagnostics, typeof(LibraryImportGenerator).Assembly); + var signatureContext = SignatureContext.Create(symbol, libraryImportData, environment, generatorDiagnostics, generatedDllImportAttr, typeof(LibraryImportGenerator).Assembly); var containingTypeContext = new ContainingSyntaxContext(originalSyntax); diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ArrayMarshallingInfoProvider.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ArrayMarshallingInfoProvider.cs new file mode 100644 index 00000000000000..2c58acff79b168 --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ArrayMarshallingInfoProvider.cs @@ -0,0 +1,87 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + /// + /// Marshalling information provider for single-dimensional zero-based array types using the System.Runtime.InteropServices.Marshalling.ArrayMarshaller and System.Runtime.InteropServices.Marshalling.PointerArrayMarshaller + /// built-in types. + /// + public sealed class ArrayMarshallingInfoProvider : ITypeBasedMarshallingInfoProvider + { + private readonly Compilation _compilation; + + public ArrayMarshallingInfoProvider(Compilation compilation) + { + _compilation = compilation; + } + + public bool CanProvideMarshallingInfoForType(ITypeSymbol type) => type is IArrayTypeSymbol { IsSZArray: true }; + + public MarshallingInfo GetMarshallingInfo(ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + CountInfo countInfo = NoCountInfo.Instance; + if (useSiteAttributes.TryGetUseSiteAttributeInfo(indirectionDepth, out UseSiteAttributeData useSiteInfo)) + { + countInfo = useSiteInfo.CountInfo; + } + + ITypeSymbol elementType = ((IArrayTypeSymbol)type).ElementType; + return CreateArrayMarshallingInfo(_compilation, type, elementType, countInfo, marshallingInfoCallback(elementType, useSiteAttributes, indirectionDepth + 1)); + } + + public static MarshallingInfo CreateArrayMarshallingInfo( + Compilation compilation, + ITypeSymbol managedType, + ITypeSymbol elementType, + CountInfo countInfo, + MarshallingInfo elementMarshallingInfo) + { + ITypeSymbol typeArgumentToInsert = elementType; + INamedTypeSymbol? arrayMarshaller; + if (elementType is IPointerTypeSymbol { PointedAtType: ITypeSymbol pointedAt }) + { + arrayMarshaller = compilation.GetTypeByMetadataName(TypeNames.System_Runtime_InteropServices_PointerArrayMarshaller_Metadata); + typeArgumentToInsert = pointedAt; + } + else + { + arrayMarshaller = compilation.GetTypeByMetadataName(TypeNames.System_Runtime_InteropServices_ArrayMarshaller_Metadata); + } + + if (arrayMarshaller is null) + { + // If the array marshaler type is not available, then we cannot marshal arrays but indicate it is missing. + return new MissingSupportCollectionMarshallingInfo(countInfo, elementMarshallingInfo); + } + + if (ManualTypeMarshallingHelper.HasEntryPointMarshallerAttribute(arrayMarshaller) + && ManualTypeMarshallingHelper.IsLinearCollectionEntryPoint(arrayMarshaller)) + { + arrayMarshaller = arrayMarshaller.Construct( + typeArgumentToInsert, + arrayMarshaller.TypeArguments.Last()); + + Func getMarshallingInfoForElement = (ITypeSymbol elementType) => elementMarshallingInfo; + if (ManualTypeMarshallingHelper.TryGetLinearCollectionMarshallersFromEntryType(arrayMarshaller, managedType, compilation, getMarshallingInfoForElement, out CustomTypeMarshallers? marshallers)) + { + return new NativeLinearCollectionMarshallingInfo( + ManagedTypeInfo.CreateTypeInfoForTypeSymbol(arrayMarshaller), + marshallers.Value, + countInfo, + ManagedTypeInfo.CreateTypeInfoForTypeSymbol(arrayMarshaller.TypeParameters.Last())); + } + } + + Debug.WriteLine("Default marshallers for arrays should be a valid shape."); + return NoMarshallingInfo.Instance; + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/BlittableTypeMarshallingInfoProvider.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/BlittableTypeMarshallingInfoProvider.cs new file mode 100644 index 00000000000000..cc3a1996957f19 --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/BlittableTypeMarshallingInfoProvider.cs @@ -0,0 +1,45 @@ +// 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.Text; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + /// + /// Marshalling information provider for unmanaged types that may be blittable. + /// + public sealed class BlittableTypeMarshallingInfoProvider : ITypeBasedMarshallingInfoProvider + { + private readonly Compilation _compilation; + + public BlittableTypeMarshallingInfoProvider(Compilation compilation) + { + _compilation = compilation; + } + + public bool CanProvideMarshallingInfoForType(ITypeSymbol type) => type is INamedTypeSymbol { IsUnmanagedType: true } unmanagedType + && unmanagedType.IsConsideredBlittable(); + public MarshallingInfo GetMarshallingInfo(ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + if (type.TypeKind is TypeKind.Enum or TypeKind.Pointer or TypeKind.FunctionPointer + || type.SpecialType.IsAlwaysBlittable()) + { + // Treat primitive types and enums as having no marshalling info. + // They are supported in configurations where runtime marshalling is enabled. + return NoMarshallingInfo.Instance; + } + else if (_compilation.GetTypeByMetadataName(TypeNames.System_Runtime_CompilerServices_DisableRuntimeMarshallingAttribute) is null) + { + // If runtime marshalling cannot be disabled, then treat this as a "missing support" scenario so we can gracefully fall back to using the forwarder downlevel. + return new MissingSupportMarshallingInfo(); + } + else + { + return new UnmanagedBlittableMarshallingInfo(type.IsStrictlyBlittable()); + } + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/BooleanMarshallingInfoProvider.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/BooleanMarshallingInfoProvider.cs new file mode 100644 index 00000000000000..6a7b78acf1dd56 --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/BooleanMarshallingInfoProvider.cs @@ -0,0 +1,28 @@ +// 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.Text; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + /// + /// Marshalling information provider for bool elements without any marshalling information. + /// + public sealed class BooleanMarshallingInfoProvider : ITypeBasedMarshallingInfoProvider + { + public bool CanProvideMarshallingInfoForType(ITypeSymbol type) => type.SpecialType == SpecialType.System_Boolean; + + public MarshallingInfo GetMarshallingInfo(ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + // We intentionally don't support marshalling bool with no marshalling info + // as treating bool as a non-normalized 1-byte value is generally not a good default. + // Additionally, that default is different than the runtime marshalling, so by explicitly + // blocking bool marshalling without additional info, we make it a little easier + // to transition by explicitly notifying people of changing behavior. + return NoMarshallingInfo.Instance; + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/CharMarshallingInfoProvider.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/CharMarshallingInfoProvider.cs new file mode 100644 index 00000000000000..b8b6f4c4c1608a --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/CharMarshallingInfoProvider.cs @@ -0,0 +1,32 @@ +// 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.Text; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + /// + /// Marshalling information provider for char elements without any marshalling information on the element itself. + /// + public sealed class CharMarshallingInfoProvider : ITypeBasedMarshallingInfoProvider + { + private readonly DefaultMarshallingInfo _defaultMarshallingInfo; + + public CharMarshallingInfoProvider(DefaultMarshallingInfo defaultMarshallingInfo) + { + _defaultMarshallingInfo = defaultMarshallingInfo; + } + + public bool CanProvideMarshallingInfoForType(ITypeSymbol type) => type.SpecialType == SpecialType.System_Char; + + public MarshallingInfo GetMarshallingInfo(ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + // No marshalling info was computed, but a character encoding was provided. + // If the type is a character then pass on these details. + return _defaultMarshallingInfo.CharEncoding == CharEncoding.Undefined ? new UnmanagedBlittableMarshallingInfo(IsStrictlyBlittable: false) : new MarshallingInfoStringSupport(_defaultMarshallingInfo.CharEncoding); + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/CustomMarshallingInfoHelper.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/CustomMarshallingInfoHelper.cs new file mode 100644 index 00000000000000..d1df5d4e19ed82 --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/CustomMarshallingInfoHelper.cs @@ -0,0 +1,111 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Linq; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + internal static class CustomMarshallingInfoHelper + { + public static MarshallingInfo CreateNativeMarshallingInfo( + ITypeSymbol type, + INamedTypeSymbol entryPointType, + AttributeData attrData, + UseSiteAttributeProvider useSiteAttributeProvider, + GetMarshallingInfoCallback getMarshallingInfoCallback, + int indirectionDepth, + CountInfo parsedCountInfo, + IGeneratorDiagnostics diagnostics, + Compilation compilation) + { + if (!ManualTypeMarshallingHelper.HasEntryPointMarshallerAttribute(entryPointType)) + { + return NoMarshallingInfo.Instance; + } + + if (!(entryPointType.IsStatic && entryPointType.TypeKind == TypeKind.Class) + && entryPointType.TypeKind != TypeKind.Struct) + { + diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.MarshallerTypeMustBeStaticClassOrStruct), entryPointType.ToDisplayString(), type.ToDisplayString()); + return NoMarshallingInfo.Instance; + } + + ManagedTypeInfo entryPointTypeInfo = ManagedTypeInfo.CreateTypeInfoForTypeSymbol(entryPointType); + + bool isLinearCollectionMarshalling = ManualTypeMarshallingHelper.IsLinearCollectionEntryPoint(entryPointType); + if (isLinearCollectionMarshalling) + { + // Update the entry point type with the type arguments based on the managed type + if (type is IArrayTypeSymbol arrayManagedType) + { + // Generally, we require linear collection marshallers to have "arity of managed type + 1" arity. + // However, arrays aren't "generic" over their element type as they're generics, but we want to treat the element type + // as a generic type parameter. As a result, we require an arity of 2 for array marshallers, 1 for the array element type, + // and 1 for the native element type (the required additional type parameter for linear collection marshallers). + if (entryPointType.Arity != 2) + { + diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.MarshallerEntryPointTypeMustMatchArity), entryPointType.ToDisplayString(), type.ToDisplayString()); + return NoMarshallingInfo.Instance; + } + + entryPointType = entryPointType.ConstructedFrom.Construct( + arrayManagedType.ElementType, + entryPointType.TypeArguments.Last()); + } + else if (type is INamedTypeSymbol namedManagedCollectionType && entryPointType.IsUnboundGenericType) + { + if (!ManualTypeMarshallingHelper.TryResolveEntryPointType( + namedManagedCollectionType, + entryPointType, + isLinearCollectionMarshalling, + (type, entryPointType) => diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.MarshallerEntryPointTypeMustMatchArity), entryPointType.ToDisplayString(), type.ToDisplayString()), + out ITypeSymbol resolvedEntryPointType)) + { + return NoMarshallingInfo.Instance; + } + + entryPointType = (INamedTypeSymbol)resolvedEntryPointType; + } + else + { + diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.MarshallerEntryPointTypeMustMatchArity), entryPointType.ToDisplayString(), type.ToDisplayString()); + return NoMarshallingInfo.Instance; + } + + Func getMarshallingInfoForElement = (ITypeSymbol elementType) => getMarshallingInfoCallback(elementType, useSiteAttributeProvider, indirectionDepth + 1); + if (ManualTypeMarshallingHelper.TryGetLinearCollectionMarshallersFromEntryType(entryPointType, type, compilation, getMarshallingInfoForElement, out CustomTypeMarshallers? collectionMarshallers)) + { + return new NativeLinearCollectionMarshallingInfo( + entryPointTypeInfo, + collectionMarshallers.Value, + parsedCountInfo, + ManagedTypeInfo.CreateTypeInfoForTypeSymbol(entryPointType.TypeParameters.Last())); + } + return NoMarshallingInfo.Instance; + } + + if (type is INamedTypeSymbol namedManagedType && entryPointType.IsUnboundGenericType) + { + if (!ManualTypeMarshallingHelper.TryResolveEntryPointType( + namedManagedType, + entryPointType, + isLinearCollectionMarshalling, + (type, entryPointType) => diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.MarshallerEntryPointTypeMustMatchArity), entryPointType.ToDisplayString(), type.ToDisplayString()), + out ITypeSymbol resolvedEntryPointType)) + { + return NoMarshallingInfo.Instance; + } + + entryPointType = (INamedTypeSymbol)resolvedEntryPointType; + } + + if (ManualTypeMarshallingHelper.TryGetValueMarshallersFromEntryType(entryPointType, type, compilation, out CustomTypeMarshallers? marshallers)) + { + return new NativeMarshallingAttributeInfo(entryPointTypeInfo, marshallers.Value); + } + return NoMarshallingInfo.Instance; + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalAsAttributeParser.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalAsAttributeParser.cs new file mode 100644 index 00000000000000..4294f11610f205 --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalAsAttributeParser.cs @@ -0,0 +1,158 @@ +// 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.Collections.Immutable; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + /// + /// Simple User-application of System.Runtime.InteropServices.MarshalAsAttribute + /// + public sealed record MarshalAsInfo( + UnmanagedType UnmanagedType, + CharEncoding CharEncoding) : MarshallingInfoStringSupport(CharEncoding) + { + // UnmanagedType.LPUTF8Str is not in netstandard2.0, so we define a constant for the value here. + // See https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.unmanagedtype + internal const UnmanagedType UnmanagedType_LPUTF8Str = (UnmanagedType)0x30; + } + + /// + /// This class suppports parsing a System.Runtime.InteropServices.MarshalAsAttribute. + /// + public sealed class MarshalAsAttributeParser : IMarshallingInfoAttributeParser, IUseSiteAttributeParser + { + private readonly Compilation _compilation; + private readonly IGeneratorDiagnostics _diagnostics; + private readonly DefaultMarshallingInfo _defaultInfo; + + public MarshalAsAttributeParser(Compilation compilation, IGeneratorDiagnostics diagnostics, DefaultMarshallingInfo defaultInfo) + { + _compilation = compilation; + _diagnostics = diagnostics; + _defaultInfo = defaultInfo; + } + + public bool CanParseAttributeType(INamedTypeSymbol attributeType) => attributeType.ToDisplayString() == TypeNames.System_Runtime_InteropServices_MarshalAsAttribute; + + UseSiteAttributeData IUseSiteAttributeParser.ParseAttribute(AttributeData attributeData, IElementInfoProvider elementInfoProvider, GetMarshallingInfoCallback marshallingInfoCallback) + { + ImmutableDictionary namedArguments = ImmutableDictionary.CreateRange(attributeData.NamedArguments); + SizeAndParamIndexInfo arraySizeInfo = SizeAndParamIndexInfo.Unspecified; + if (namedArguments.TryGetValue(nameof(MarshalAsAttribute.SizeConst), out TypedConstant sizeConstArg)) + { + arraySizeInfo = arraySizeInfo with { ConstSize = (int)sizeConstArg.Value! }; + } + if (namedArguments.TryGetValue(nameof(MarshalAsAttribute.SizeParamIndex), out TypedConstant sizeParamIndexArg)) + { + if (!elementInfoProvider.TryGetInfoForParamIndex(attributeData, (short)sizeParamIndexArg.Value!, marshallingInfoCallback, out TypePositionInfo paramIndexInfo)) + { + _diagnostics.ReportConfigurationNotSupported(attributeData, nameof(MarshalAsAttribute.SizeParamIndex), sizeParamIndexArg.Value.ToString()); + } + arraySizeInfo = arraySizeInfo with { ParamAtIndex = paramIndexInfo }; + } + return new UseSiteAttributeData(0, arraySizeInfo, attributeData); + } + + MarshallingInfo? IMarshallingInfoAttributeParser.ParseAttribute(AttributeData attributeData, ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + object unmanagedTypeObj = attributeData.ConstructorArguments[0].Value!; + UnmanagedType unmanagedType = unmanagedTypeObj is short unmanagedTypeAsShort + ? (UnmanagedType)unmanagedTypeAsShort + : (UnmanagedType)unmanagedTypeObj; + if (!Enum.IsDefined(typeof(UnmanagedType), unmanagedType) + || unmanagedType == UnmanagedType.CustomMarshaler + || unmanagedType == UnmanagedType.SafeArray) + { + _diagnostics.ReportConfigurationNotSupported(attributeData, nameof(UnmanagedType), unmanagedType.ToString()); + } + + bool isArrayType = unmanagedType == UnmanagedType.LPArray || unmanagedType == UnmanagedType.ByValArray; + UnmanagedType elementUnmanagedType = (UnmanagedType)SizeAndParamIndexInfo.UnspecifiedConstSize; + + // All other data on attribute is defined as NamedArguments. + foreach (KeyValuePair namedArg in attributeData.NamedArguments) + { + switch (namedArg.Key) + { + case nameof(MarshalAsAttribute.SafeArraySubType): + case nameof(MarshalAsAttribute.SafeArrayUserDefinedSubType): + case nameof(MarshalAsAttribute.IidParameterIndex): + case nameof(MarshalAsAttribute.MarshalTypeRef): + case nameof(MarshalAsAttribute.MarshalType): + case nameof(MarshalAsAttribute.MarshalCookie): + _diagnostics.ReportConfigurationNotSupported(attributeData, $"{attributeData.AttributeClass!.Name}{Type.Delimiter}{namedArg.Key}"); + break; + case nameof(MarshalAsAttribute.ArraySubType): + if (!isArrayType) + { + _diagnostics.ReportConfigurationNotSupported(attributeData, $"{attributeData.AttributeClass!.Name}{Type.Delimiter}{namedArg.Key}"); + } + elementUnmanagedType = (UnmanagedType)namedArg.Value.Value!; + break; + } + } + + if (isArrayType) + { + if (type is not IArrayTypeSymbol { ElementType: ITypeSymbol elementType }) + { + _diagnostics.ReportConfigurationNotSupported(attributeData, nameof(UnmanagedType), unmanagedType.ToString()); + return NoMarshallingInfo.Instance; + } + + MarshallingInfo elementMarshallingInfo = NoMarshallingInfo.Instance; + if (elementUnmanagedType != (UnmanagedType)SizeAndParamIndexInfo.UnspecifiedConstSize) + { + elementMarshallingInfo = elementType.SpecialType == SpecialType.System_String + ? CreateStringMarshallingInfo(elementType, elementUnmanagedType) + : new MarshalAsInfo(elementUnmanagedType, _defaultInfo.CharEncoding); + } + else + { + elementMarshallingInfo = marshallingInfoCallback(elementType, useSiteAttributes, indirectionDepth + 1); + } + + CountInfo countInfo = NoCountInfo.Instance; + + if (useSiteAttributes.TryGetUseSiteAttributeInfo(indirectionDepth, out UseSiteAttributeData useSiteAttributeData)) + { + countInfo = useSiteAttributeData.CountInfo; + } + + return ArrayMarshallingInfoProvider.CreateArrayMarshallingInfo(_compilation, type, elementType, countInfo, elementMarshallingInfo); + } + + if (type.SpecialType == SpecialType.System_String) + { + return CreateStringMarshallingInfo(type, unmanagedType); + } + + return new MarshalAsInfo(unmanagedType, _defaultInfo.CharEncoding); + } + + private MarshallingInfo CreateStringMarshallingInfo( + ITypeSymbol type, + UnmanagedType unmanagedType) + { + string? marshallerName = unmanagedType switch + { + UnmanagedType.BStr => TypeNames.BStrStringMarshaller, + UnmanagedType.LPStr => TypeNames.AnsiStringMarshaller, + UnmanagedType.LPTStr or UnmanagedType.LPWStr => TypeNames.Utf16StringMarshaller, + MarshalAsInfo.UnmanagedType_LPUTF8Str => TypeNames.Utf8StringMarshaller, + _ => null + }; + + if (marshallerName is null) + return new MarshalAsInfo(unmanagedType, _defaultInfo.CharEncoding); + + return StringMarshallingInfoProvider.CreateStringMarshallingInfo(_compilation, type, marshallerName); + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalUsingAttributeParser.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalUsingAttributeParser.cs new file mode 100644 index 00000000000000..14d60d3c9ce90f --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalUsingAttributeParser.cs @@ -0,0 +1,114 @@ +// 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.Collections.Immutable; +using System.Diagnostics; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + /// + /// This class suppports parsing a System.Runtime.InteropServices.Marshalling.MarshalUsingAttribute. + /// + public sealed class MarshalUsingAttributeParser : IMarshallingInfoAttributeParser, IUseSiteAttributeParser + { + private readonly Compilation _compilation; + private readonly IGeneratorDiagnostics _diagnostics; + + public MarshalUsingAttributeParser(Compilation compilation, IGeneratorDiagnostics diagnostics) + { + _compilation = compilation; + _diagnostics = diagnostics; + } + + public bool CanParseAttributeType(INamedTypeSymbol attributeType) => attributeType.ToDisplayString() == TypeNames.MarshalUsingAttribute; + + MarshallingInfo? IMarshallingInfoAttributeParser.ParseAttribute(AttributeData attributeData, ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + Debug.Assert(attributeData.AttributeClass!.ToDisplayString() == TypeNames.MarshalUsingAttribute); + CountInfo countInfo = NoCountInfo.Instance; + if (useSiteAttributes.TryGetUseSiteAttributeInfo(indirectionDepth, out UseSiteAttributeData useSiteInfo)) + { + countInfo = useSiteInfo.CountInfo; + } + + if (attributeData.ConstructorArguments.Length == 0) + { + // This attribute only has count information. + // It does not provide any marshalling info. + // Return null here to respresent the lack of any marshalling info, + // instead of the presence of invalid marshalling info. + return null; + } + + if (attributeData.ConstructorArguments[0].Value is not INamedTypeSymbol namedType) + { + return NoMarshallingInfo.Instance; + } + + return CustomMarshallingInfoHelper.CreateNativeMarshallingInfo( + type, + namedType, + attributeData, + useSiteAttributes, + marshallingInfoCallback, + indirectionDepth, + countInfo, + _diagnostics, + _compilation + ); + } + + UseSiteAttributeData IUseSiteAttributeParser.ParseAttribute(AttributeData attributeData, IElementInfoProvider elementInfoProvider, GetMarshallingInfoCallback marshallingInfoCallback) + { + ImmutableDictionary namedArgs = ImmutableDictionary.CreateRange(attributeData.NamedArguments); + CountInfo countInfo = ParseCountInfo(attributeData, namedArgs, elementInfoProvider, marshallingInfoCallback); + int elementIndirectionDepth = namedArgs.TryGetValue(ManualTypeMarshallingHelper.MarshalUsingProperties.ElementIndirectionDepth, out TypedConstant value) ? (int)value.Value! : 0; + return new UseSiteAttributeData(elementIndirectionDepth, countInfo, attributeData); + } + + private CountInfo ParseCountInfo(AttributeData attributeData, ImmutableDictionary namedArguments, IElementInfoProvider elementInfoProvider, GetMarshallingInfoCallback marshallingInfoCallback) + { + int? constSize = null; + string? elementName = null; + foreach (KeyValuePair arg in attributeData.NamedArguments) + { + if (arg.Key == ManualTypeMarshallingHelper.MarshalUsingProperties.ConstantElementCount) + { + constSize = (int)arg.Value.Value!; + } + else if (arg.Key == ManualTypeMarshallingHelper.MarshalUsingProperties.CountElementName) + { + if (arg.Value.Value is null) + { + _diagnostics.ReportConfigurationNotSupported(attributeData, ManualTypeMarshallingHelper.MarshalUsingProperties.CountElementName, "null"); + return NoCountInfo.Instance; + } + elementName = (string)arg.Value.Value!; + } + } + + if (constSize is not null && elementName is not null) + { + _diagnostics.ReportInvalidMarshallingAttributeInfo(attributeData, nameof(SR.ConstantAndElementCountInfoDisallowed)); + } + else if (constSize is not null) + { + return new ConstSizeCountInfo(constSize.Value); + } + else if (elementName is not null) + { + if (!elementInfoProvider.TryGetInfoForElementName(attributeData, elementName, marshallingInfoCallback, out TypePositionInfo elementInfo)) + { + _diagnostics.ReportConfigurationNotSupported(attributeData, ManualTypeMarshallingHelper.MarshalUsingProperties.CountElementName, elementName); + return NoCountInfo.Instance; + } + return new CountElementCountInfo(elementInfo); + } + + return NoCountInfo.Instance; + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshallerHelpers.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshallerHelpers.cs index c245f8db61bcb1..ab849630886ae1 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshallerHelpers.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshallerHelpers.cs @@ -281,13 +281,21 @@ public static IEnumerable GetDependentElementsOfMarshallingInf { if (nestedCollection.ElementCountInfo is CountElementCountInfo { ElementInfo: TypePositionInfo nestedCountElement }) { - yield return nestedCountElement; + // Do not include dependent elements with no managed or native index. + // These values are dummy values that are inserted earlier to avoid emitting extra diagnostics. + if (nestedCountElement.ManagedIndex != TypePositionInfo.UnsetIndex || nestedCountElement.NativeIndex != TypePositionInfo.UnsetIndex) + { + yield return nestedCountElement; + } } foreach (KeyValuePair mode in nestedCollection.Marshallers.Modes) { - foreach (TypePositionInfo nestedElements in GetDependentElementsOfMarshallingInfo(mode.Value.CollectionElementMarshallingInfo)) + foreach (TypePositionInfo nestedElement in GetDependentElementsOfMarshallingInfo(mode.Value.CollectionElementMarshallingInfo)) { - yield return nestedElements; + if (nestedElement.ManagedIndex != TypePositionInfo.UnsetIndex || nestedElement.NativeIndex != TypePositionInfo.UnsetIndex) + { + yield return nestedElement; + } } } } diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallingAttributeInfo.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallingAttributeInfo.cs index 19680588e7bad4..027267cf373a11 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallingAttributeInfo.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallingAttributeInfo.cs @@ -15,7 +15,7 @@ namespace Microsoft.Interop /// Type used to pass on default marshalling details. /// /// - /// This type used to pass default marshalling details to . + /// This type used to pass default marshalling details to the various marshalling info parsers. /// Since it contains a , it should not be used as a field on any types /// derived from . See remarks on . /// @@ -79,18 +79,6 @@ public record MarshallingInfoStringSupport( CharEncoding CharEncoding ) : MarshallingInfo; - /// - /// Simple User-application of System.Runtime.InteropServices.MarshalAsAttribute - /// - public sealed record MarshalAsInfo( - UnmanagedType UnmanagedType, - CharEncoding CharEncoding) : MarshallingInfoStringSupport(CharEncoding) - { - // UnmanagedType.LPUTF8Str is not in netstandard2.0, so we define a constant for the value here. - // See https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.unmanagedtype - internal const UnmanagedType UnmanagedType_LPUTF8Str = (UnmanagedType)0x30; - } - /// /// The provided type was determined to be an "unmanaged" type that can be passed as-is to native code. /// @@ -145,11 +133,6 @@ public sealed record NativeLinearCollectionMarshallingInfo( EntryPointType, Marshallers); - /// - /// The type of the element is a SafeHandle-derived type with no marshalling attributes. - /// - public sealed record SafeHandleMarshallingInfo(bool AccessibleDefaultConstructor, bool IsAbstract) : MarshallingInfo; - /// /// Marshalling information is lacking because of support not because it is /// unknown or non-existent. Includes information about element types in case @@ -160,720 +143,4 @@ public sealed record SafeHandleMarshallingInfo(bool AccessibleDefaultConstructor /// the forwarder marshaller. /// public sealed record MissingSupportCollectionMarshallingInfo(CountInfo CountInfo, MarshallingInfo ElementMarshallingInfo) : MissingSupportMarshallingInfo; - - public sealed class MarshallingAttributeInfoParser - { - private readonly Compilation _compilation; - private readonly IGeneratorDiagnostics _diagnostics; - private readonly DefaultMarshallingInfo _defaultInfo; - private readonly ISymbol _contextSymbol; - private readonly ITypeSymbol _marshalAsAttribute; - private readonly ITypeSymbol _marshalUsingAttribute; - - public MarshallingAttributeInfoParser( - Compilation compilation, - IGeneratorDiagnostics diagnostics, - DefaultMarshallingInfo defaultInfo, - ISymbol contextSymbol) - { - _compilation = compilation; - _diagnostics = diagnostics; - _defaultInfo = defaultInfo; - _contextSymbol = contextSymbol; - _marshalAsAttribute = compilation.GetTypeByMetadataName(TypeNames.System_Runtime_InteropServices_MarshalAsAttribute)!; - _marshalUsingAttribute = compilation.GetTypeByMetadataName(TypeNames.MarshalUsingAttribute)!; - } - - public MarshallingInfo ParseMarshallingInfo( - ITypeSymbol managedType, - IEnumerable useSiteAttributes) - { - return ParseMarshallingInfo(managedType, useSiteAttributes, ImmutableHashSet.Empty); - } - - private MarshallingInfo ParseMarshallingInfo( - ITypeSymbol managedType, - IEnumerable useSiteAttributes, - ImmutableHashSet inspectedElements) - { - Dictionary marshallingAttributesByIndirectionDepth = new(); - int maxIndirectionLevelDataProvided = 0; - foreach (AttributeData attribute in useSiteAttributes) - { - if (TryGetAttributeIndirectionLevel(attribute, out int indirectionLevel)) - { - if (marshallingAttributesByIndirectionDepth.ContainsKey(indirectionLevel)) - { - _diagnostics.ReportInvalidMarshallingAttributeInfo(attribute, nameof(SR.DuplicateMarshallingInfo), indirectionLevel.ToString()); - return NoMarshallingInfo.Instance; - } - marshallingAttributesByIndirectionDepth.Add(indirectionLevel, attribute); - maxIndirectionLevelDataProvided = Math.Max(maxIndirectionLevelDataProvided, indirectionLevel); - } - } - - int maxIndirectionDepthUsed = 0; - MarshallingInfo info = GetMarshallingInfo( - managedType, - marshallingAttributesByIndirectionDepth, - indirectionLevel: 0, - inspectedElements, - ref maxIndirectionDepthUsed); - if (maxIndirectionDepthUsed < maxIndirectionLevelDataProvided) - { - _diagnostics.ReportInvalidMarshallingAttributeInfo( - marshallingAttributesByIndirectionDepth[maxIndirectionLevelDataProvided], - nameof(SR.ExtraneousMarshallingInfo), - maxIndirectionLevelDataProvided.ToString(), - maxIndirectionDepthUsed.ToString()); - } - return info; - } - - private MarshallingInfo GetMarshallingInfo( - ITypeSymbol type, - Dictionary useSiteAttributes, - int indirectionLevel, - ImmutableHashSet inspectedElements, - ref int maxIndirectionDepthUsed) - { - maxIndirectionDepthUsed = Math.Max(indirectionLevel, maxIndirectionDepthUsed); - CountInfo parsedCountInfo = NoCountInfo.Instance; - - if (useSiteAttributes.TryGetValue(indirectionLevel, out AttributeData useSiteAttribute)) - { - INamedTypeSymbol attributeClass = useSiteAttribute.AttributeClass!; - - if (indirectionLevel == 0 - && SymbolEqualityComparer.Default.Equals(_compilation.GetTypeByMetadataName(TypeNames.System_Runtime_InteropServices_MarshalAsAttribute), attributeClass)) - { - // https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.marshalasattribute - return CreateInfoFromMarshalAs(type, useSiteAttribute, inspectedElements, ref maxIndirectionDepthUsed); - } - else if (SymbolEqualityComparer.Default.Equals(_compilation.GetTypeByMetadataName(TypeNames.MarshalUsingAttribute), attributeClass)) - { - if (parsedCountInfo != NoCountInfo.Instance) - { - _diagnostics.ReportInvalidMarshallingAttributeInfo(useSiteAttribute, nameof(SR.DuplicateCountInfo)); - return NoMarshallingInfo.Instance; - } - parsedCountInfo = CreateCountInfo(useSiteAttribute, inspectedElements); - if (useSiteAttribute.ConstructorArguments.Length != 0) - { - return CreateNativeMarshallingInfo( - type, - (INamedTypeSymbol)useSiteAttribute.ConstructorArguments[0].Value!, - useSiteAttribute, - isMarshalUsingAttribute: true, - indirectionLevel, - parsedCountInfo, - useSiteAttributes, - inspectedElements, - ref maxIndirectionDepthUsed); - } - } - } - - // If we aren't overriding the marshalling at usage time, - // then fall back to the information on the element type itself. - foreach (AttributeData typeAttribute in type.GetAttributes()) - { - INamedTypeSymbol attributeClass = typeAttribute.AttributeClass!; - - if (attributeClass.ToDisplayString() == TypeNames.NativeMarshallingAttribute) - { - return CreateNativeMarshallingInfo( - type, - (INamedTypeSymbol)typeAttribute.ConstructorArguments[0].Value!, - typeAttribute, - isMarshalUsingAttribute: false, - indirectionLevel, - parsedCountInfo, - useSiteAttributes, - inspectedElements, - ref maxIndirectionDepthUsed); - } - } - - // If the type doesn't have custom attributes that dictate marshalling, - // then consider the type itself. - if (TryCreateTypeBasedMarshallingInfo( - type, - parsedCountInfo, - indirectionLevel, - useSiteAttributes, - inspectedElements, - ref maxIndirectionDepthUsed, - out MarshallingInfo infoMaybe)) - { - return infoMaybe; - } - - return NoMarshallingInfo.Instance; - } - - private CountInfo CreateCountInfo(AttributeData marshalUsingData, ImmutableHashSet inspectedElements) - { - int? constSize = null; - string? elementName = null; - foreach (KeyValuePair arg in marshalUsingData.NamedArguments) - { - if (arg.Key == ManualTypeMarshallingHelper.MarshalUsingProperties.ConstantElementCount) - { - constSize = (int)arg.Value.Value!; - } - else if (arg.Key == ManualTypeMarshallingHelper.MarshalUsingProperties.CountElementName) - { - if (arg.Value.Value is null) - { - _diagnostics.ReportConfigurationNotSupported(marshalUsingData, ManualTypeMarshallingHelper.MarshalUsingProperties.CountElementName, "null"); - return NoCountInfo.Instance; - } - elementName = (string)arg.Value.Value!; - } - } - - if (constSize is not null && elementName is not null) - { - _diagnostics.ReportInvalidMarshallingAttributeInfo(marshalUsingData, nameof(SR.ConstantAndElementCountInfoDisallowed)); - } - else if (constSize is not null) - { - return new ConstSizeCountInfo(constSize.Value); - } - else if (elementName is not null) - { - if (inspectedElements.Contains(elementName)) - { - throw new CyclicalCountElementInfoException(inspectedElements, elementName); - } - - try - { - TypePositionInfo? elementInfo = CreateForElementName(elementName, inspectedElements.Add(elementName)); - if (elementInfo is null) - { - _diagnostics.ReportConfigurationNotSupported(marshalUsingData, ManualTypeMarshallingHelper.MarshalUsingProperties.CountElementName, elementName); - return NoCountInfo.Instance; - } - return new CountElementCountInfo(elementInfo); - } - // Specifically catch the exception when we're trying to inspect the element that started the cycle. - // This ensures that we've unwound the whole cycle so when we return NoCountInfo.Instance, there will be no cycles in the count info. - catch (CyclicalCountElementInfoException ex) when (ex.StartOfCycle == elementName) - { - _diagnostics.ReportInvalidMarshallingAttributeInfo(marshalUsingData, nameof(SR.CyclicalCountInfo), elementName); - return NoCountInfo.Instance; - } - } - - return NoCountInfo.Instance; - } - - private TypePositionInfo? CreateForParamIndex(AttributeData attrData, int paramIndex, ImmutableHashSet inspectedElements) - { - if (!(_contextSymbol is IMethodSymbol method && 0 <= paramIndex && paramIndex < method.Parameters.Length)) - { - return null; - } - IParameterSymbol param = method.Parameters[paramIndex]; - - if (inspectedElements.Contains(param.Name)) - { - throw new CyclicalCountElementInfoException(inspectedElements, param.Name); - } - - try - { - return TypePositionInfo.CreateForParameter( - param, - ParseMarshallingInfo(param.Type, param.GetAttributes(), inspectedElements.Add(param.Name)), _compilation) with - { ManagedIndex = paramIndex }; - } - // Specifically catch the exception when we're trying to inspect the element that started the cycle. - // This ensures that we've unwound the whole cycle so when we return, there will be no cycles in the count info. - catch (CyclicalCountElementInfoException ex) when (ex.StartOfCycle == param.Name) - { - _diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.CyclicalCountInfo), param.Name); - return SizeAndParamIndexInfo.UnspecifiedParam; - } - } - - private TypePositionInfo? CreateForElementName(string elementName, ImmutableHashSet inspectedElements) - { - if (_contextSymbol is IMethodSymbol method) - { - if (elementName == CountElementCountInfo.ReturnValueElementName) - { - return new TypePositionInfo( - ManagedTypeInfo.CreateTypeInfoForTypeSymbol(method.ReturnType), - ParseMarshallingInfo(method.ReturnType, method.GetReturnTypeAttributes(), inspectedElements)) with - { - ManagedIndex = TypePositionInfo.ReturnIndex - }; - } - - for (int i = 0; i < method.Parameters.Length; i++) - { - IParameterSymbol param = method.Parameters[i]; - if (param.Name == elementName) - { - return TypePositionInfo.CreateForParameter(param, ParseMarshallingInfo(param.Type, param.GetAttributes(), inspectedElements), _compilation) with { ManagedIndex = i }; - } - } - } - else if (_contextSymbol is INamedTypeSymbol) - { - // TODO: Handle when we create a struct marshalling generator - // Do we want to support CountElementName pointing to only fields, or properties as well? - // If only fields, how do we handle properties with generated backing fields? - } - - return null; - } - - private MarshallingInfo CreateInfoFromMarshalAs( - ITypeSymbol type, - AttributeData attrData, - ImmutableHashSet inspectedElements, - ref int maxIndirectionDepthUsed) - { - object unmanagedTypeObj = attrData.ConstructorArguments[0].Value!; - UnmanagedType unmanagedType = unmanagedTypeObj is short unmanagedTypeAsShort - ? (UnmanagedType)unmanagedTypeAsShort - : (UnmanagedType)unmanagedTypeObj; - if (!Enum.IsDefined(typeof(UnmanagedType), unmanagedType) - || unmanagedType == UnmanagedType.CustomMarshaler - || unmanagedType == UnmanagedType.SafeArray) - { - _diagnostics.ReportConfigurationNotSupported(attrData, nameof(UnmanagedType), unmanagedType.ToString()); - } - - bool isArrayType = unmanagedType == UnmanagedType.LPArray || unmanagedType == UnmanagedType.ByValArray; - UnmanagedType elementUnmanagedType = (UnmanagedType)SizeAndParamIndexInfo.UnspecifiedConstSize; - SizeAndParamIndexInfo arraySizeInfo = SizeAndParamIndexInfo.Unspecified; - - // All other data on attribute is defined as NamedArguments. - foreach (KeyValuePair namedArg in attrData.NamedArguments) - { - switch (namedArg.Key) - { - default: - Debug.Fail($"An unknown member was found on {nameof(MarshalAsAttribute)}"); - continue; - case nameof(MarshalAsAttribute.SafeArraySubType): - case nameof(MarshalAsAttribute.SafeArrayUserDefinedSubType): - case nameof(MarshalAsAttribute.IidParameterIndex): - case nameof(MarshalAsAttribute.MarshalTypeRef): - case nameof(MarshalAsAttribute.MarshalType): - case nameof(MarshalAsAttribute.MarshalCookie): - _diagnostics.ReportConfigurationNotSupported(attrData, $"{attrData.AttributeClass!.Name}{Type.Delimiter}{namedArg.Key}"); - break; - case nameof(MarshalAsAttribute.ArraySubType): - if (!isArrayType) - { - _diagnostics.ReportConfigurationNotSupported(attrData, $"{attrData.AttributeClass!.Name}{Type.Delimiter}{namedArg.Key}"); - } - elementUnmanagedType = (UnmanagedType)namedArg.Value.Value!; - break; - case nameof(MarshalAsAttribute.SizeConst): - if (!isArrayType) - { - _diagnostics.ReportConfigurationNotSupported(attrData, $"{attrData.AttributeClass!.Name}{Type.Delimiter}{namedArg.Key}"); - } - arraySizeInfo = arraySizeInfo with { ConstSize = (int)namedArg.Value.Value! }; - break; - case nameof(MarshalAsAttribute.SizeParamIndex): - if (!isArrayType) - { - _diagnostics.ReportConfigurationNotSupported(attrData, $"{attrData.AttributeClass!.Name}{Type.Delimiter}{namedArg.Key}"); - } - TypePositionInfo? paramIndexInfo = CreateForParamIndex(attrData, (short)namedArg.Value.Value!, inspectedElements); - - if (paramIndexInfo is null) - { - _diagnostics.ReportConfigurationNotSupported(attrData, nameof(MarshalAsAttribute.SizeParamIndex), namedArg.Value.Value.ToString()); - } - arraySizeInfo = arraySizeInfo with { ParamAtIndex = paramIndexInfo }; - break; - } - } - - if (isArrayType) - { - if (type is not IArrayTypeSymbol { ElementType: ITypeSymbol elementType }) - { - _diagnostics.ReportConfigurationNotSupported(attrData, nameof(UnmanagedType), unmanagedType.ToString()); - return NoMarshallingInfo.Instance; - } - - MarshallingInfo elementMarshallingInfo = NoMarshallingInfo.Instance; - if (elementUnmanagedType != (UnmanagedType)SizeAndParamIndexInfo.UnspecifiedConstSize) - { - elementMarshallingInfo = elementType.SpecialType == SpecialType.System_String - ? CreateStringMarshallingInfo(elementType, elementUnmanagedType) - : new MarshalAsInfo(elementUnmanagedType, _defaultInfo.CharEncoding); - } - else - { - maxIndirectionDepthUsed = 1; - elementMarshallingInfo = GetMarshallingInfo(elementType, new Dictionary(), 1, ImmutableHashSet.Empty, ref maxIndirectionDepthUsed); - } - - return CreateArrayMarshallingInfo(type, elementType, arraySizeInfo, elementMarshallingInfo); - } - - if (type.SpecialType == SpecialType.System_String) - { - return CreateStringMarshallingInfo(type, unmanagedType); - } - - return new MarshalAsInfo(unmanagedType, _defaultInfo.CharEncoding); - } - - private MarshallingInfo CreateNativeMarshallingInfo( - ITypeSymbol type, - INamedTypeSymbol entryPointType, - AttributeData attrData, - bool isMarshalUsingAttribute, - int indirectionLevel, - CountInfo parsedCountInfo, - Dictionary useSiteAttributes, - ImmutableHashSet inspectedElements, - ref int maxIndirectionDepthUsed) - { - if (!ManualTypeMarshallingHelper.HasEntryPointMarshallerAttribute(entryPointType)) - { - return NoMarshallingInfo.Instance; - } - - if (!(entryPointType.IsStatic && entryPointType.TypeKind == TypeKind.Class) - && entryPointType.TypeKind != TypeKind.Struct) - { - _diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.MarshallerTypeMustBeStaticClassOrStruct), entryPointType.ToDisplayString(), type.ToDisplayString()); - return NoMarshallingInfo.Instance; - } - - ManagedTypeInfo entryPointTypeInfo = ManagedTypeInfo.CreateTypeInfoForTypeSymbol(entryPointType); - - bool isLinearCollectionMarshalling = ManualTypeMarshallingHelper.IsLinearCollectionEntryPoint(entryPointType); - if (isLinearCollectionMarshalling) - { - // Update the entry point type with the type arguments based on the managed type - if (type is IArrayTypeSymbol arrayManagedType) - { - if (entryPointType.Arity != 2) - { - _diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.MarshallerEntryPointTypeMustMatchArity), entryPointType.ToDisplayString(), type.ToDisplayString()); - return NoMarshallingInfo.Instance; - } - - entryPointType = entryPointType.ConstructedFrom.Construct( - arrayManagedType.ElementType, - entryPointType.TypeArguments.Last()); - } - else if (type is INamedTypeSymbol namedManagedCollectionType && entryPointType.IsUnboundGenericType) - { - if (!ManualTypeMarshallingHelper.TryResolveEntryPointType( - namedManagedCollectionType, - entryPointType, - isLinearCollectionMarshalling, - (type, entryPointType) => _diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.MarshallerEntryPointTypeMustMatchArity), entryPointType.ToDisplayString(), type.ToDisplayString()), - out ITypeSymbol resolvedEntryPointType)) - { - return NoMarshallingInfo.Instance; - } - - entryPointType = (INamedTypeSymbol)resolvedEntryPointType; - } - else - { - _diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.MarshallerEntryPointTypeMustMatchArity), entryPointType.ToDisplayString(), type.ToDisplayString()); - return NoMarshallingInfo.Instance; - } - - int maxIndirectionDepthUsedLocal = maxIndirectionDepthUsed; - Func getMarshallingInfoForElement = (ITypeSymbol elementType) => GetMarshallingInfo(elementType, new Dictionary(), 1, ImmutableHashSet.Empty, ref maxIndirectionDepthUsedLocal); - if (ManualTypeMarshallingHelper.TryGetLinearCollectionMarshallersFromEntryType(entryPointType, type, _compilation, getMarshallingInfoForElement, out CustomTypeMarshallers? collectionMarshallers)) - { - maxIndirectionDepthUsed = maxIndirectionDepthUsedLocal; - return new NativeLinearCollectionMarshallingInfo( - entryPointTypeInfo, - collectionMarshallers.Value, - parsedCountInfo, - ManagedTypeInfo.CreateTypeInfoForTypeSymbol(entryPointType.TypeParameters.Last())); - } - return NoMarshallingInfo.Instance; - } - - if (type is INamedTypeSymbol namedManagedType && entryPointType.IsUnboundGenericType) - { - if (!ManualTypeMarshallingHelper.TryResolveEntryPointType( - namedManagedType, - entryPointType, - isLinearCollectionMarshalling, - (type, entryPointType) => _diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.MarshallerEntryPointTypeMustMatchArity), entryPointType.ToDisplayString(), type.ToDisplayString()), - out ITypeSymbol resolvedEntryPointType)) - { - return NoMarshallingInfo.Instance; - } - - entryPointType = (INamedTypeSymbol)resolvedEntryPointType; - } - - if (ManualTypeMarshallingHelper.TryGetValueMarshallersFromEntryType(entryPointType, type, _compilation, out CustomTypeMarshallers? marshallers)) - { - return new NativeMarshallingAttributeInfo(entryPointTypeInfo, marshallers.Value); - } - return NoMarshallingInfo.Instance; - } - - private bool TryCreateTypeBasedMarshallingInfo( - ITypeSymbol type, - CountInfo parsedCountInfo, - int indirectionLevel, - Dictionary useSiteAttributes, - ImmutableHashSet inspectedElements, - ref int maxIndirectionDepthUsed, - out MarshallingInfo marshallingInfo) - { - // Check for an implicit SafeHandle conversion. - // The SafeHandle type might not be defined if we're using one of the test CoreLib implementations used for NativeAOT. - ITypeSymbol? safeHandleType = _compilation.GetTypeByMetadataName(TypeNames.System_Runtime_InteropServices_SafeHandle); - if (safeHandleType is not null) - { - CodeAnalysis.Operations.CommonConversion conversion = _compilation.ClassifyCommonConversion(type, safeHandleType); - if (conversion.Exists - && conversion.IsImplicit - && (conversion.IsReference || conversion.IsIdentity)) - { - bool hasAccessibleDefaultConstructor = false; - if (type is INamedTypeSymbol named && !named.IsAbstract && named.InstanceConstructors.Length > 0) - { - foreach (IMethodSymbol ctor in named.InstanceConstructors) - { - if (ctor.Parameters.Length == 0) - { - hasAccessibleDefaultConstructor = _compilation.IsSymbolAccessibleWithin(ctor, _contextSymbol.ContainingType); - break; - } - } - } - marshallingInfo = new SafeHandleMarshallingInfo(hasAccessibleDefaultConstructor, type.IsAbstract); - return true; - } - } - - if (type is IArrayTypeSymbol { ElementType: ITypeSymbol elementType }) - { - MarshallingInfo elementMarshallingInfo = GetMarshallingInfo(elementType, useSiteAttributes, indirectionLevel + 1, inspectedElements, ref maxIndirectionDepthUsed); - marshallingInfo = CreateArrayMarshallingInfo(type, elementType, parsedCountInfo, elementMarshallingInfo); - return true; - } - - // No marshalling info was computed, but a character encoding was provided. - // If the type is a character or string then pass on these details. - if (type.SpecialType == SpecialType.System_Char && _defaultInfo.CharEncoding != CharEncoding.Undefined) - { - marshallingInfo = new MarshallingInfoStringSupport(_defaultInfo.CharEncoding); - return true; - } - - if (type.SpecialType == SpecialType.System_String && _defaultInfo.CharEncoding != CharEncoding.Undefined) - { - if (_defaultInfo.CharEncoding == CharEncoding.Custom) - { - if (_defaultInfo.StringMarshallingCustomType is not null) - { - AttributeData attrData = _contextSymbol is IMethodSymbol - ? _contextSymbol.GetAttributes().FirstOrDefault(a => a.AttributeClass.ToDisplayString() == TypeNames.LibraryImportAttribute) - : default; - marshallingInfo = CreateNativeMarshallingInfo(type, _defaultInfo.StringMarshallingCustomType, attrData, true, indirectionLevel, parsedCountInfo, useSiteAttributes, inspectedElements, ref maxIndirectionDepthUsed); - return true; - } - } - else - { - marshallingInfo = _defaultInfo.CharEncoding switch - { - CharEncoding.Utf16 => CreateStringMarshallingInfo(type, TypeNames.Utf16StringMarshaller), - CharEncoding.Utf8 => CreateStringMarshallingInfo(type, TypeNames.Utf8StringMarshaller), - _ => throw new InvalidOperationException() - }; - - return true; - } - - marshallingInfo = new MarshallingInfoStringSupport(_defaultInfo.CharEncoding); - return true; - } - - - if (type.SpecialType == SpecialType.System_Boolean) - { - // We explicitly don't support marshalling bool without any marshalling info - // as treating bool as a non-normalized 1-byte value is generally not a good default. - // Additionally, that default is different than the runtime marshalling, so by explicitly - // blocking bool marshalling without additional info, we make it a little easier - // to transition by explicitly notifying people of changing behavior. - marshallingInfo = NoMarshallingInfo.Instance; - return false; - } - - if (type is INamedTypeSymbol { IsUnmanagedType: true } unmanagedType - && unmanagedType.IsConsideredBlittable()) - { - marshallingInfo = GetBlittableMarshallingInfo(type); - return true; - } - - marshallingInfo = NoMarshallingInfo.Instance; - return false; - } - - private MarshallingInfo CreateArrayMarshallingInfo( - ITypeSymbol managedType, - ITypeSymbol elementType, - CountInfo countInfo, - MarshallingInfo elementMarshallingInfo) - { - ITypeSymbol typeArgumentToInsert = elementType; - INamedTypeSymbol? arrayMarshaller; - if (elementType is IPointerTypeSymbol { PointedAtType: ITypeSymbol pointedAt }) - { - arrayMarshaller = _compilation.GetTypeByMetadataName(TypeNames.System_Runtime_InteropServices_PointerArrayMarshaller_Metadata); - typeArgumentToInsert = pointedAt; - } - else - { - arrayMarshaller = _compilation.GetTypeByMetadataName(TypeNames.System_Runtime_InteropServices_ArrayMarshaller_Metadata); - } - - if (arrayMarshaller is null) - { - // If the array marshaler type is not available, then we cannot marshal arrays but indicate it is missing. - return new MissingSupportCollectionMarshallingInfo(countInfo, elementMarshallingInfo); - } - - if (ManualTypeMarshallingHelper.HasEntryPointMarshallerAttribute(arrayMarshaller) - && ManualTypeMarshallingHelper.IsLinearCollectionEntryPoint(arrayMarshaller)) - { - arrayMarshaller = arrayMarshaller.Construct( - typeArgumentToInsert, - arrayMarshaller.TypeArguments.Last()); - - Func getMarshallingInfoForElement = (ITypeSymbol elementType) => elementMarshallingInfo; - if (ManualTypeMarshallingHelper.TryGetLinearCollectionMarshallersFromEntryType(arrayMarshaller, managedType, _compilation, getMarshallingInfoForElement, out CustomTypeMarshallers? marshallers)) - { - return new NativeLinearCollectionMarshallingInfo( - ManagedTypeInfo.CreateTypeInfoForTypeSymbol(arrayMarshaller), - marshallers.Value, - countInfo, - ManagedTypeInfo.CreateTypeInfoForTypeSymbol(arrayMarshaller.TypeParameters.Last())); - } - } - - Debug.WriteLine("Default marshallers for arrays should be a valid shape."); - return NoMarshallingInfo.Instance; - } - - private MarshallingInfo CreateStringMarshallingInfo( - ITypeSymbol type, - UnmanagedType unmanagedType) - { - string? marshallerName = unmanagedType switch - { - UnmanagedType.BStr => TypeNames.BStrStringMarshaller, - UnmanagedType.LPStr => TypeNames.AnsiStringMarshaller, - UnmanagedType.LPTStr or UnmanagedType.LPWStr => TypeNames.Utf16StringMarshaller, - MarshalAsInfo.UnmanagedType_LPUTF8Str => TypeNames.Utf8StringMarshaller, - _ => null - }; - - if (marshallerName is null) - return new MarshalAsInfo(unmanagedType, _defaultInfo.CharEncoding); - - return CreateStringMarshallingInfo(type, marshallerName); - } - - private MarshallingInfo CreateStringMarshallingInfo( - ITypeSymbol type, - string marshallerName) - { - INamedTypeSymbol? stringMarshaller = _compilation.GetTypeByMetadataName(marshallerName); - if (stringMarshaller is null) - return new MissingSupportMarshallingInfo(); - - if (ManualTypeMarshallingHelper.HasEntryPointMarshallerAttribute(stringMarshaller)) - { - if (ManualTypeMarshallingHelper.TryGetValueMarshallersFromEntryType(stringMarshaller, type, _compilation, out CustomTypeMarshallers? marshallers)) - { - return new NativeMarshallingAttributeInfo( - EntryPointType: ManagedTypeInfo.CreateTypeInfoForTypeSymbol(stringMarshaller), - Marshallers: marshallers.Value); - } - } - - return new MissingSupportMarshallingInfo(); - } - - private MarshallingInfo GetBlittableMarshallingInfo(ITypeSymbol type) - { - if (type.TypeKind is TypeKind.Enum or TypeKind.Pointer or TypeKind.FunctionPointer - || type.SpecialType.IsAlwaysBlittable()) - { - // Treat primitive types and enums as having no marshalling info. - // They are supported in configurations where runtime marshalling is enabled. - return NoMarshallingInfo.Instance; - } - else if (_compilation.GetTypeByMetadataName(TypeNames.System_Runtime_CompilerServices_DisableRuntimeMarshallingAttribute) is null) - { - // If runtime marshalling cannot be disabled, then treat this as a "missing support" scenario so we can gracefully fall back to using the forwarder downlevel. - return new MissingSupportMarshallingInfo(); - } - else - { - return new UnmanagedBlittableMarshallingInfo(type.IsStrictlyBlittable()); - } - } - - private bool TryGetAttributeIndirectionLevel(AttributeData attrData, out int indirectionLevel) - { - if (SymbolEqualityComparer.Default.Equals(attrData.AttributeClass, _marshalAsAttribute)) - { - indirectionLevel = 0; - return true; - } - - if (!SymbolEqualityComparer.Default.Equals(attrData.AttributeClass, _marshalUsingAttribute)) - { - indirectionLevel = 0; - return false; - } - - foreach (KeyValuePair arg in attrData.NamedArguments) - { - if (arg.Key == ManualTypeMarshallingHelper.MarshalUsingProperties.ElementIndirectionDepth) - { - indirectionLevel = (int)arg.Value.Value!; - return true; - } - } - indirectionLevel = 0; - return true; - } - - private sealed class CyclicalCountElementInfoException : Exception - { - public CyclicalCountElementInfoException(ImmutableHashSet elementsInCycle, string startOfCycle) - { - ElementsInCycle = elementsInCycle; - StartOfCycle = startOfCycle; - } - - public ImmutableHashSet ElementsInCycle { get; } - - public string StartOfCycle { get; } - } - } } diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallingInfoParser.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallingInfoParser.cs new file mode 100644 index 00000000000000..410166893a514a --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallingInfoParser.cs @@ -0,0 +1,367 @@ +// 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.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + /// + /// Information from a marshalling attribute that can only be provided if the attribute is at the usage site. + /// + /// The indirection depth that the info applies to. + /// Any collection count information provided. + /// The original attribute data. + public sealed record UseSiteAttributeData(int IndirectionDepth, CountInfo CountInfo, AttributeData AttributeData); + + /// + /// A callback to get the marshalling info for a given type at the provided indirection depth with the provided attributes at its usage site. + /// + /// The managed type to get marshalling info for + /// The attributes at the use site + /// The target indirection level + /// Marshalling info for provided information. + public delegate MarshallingInfo GetMarshallingInfoCallback(ITypeSymbol type, UseSiteAttributeProvider useSiteAttributes, int indirectionDepth); + + /// + /// A parser for an attribute used at the marshalling site, such as a parameter or return value attribute. + /// + public interface IUseSiteAttributeParser + { + /// + /// Whether or not the parser can parse an attribute of the provided type. + /// + /// The attribute type + /// true if the parser can parse an attribute of the provided type; otherwise false + bool CanParseAttributeType(INamedTypeSymbol attributeType); + + /// + /// Parse the use-site information out of the provided attribute. + /// + /// The attribute data to parse. + /// The provider for information about other elements. This is used to retrieve information about other parameters that might be referenced by any count information. + /// A callback to provide to the when retrieving additional information. + /// The information about the attribute at the use site. + UseSiteAttributeData ParseAttribute(AttributeData attributeData, IElementInfoProvider elementInfoProvider, GetMarshallingInfoCallback marshallingInfoCallback); + } + + /// + /// A parser for an attribute that provides information about which marshaller to use. + /// + public interface IMarshallingInfoAttributeParser + { + /// + /// Whether or not the parser can parse an attribute of the provided type. + /// + /// The attribute type + /// true if the parser can parse an attribute of the provided type; otherwise false + bool CanParseAttributeType(INamedTypeSymbol attributeType); + + /// + /// Parse the attribute into marshalling information + /// + /// The attribute to parse + /// The managed type + /// The current indirection depth + /// Attributes provided at the usage site, such as for count information + /// A callback to get marshalling info for nested elements, in the case of a collection of collections. + /// Marshalling information parsed from the attribute, or null if no information could be parsed from the attribute + MarshallingInfo? ParseAttribute(AttributeData attributeData, ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback); + } + + /// + /// A provider of marshalling info based only on the managed type any any previously parsed use-site attribute information + /// + public interface ITypeBasedMarshallingInfoProvider + { + /// + /// Whether or not the provider can provide marshalling info for the given managed type. + /// + /// The managed type + /// true if the provider can provide info for the provided type; otherwise false + bool CanProvideMarshallingInfoForType(ITypeSymbol type); + /// + /// Get marshalling info for the provided type at the given indirection level. + /// + /// The managed type + /// The current indirection depth + /// Attributes provided at the usage site, such as for count information + /// A callback to get marshalling info for nested elements, in the case of a collection of collections. + /// Marshalling information for the provided type + MarshallingInfo GetMarshallingInfo(ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback); + } + + /// + /// A provider of TypePositionInfo instances for other elements in the current signature, such as parameters or return values. + /// + public interface IElementInfoProvider + { + /// + /// Get the name for a given index. + /// + /// The index + /// The name associated with the provided index, or if the index does not correspond to an element. + string FindNameForParamIndex(int paramIndex); + /// + /// Get a instance for the given element name. + /// + /// The attribute to report diagnostics on. + /// The element name to retrieve a instance for. + /// A callback to retrieve marshalling info to put into the . + /// The to pass to the . + /// The produced info. + /// true if a instance could be created for the type; otherwise false + bool TryGetInfoForElementName(AttributeData attrData, string elementName, GetMarshallingInfoCallback marshallingInfoCallback, IElementInfoProvider rootProvider, out TypePositionInfo info); + /// + /// Get a instance for the given element index. + /// + /// The attribute to report diagnostics on. + /// The element index to retrieve a instance for. + /// A callback to retrieve marshalling info to put into the . + /// The to pass to the . + /// The produced info. + /// true if a instance could be created for the type; otherwise false + bool TryGetInfoForParamIndex(AttributeData attrData, int paramIndex, GetMarshallingInfoCallback marshallingInfoCallback, IElementInfoProvider rootProvider, out TypePositionInfo info); + } + + /// + /// Convenience extension methods for . + /// + public static class ElementInfoProviderExtensions + { + /// + /// Get a instance for the given element name. + /// + /// The attribute to report diagnostics on. + /// The element name to retrieve a instance for. + /// A callback to retrieve marshalling info to put into the . + /// The produced info. + /// true if a instance could be created for the type; otherwise false + public static bool TryGetInfoForElementName(this IElementInfoProvider provider, AttributeData attrData, string elementName, GetMarshallingInfoCallback marshallingInfoCallback, out TypePositionInfo info) + { + return provider.TryGetInfoForElementName(attrData, elementName, marshallingInfoCallback, provider, out info); + } + + /// + /// Get a instance for the given element index. + /// + /// The attribute to report diagnostics on. + /// The element index to retrieve a instance for. + /// A callback to retrieve marshalling info to put into the . + /// The produced info. + /// true if a instance could be created for the type; otherwise false + public static bool TryGetInfoForParamIndex(this IElementInfoProvider provider, AttributeData attrData, int paramIndex, GetMarshallingInfoCallback marshallingInfoCallback, out TypePositionInfo info) + { + return provider.TryGetInfoForParamIndex(attrData, paramIndex, marshallingInfoCallback, provider, out info); + } + } + + /// + /// Overall parser for all marshalling info. + /// + /// + /// This type combines the provided parsers to enable parsing marshalling information from a single call. + /// For a given managed type and use site attributes, it will parse marshalling information in the following order: + /// + /// Parse attributes provided at the usage site for use-site-only information. + /// Parse attributes provided at the usage site for marshalling information. + /// If no marshalling information has been found yet, parse attributes provided at the definition of the managed type. + /// If no marshalling information has been found yet, generate marshalling information for the managed type itself. + /// + /// + public sealed class MarshallingInfoParser + { + private readonly IGeneratorDiagnostics _diagnostics; + private readonly IElementInfoProvider _elementInfoProvider; + private readonly ImmutableArray _useSiteMarshallingAttributeParsers; + private readonly ImmutableArray _marshallingAttributeParsers; + private readonly ImmutableArray _typeBasedMarshallingInfoProviders; + + /// + /// Construct a new . + /// + /// The diagnostics sink to report all diagnostics to. + /// An to retrieve information about other elements than the current element when parsing. + /// Parsers for retrieving use-site-only information from attributes. + /// Parsers for retrieving marshalling information from attributes and the managed type. + /// Parsers for retrieving marshalling information from the managed type only. + public MarshallingInfoParser( + IGeneratorDiagnostics diagnostics, + IElementInfoProvider elementInfoProvider, + ImmutableArray useSiteMarshallingAttributeParsers, + ImmutableArray marshallingAttributeParsers, + ImmutableArray typeBasedMarshallingInfoProviders) + { + _diagnostics = diagnostics; + // Always support cycle detection. Otherwise we can get stack-overflows, which does not provide a good dev experience for any customer scenario. + _elementInfoProvider = new CycleDetectingElementInfoProvider(elementInfoProvider, diagnostics); + _useSiteMarshallingAttributeParsers = useSiteMarshallingAttributeParsers; + _marshallingAttributeParsers = marshallingAttributeParsers; + _typeBasedMarshallingInfoProviders = typeBasedMarshallingInfoProviders; + } + + /// + /// Parse the marshalling info for the provided managed type and attributes at the usage site. + /// + /// The managed type + /// All attributes specified at the usage site + /// The parsed marshalling information + public MarshallingInfo ParseMarshallingInfo( + ITypeSymbol managedType, + IEnumerable useSiteAttributes) + { + UseSiteAttributeProvider useSiteAttributeProvider = new UseSiteAttributeProvider(_useSiteMarshallingAttributeParsers, useSiteAttributes, _elementInfoProvider, _diagnostics, GetMarshallingInfo); + + MarshallingInfo info = GetMarshallingInfo( + managedType, + useSiteAttributeProvider, + indirectionDepth: 0); + + useSiteAttributeProvider.OnAttributeUsageFinished(); + return info; + } + + private MarshallingInfo GetMarshallingInfo( + ITypeSymbol type, + UseSiteAttributeProvider useSiteAttributes, + int indirectionDepth) + { + if (useSiteAttributes.TryGetUseSiteAttributeInfo(indirectionDepth, out UseSiteAttributeData useSiteAttribute)) + { + if (GetMarshallingInfoForAttribute(useSiteAttribute.AttributeData, type, indirectionDepth, useSiteAttributes, GetMarshallingInfo) is MarshallingInfo marshallingInfo) + { + return marshallingInfo; + } + } + + // If we aren't overriding the marshalling at usage time, + // then fall back to the information on the element type itself. + foreach (AttributeData typeAttribute in type.GetAttributes()) + { + if (GetMarshallingInfoForAttribute(typeAttribute, type, indirectionDepth, useSiteAttributes, GetMarshallingInfo) is MarshallingInfo marshallingInfo) + { + return marshallingInfo; + } + } + + // If the type doesn't have custom attributes that dictate marshalling, + // then consider the type itself. + return GetMarshallingInfoForType(type, indirectionDepth, useSiteAttributes, GetMarshallingInfo) ?? NoMarshallingInfo.Instance; + } + + private MarshallingInfo? GetMarshallingInfoForAttribute(AttributeData attribute, ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + foreach (var parser in _marshallingAttributeParsers) + { + // Automatically ignore invalid attributes. + // The compiler will already error on them. + if (attribute.AttributeConstructor is not null && parser.CanParseAttributeType(attribute.AttributeClass)) + { + return parser.ParseAttribute(attribute, type, indirectionDepth, useSiteAttributes, marshallingInfoCallback); + } + } + return null; + } + + private MarshallingInfo? GetMarshallingInfoForType(ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + foreach (var parser in _typeBasedMarshallingInfoProviders) + { + if (parser.CanProvideMarshallingInfoForType(type)) + { + return parser.GetMarshallingInfo(type, indirectionDepth, useSiteAttributes, marshallingInfoCallback); + } + } + return null; + } + } + + /// + /// Wraps another with support to detect infinite cycles in marshalling info (i.e. count information that refers to other elements that refer to the original element). + /// + internal sealed class CycleDetectingElementInfoProvider : IElementInfoProvider + { + private ImmutableHashSet _activeInspectingElements = ImmutableHashSet.Empty; + private readonly IElementInfoProvider _innerProvider; + private readonly IGeneratorDiagnostics _diagnostics; + + public CycleDetectingElementInfoProvider(IElementInfoProvider innerProvider, IGeneratorDiagnostics diagnostics) + { + _innerProvider = innerProvider; + _diagnostics = diagnostics; + } + + public string FindNameForParamIndex(int paramIndex) => _innerProvider.FindNameForParamIndex(paramIndex); + public bool TryGetInfoForElementName(AttributeData attrData, string elementName, GetMarshallingInfoCallback marshallingInfoCallback, IElementInfoProvider rootProvider, [NotNullWhen(true)] out TypePositionInfo? info) + { + ImmutableHashSet inspectedElements = _activeInspectingElements; + if (inspectedElements.Contains(elementName)) + { + throw new CyclicalElementInfoException(inspectedElements, elementName); + } + try + { + _activeInspectingElements = inspectedElements.Add(elementName); + return _innerProvider.TryGetInfoForElementName(attrData, elementName, marshallingInfoCallback, rootProvider, out info); + } + // Specifically catch the exception when we're trying to inspect the element that started the cycle. + // This ensures that we've unwound the whole cycle so when we return, there will be no cycles in the count info. + catch (CyclicalElementInfoException ex) when (ex.StartOfCycle == elementName) + { + _diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.CyclicalCountInfo), elementName); + // Create a dummy value for the invalid marshalling. We're already in an error state, so try to not report extraneous diagnostics. + info = new TypePositionInfo(SpecialTypeInfo.Void, NoMarshallingInfo.Instance); + return true; + } + finally + { + _activeInspectingElements = inspectedElements; + } + } + + public bool TryGetInfoForParamIndex(AttributeData attrData, int paramIndex, GetMarshallingInfoCallback marshallingInfoCallback, IElementInfoProvider rootProvider, [NotNullWhen(true)] out TypePositionInfo? info) + { + ImmutableHashSet inspectedElements = _activeInspectingElements; + string paramName = _innerProvider.FindNameForParamIndex(paramIndex); + if (paramName is not null && inspectedElements.Contains(paramName)) + { + throw new CyclicalElementInfoException(inspectedElements, paramName); + } + + try + { + _activeInspectingElements = inspectedElements.Add(paramName); + return _innerProvider.TryGetInfoForParamIndex(attrData, paramIndex, marshallingInfoCallback, rootProvider, out info); + } + // Specifically catch the exception when we're trying to inspect the element that started the cycle. + // This ensures that we've unwound the whole cycle so when we return, there will be no cycles in the count info. + catch (CyclicalElementInfoException ex) when (ex.StartOfCycle == paramName) + { + _diagnostics.ReportInvalidMarshallingAttributeInfo(attrData, nameof(SR.CyclicalCountInfo), paramName); + // Create a dummy value for the invalid marshalling. We're already in an error state, so try to not report extraneous diagnostics. + info = new TypePositionInfo(SpecialTypeInfo.Void, NoMarshallingInfo.Instance); + return true; + } + finally + { + _activeInspectingElements = inspectedElements; + } + } + + private sealed class CyclicalElementInfoException : Exception + { + public CyclicalElementInfoException(ImmutableHashSet elementsInCycle, string startOfCycle) + { + ElementsInCycle = elementsInCycle; + StartOfCycle = startOfCycle; + } + + public ImmutableHashSet ElementsInCycle { get; } + + public string StartOfCycle { get; } + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MethodSignatureElementInfoProvider.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MethodSignatureElementInfoProvider.cs new file mode 100644 index 00000000000000..e00eef6d2c0aea --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MethodSignatureElementInfoProvider.cs @@ -0,0 +1,78 @@ +// 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.Collections.Immutable; +using System.Text; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + public sealed class MethodSignatureElementInfoProvider : IElementInfoProvider + { + private readonly Compilation _compilation; + private readonly IGeneratorDiagnostics _generatorDiagnostics; + private readonly IMethodSymbol _method; + private readonly ImmutableArray _useSiteAttributeParsers; + + public MethodSignatureElementInfoProvider(Compilation compilation, IGeneratorDiagnostics generatorDiagnostics, IMethodSymbol method, ImmutableArray useSiteAttributeParsers) + { + _compilation = compilation; + _generatorDiagnostics = generatorDiagnostics; + _method = method; + _useSiteAttributeParsers = useSiteAttributeParsers; + } + + public string FindNameForParamIndex(int paramIndex) => paramIndex >= _method.Parameters.Length ? string.Empty : _method.Parameters[paramIndex].Name; + + public bool TryGetInfoForElementName(AttributeData attrData, string elementName, GetMarshallingInfoCallback marshallingInfoCallback, IElementInfoProvider rootProvider, out TypePositionInfo info) + { + if (elementName == CountElementCountInfo.ReturnValueElementName) + { + info = new TypePositionInfo( + ManagedTypeInfo.CreateTypeInfoForTypeSymbol(_method.ReturnType), + marshallingInfoCallback(_method.ReturnType, new UseSiteAttributeProvider(_useSiteAttributeParsers, _method.GetReturnTypeAttributes(), rootProvider, _generatorDiagnostics, marshallingInfoCallback), 0)) with + { + ManagedIndex = TypePositionInfo.ReturnIndex + }; + return true; + } + + for (int i = 0; i < _method.Parameters.Length; i++) + { + IParameterSymbol param = _method.Parameters[i]; + if (param.Name == elementName) + { + info = TypePositionInfo.CreateForParameter( + param, + marshallingInfoCallback(param.Type, new UseSiteAttributeProvider(_useSiteAttributeParsers, param.GetAttributes(), rootProvider, _generatorDiagnostics, marshallingInfoCallback), 0), _compilation) with + { + ManagedIndex = i + }; + return true; + } + } + info = null; + return false; + } + + public bool TryGetInfoForParamIndex(AttributeData attrData, int paramIndex, GetMarshallingInfoCallback marshallingInfoCallback, IElementInfoProvider rootProvider, out TypePositionInfo info) + { + if (paramIndex >= _method.Parameters.Length) + { + info = null; + return false; + } + IParameterSymbol param = _method.Parameters[paramIndex]; + + info = TypePositionInfo.CreateForParameter( + param, + marshallingInfoCallback(param.Type, new UseSiteAttributeProvider(_useSiteAttributeParsers, param.GetAttributes(), rootProvider, _generatorDiagnostics, marshallingInfoCallback), 0), _compilation) with + { + ManagedIndex = paramIndex + }; + return true; + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/NativeMarshallingAttributeParser.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/NativeMarshallingAttributeParser.cs new file mode 100644 index 00000000000000..c51116029143e7 --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/NativeMarshallingAttributeParser.cs @@ -0,0 +1,49 @@ +// 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 Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + public sealed class NativeMarshallingAttributeParser : IMarshallingInfoAttributeParser + { + private readonly Compilation _compilation; + private readonly IGeneratorDiagnostics _diagnostics; + + public NativeMarshallingAttributeParser(Compilation compilation, IGeneratorDiagnostics diagnostics) + { + _compilation = compilation; + _diagnostics = diagnostics; + } + + public bool CanParseAttributeType(INamedTypeSymbol attributeType) => attributeType.ToDisplayString() == TypeNames.NativeMarshallingAttribute; + + public MarshallingInfo? ParseAttribute(AttributeData attributeData, ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + Debug.Assert(attributeData.AttributeClass!.ToDisplayString() == TypeNames.NativeMarshallingAttribute); + CountInfo countInfo = NoCountInfo.Instance; + if (useSiteAttributes.TryGetUseSiteAttributeInfo(indirectionDepth, out var useSiteInfo)) + { + countInfo = useSiteInfo.CountInfo; + } + + if (attributeData.ConstructorArguments[0].Value is not INamedTypeSymbol entryPointType) + { + return NoMarshallingInfo.Instance; + } + + return CustomMarshallingInfoHelper.CreateNativeMarshallingInfo( + type, + entryPointType, + attributeData, + useSiteAttributes, + marshallingInfoCallback, + indirectionDepth, + countInfo, + _diagnostics, + _compilation + ); + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/SafeHandleMarshallingInfoProvider.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/SafeHandleMarshallingInfoProvider.cs new file mode 100644 index 00000000000000..0309793096e7c4 --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/SafeHandleMarshallingInfoProvider.cs @@ -0,0 +1,65 @@ +// 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.Text; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + /// + /// The type of the element is a SafeHandle-derived type with no marshalling attributes. + /// + public sealed record SafeHandleMarshallingInfo(bool AccessibleDefaultConstructor, bool IsAbstract) : MarshallingInfo; + + /// + /// This class supports generating marshalling info for SafeHandle-derived types. + /// + public sealed class SafeHandleMarshallingInfoProvider : ITypeBasedMarshallingInfoProvider + { + private readonly Compilation _compilation; + private readonly ITypeSymbol _containingScope; + + public SafeHandleMarshallingInfoProvider(Compilation compilation, ITypeSymbol containingScope) + { + _compilation = compilation; + _containingScope = containingScope; + } + + public bool CanProvideMarshallingInfoForType(ITypeSymbol type) + { + // Check for an implicit SafeHandle conversion. + // The SafeHandle type might not be defined if we're using one of the test CoreLib implementations used for NativeAOT. + ITypeSymbol? safeHandleType = _compilation.GetTypeByMetadataName(TypeNames.System_Runtime_InteropServices_SafeHandle); + if (safeHandleType is not null) + { + CodeAnalysis.Operations.CommonConversion conversion = _compilation.ClassifyCommonConversion(type, safeHandleType); + if (conversion.Exists + && conversion.IsImplicit + && (conversion.IsReference || conversion.IsIdentity)) + { + return true; + } + } + return false; + } + + public MarshallingInfo GetMarshallingInfo(ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + bool hasAccessibleDefaultConstructor = false; + if (type is INamedTypeSymbol named && !named.IsAbstract && named.InstanceConstructors.Length > 0) + { + foreach (IMethodSymbol ctor in named.InstanceConstructors) + { + if (ctor.Parameters.Length == 0) + { + hasAccessibleDefaultConstructor = _compilation.IsSymbolAccessibleWithin(ctor, _containingScope); + break; + } + } + } + return new SafeHandleMarshallingInfo(hasAccessibleDefaultConstructor, type.IsAbstract); + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/SignatureContext.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/SignatureContext.cs index da94ec9a541d26..b9df1831512e7c 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/SignatureContext.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/SignatureContext.cs @@ -56,9 +56,10 @@ public static SignatureContext Create( InteropAttributeData interopAttributeData, StubEnvironment env, IGeneratorDiagnostics diagnostics, + AttributeData signatureWideMarshallingAttributeData, Assembly generatorInfoAssembly) { - ImmutableArray typeInfos = GenerateTypeInformation(method, interopAttributeData, diagnostics, env); + ImmutableArray typeInfos = GenerateTypeInformation(method, interopAttributeData, diagnostics, env, signatureWideMarshallingAttributeData); ImmutableArray.Builder additionalAttrs = ImmutableArray.CreateBuilder(); @@ -99,7 +100,12 @@ public static SignatureContext Create( }; } - private static ImmutableArray GenerateTypeInformation(IMethodSymbol method, InteropAttributeData interopAttributeData, IGeneratorDiagnostics diagnostics, StubEnvironment env) + private static ImmutableArray GenerateTypeInformation( + IMethodSymbol method, + InteropAttributeData interopAttributeData, + IGeneratorDiagnostics diagnostics, + StubEnvironment env, + AttributeData signatureWideMarshallingAttributeData) { // Compute the current default string encoding value. CharEncoding defaultEncoding = CharEncoding.Undefined; @@ -120,14 +126,32 @@ private static ImmutableArray GenerateTypeInformation(IMethodS var defaultInfo = new DefaultMarshallingInfo(defaultEncoding, interopAttributeData.StringMarshallingCustomType); - var marshallingAttributeParser = new MarshallingAttributeInfoParser(env.Compilation, diagnostics, defaultInfo, method); + var useSiteAttributeParsers = ImmutableArray.Create( + new MarshalAsAttributeParser(env.Compilation, diagnostics, defaultInfo), + new MarshalUsingAttributeParser(env.Compilation, diagnostics)); + + var marshallingInfoParser = new MarshallingInfoParser( + diagnostics, + new MethodSignatureElementInfoProvider(env.Compilation, diagnostics, method, useSiteAttributeParsers), + useSiteAttributeParsers, + ImmutableArray.Create( + new MarshalAsAttributeParser(env.Compilation, diagnostics, defaultInfo), + new MarshalUsingAttributeParser(env.Compilation, diagnostics), + new NativeMarshallingAttributeParser(env.Compilation, diagnostics)), + ImmutableArray.Create( + new SafeHandleMarshallingInfoProvider(env.Compilation, method.ContainingType), + new ArrayMarshallingInfoProvider(env.Compilation), + new CharMarshallingInfoProvider(defaultInfo), + new StringMarshallingInfoProvider(env.Compilation, diagnostics, signatureWideMarshallingAttributeData, defaultInfo), + new BooleanMarshallingInfoProvider(), + new BlittableTypeMarshallingInfoProvider(env.Compilation))); // Determine parameter and return types ImmutableArray.Builder typeInfos = ImmutableArray.CreateBuilder(); for (int i = 0; i < method.Parameters.Length; i++) { IParameterSymbol param = method.Parameters[i]; - MarshallingInfo marshallingInfo = marshallingAttributeParser.ParseMarshallingInfo(param.Type, param.GetAttributes()); + MarshallingInfo marshallingInfo = marshallingInfoParser.ParseMarshallingInfo(param.Type, param.GetAttributes()); var typeInfo = TypePositionInfo.CreateForParameter(param, marshallingInfo, env.Compilation); typeInfo = typeInfo with { @@ -137,7 +161,7 @@ private static ImmutableArray GenerateTypeInformation(IMethodS typeInfos.Add(typeInfo); } - TypePositionInfo retTypeInfo = new(ManagedTypeInfo.CreateTypeInfoForTypeSymbol(method.ReturnType), marshallingAttributeParser.ParseMarshallingInfo(method.ReturnType, method.GetReturnTypeAttributes())); + TypePositionInfo retTypeInfo = new(ManagedTypeInfo.CreateTypeInfoForTypeSymbol(method.ReturnType), marshallingInfoParser.ParseMarshallingInfo(method.ReturnType, method.GetReturnTypeAttributes())); retTypeInfo = retTypeInfo with { ManagedIndex = TypePositionInfo.ReturnIndex, diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/StringMarshallingInfoProvider.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/StringMarshallingInfoProvider.cs new file mode 100644 index 00000000000000..e8c9aee264d3df --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/StringMarshallingInfoProvider.cs @@ -0,0 +1,96 @@ +// 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.Text; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + + /// + /// This class supports generating marshalling info for the type. + /// This includes support for the System.Runtime.InteropServices.StringMarshalling enum. + /// + public sealed class StringMarshallingInfoProvider : ITypeBasedMarshallingInfoProvider + { + private readonly Compilation _compilation; + private readonly IGeneratorDiagnostics _diagnostics; + private readonly AttributeData _stringMarshallingCustomAttribute; + private readonly DefaultMarshallingInfo _defaultMarshallingInfo; + + public StringMarshallingInfoProvider(Compilation compilation, IGeneratorDiagnostics diagnostics, AttributeData stringMarshallingCustomAttribute, DefaultMarshallingInfo defaultMarshallingInfo) + { + _compilation = compilation; + _diagnostics = diagnostics; + _stringMarshallingCustomAttribute = stringMarshallingCustomAttribute; + _defaultMarshallingInfo = defaultMarshallingInfo; + } + + public bool CanProvideMarshallingInfoForType(ITypeSymbol type) => type.SpecialType == SpecialType.System_String; + + public MarshallingInfo GetMarshallingInfo(ITypeSymbol type, int indirectionDepth, UseSiteAttributeProvider useSiteAttributes, GetMarshallingInfoCallback marshallingInfoCallback) + { + if (_defaultMarshallingInfo.CharEncoding == CharEncoding.Undefined) + { + return NoMarshallingInfo.Instance; + } + else if (_defaultMarshallingInfo.CharEncoding == CharEncoding.Custom) + { + if (_defaultMarshallingInfo.StringMarshallingCustomType is not null) + { + CountInfo countInfo = NoCountInfo.Instance; + if (useSiteAttributes.TryGetUseSiteAttributeInfo(indirectionDepth, out var useSiteInfo)) + { + countInfo = useSiteInfo.CountInfo; + } + return CustomMarshallingInfoHelper.CreateNativeMarshallingInfo( + type, + _defaultMarshallingInfo.StringMarshallingCustomType, + _stringMarshallingCustomAttribute, + useSiteAttributes, + marshallingInfoCallback, + indirectionDepth, + countInfo, + _diagnostics, + _compilation); + } + } + else + { + // No marshalling info was computed, but a character encoding was provided. + return _defaultMarshallingInfo.CharEncoding switch + { + CharEncoding.Utf16 => CreateStringMarshallingInfo(_compilation, type, TypeNames.Utf16StringMarshaller), + CharEncoding.Utf8 => CreateStringMarshallingInfo(_compilation, type, TypeNames.Utf8StringMarshaller), + _ => throw new InvalidOperationException() + }; + } + + return new MarshallingInfoStringSupport(_defaultMarshallingInfo.CharEncoding); + } + + public static MarshallingInfo CreateStringMarshallingInfo( + Compilation compilation, + ITypeSymbol type, + string marshallerName) + { + INamedTypeSymbol? stringMarshaller = compilation.GetTypeByMetadataName(marshallerName); + if (stringMarshaller is null) + return new MissingSupportMarshallingInfo(); + + if (ManualTypeMarshallingHelper.HasEntryPointMarshallerAttribute(stringMarshaller)) + { + if (ManualTypeMarshallingHelper.TryGetValueMarshallersFromEntryType(stringMarshaller, type, compilation, out CustomTypeMarshallers? marshallers)) + { + return new NativeMarshallingAttributeInfo( + EntryPointType: ManagedTypeInfo.CreateTypeInfoForTypeSymbol(stringMarshaller), + Marshallers: marshallers.Value); + } + } + + return new MissingSupportMarshallingInfo(); + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/UseSiteAttributeProvider.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/UseSiteAttributeProvider.cs new file mode 100644 index 00000000000000..fa19c1991e2627 --- /dev/null +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/UseSiteAttributeProvider.cs @@ -0,0 +1,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.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; + +namespace Microsoft.Interop +{ + /// + /// Parses information for all use-site attributes and tracks their usage. + /// + public sealed class UseSiteAttributeProvider + { + private readonly ImmutableDictionary _useSiteAttributesByIndirectionDepth; + private readonly int _maxIndirectionLevelDataProvided; + private readonly IGeneratorDiagnostics _diagnostics; + private int _maxIndirectionLevelUsed; + + /// + /// Construct a new for a given usage site. + /// + /// The parsers for the attributes at the given usage site. + /// The attributes at the usage site. + /// The provider for additional element information, used by the attribute parsers. + /// Diagnostics sink for any invalid configurations. + /// A callback to get marshalling information for other elements. Used by . + internal UseSiteAttributeProvider( + ImmutableArray useSiteAttributeParsers, + IEnumerable useSiteAttributes, + IElementInfoProvider elementInfoProvider, + IGeneratorDiagnostics diagnostics, + GetMarshallingInfoCallback getMarshallingInfoCallback) + { + ImmutableDictionary.Builder useSiteAttributesByIndirectionDepth = ImmutableDictionary.CreateBuilder(); + _maxIndirectionLevelDataProvided = 0; + foreach (AttributeData attribute in useSiteAttributes) + { + UseSiteAttributeData? useSiteAttributeData = GetUseSiteInfoForAttribute(attribute); + if (useSiteAttributeData is not null) + { + int indirectionDepth = useSiteAttributeData.IndirectionDepth; + if (useSiteAttributesByIndirectionDepth.ContainsKey(indirectionDepth)) + { + diagnostics.ReportInvalidMarshallingAttributeInfo(attribute, nameof(SR.DuplicateMarshallingInfo), indirectionDepth.ToString()); + } + else + { + useSiteAttributesByIndirectionDepth.Add(indirectionDepth, useSiteAttributeData); + _maxIndirectionLevelDataProvided = Math.Max(_maxIndirectionLevelDataProvided, indirectionDepth); + } + } + } + _useSiteAttributesByIndirectionDepth = useSiteAttributesByIndirectionDepth.ToImmutable(); + _diagnostics = diagnostics; + + UseSiteAttributeData? GetUseSiteInfoForAttribute(AttributeData attribute) + { + foreach (var parser in useSiteAttributeParsers) + { + // Automatically ignore invalid attributes. + // The compiler will already error on them. + if (attribute.AttributeConstructor is not null && parser.CanParseAttributeType(attribute.AttributeClass)) + { + return parser.ParseAttribute(attribute, elementInfoProvider, getMarshallingInfoCallback); + } + } + return null; + } + } + + /// + /// Get the provided for a given , if it exists. + /// + /// The indirection depth to retrieve info for. + /// The use site information, if it exists. + /// true if an attribute was provided for the given indirection depth. + public bool TryGetUseSiteAttributeInfo(int indirectionDepth, out UseSiteAttributeData useSiteInfo) + { + _maxIndirectionLevelUsed = Math.Max(indirectionDepth, _maxIndirectionLevelUsed); + return _useSiteAttributesByIndirectionDepth.TryGetValue(indirectionDepth, out useSiteInfo); + } + + /// + /// Call when no more of the use-site attribute information will be used. + /// Records any information or diagnostics about unused marshalling information. + /// + internal void OnAttributeUsageFinished() + { + if (_maxIndirectionLevelUsed < _maxIndirectionLevelDataProvided) + { + _diagnostics.ReportInvalidMarshallingAttributeInfo( + _useSiteAttributesByIndirectionDepth[_maxIndirectionLevelDataProvided].AttributeData, + nameof(SR.ExtraneousMarshallingInfo), + _maxIndirectionLevelDataProvided.ToString(), + _maxIndirectionLevelUsed.ToString()); + } + } + } +} diff --git a/src/libraries/System.Runtime.InteropServices/tests/LibraryImportGenerator.UnitTests/CompileFails.cs b/src/libraries/System.Runtime.InteropServices/tests/LibraryImportGenerator.UnitTests/CompileFails.cs index 5a77bb12d7b466..4d10887e344332 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/LibraryImportGenerator.UnitTests/CompileFails.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/LibraryImportGenerator.UnitTests/CompileFails.cs @@ -120,8 +120,8 @@ public static IEnumerable CodeSnippetsToCompile() // Generic collection marshaller has different arity than collection. yield return new object[] { ID(), CodeSnippets.CustomCollectionMarshalling.Stateless.GenericCollectionMarshallingArityMismatch, 2, 0 }; - yield return new object[] { ID(), CodeSnippets.MarshalAsAndMarshalUsingOnReturnValue, 2, 0 }; - yield return new object[] { ID(), CodeSnippets.CustomCollectionMarshalling.Stateless.CustomElementMarshallingDuplicateElementIndirectionDepth, 2, 0 }; + yield return new object[] { ID(), CodeSnippets.MarshalAsAndMarshalUsingOnReturnValue, 1, 0 }; + yield return new object[] { ID(), CodeSnippets.CustomCollectionMarshalling.Stateless.CustomElementMarshallingDuplicateElementIndirectionDepth, 1, 0 }; yield return new object[] { ID(), CodeSnippets.CustomCollectionMarshalling.Stateless.CustomElementMarshallingUnusedElementIndirectionDepth, 1, 0 }; yield return new object[] { ID(), CodeSnippets.RecursiveCountElementNameOnReturnValue, 2, 0 }; yield return new object[] { ID(), CodeSnippets.RecursiveCountElementNameOnParameter, 2, 0 }; From fe9a5a4685f1314bab48804ae9b9716890b331e1 Mon Sep 17 00:00:00 2001 From: Adeel Mujahid <3840695+am11@users.noreply.github.com> Date: Tue, 30 Aug 2022 07:40:43 +0300 Subject: [PATCH 024/107] Use nproc without --all on Linux (#74696) * Use nproc without --all on Linux * Fix a few typos missed in previous PR * Allow llvm-objcopy to be 'NOT FOUND' * Add CMAKE ASM workaround for newer clang * Fix comment --- eng/native/build-commons.sh | 20 +++++------ eng/native/configurecompiler.cmake | 7 ++++ eng/native/configuretools.cmake | 39 ++++++++++++--------- eng/native/ijw/IJW.cmake | 2 +- eng/native/init-os-and-arch.sh | 6 ++-- src/coreclr/debug/ee/CMakeLists.txt | 6 ++-- src/coreclr/pal/inc/pal.h | 4 +-- src/tests/Common/scripts/bringup_runtest.sh | 26 +++++++------- src/tests/build.sh | 22 ++++++------ 9 files changed, 72 insertions(+), 60 deletions(-) diff --git a/eng/native/build-commons.sh b/eng/native/build-commons.sh index 4199828f2970be..dd0dea81cd6199 100755 --- a/eng/native/build-commons.sh +++ b/eng/native/build-commons.sh @@ -234,23 +234,19 @@ __HostOS=$os __BuildOS=$os # Get the number of processors available to the scheduler -# Other techniques such as `nproc` only get the number of -# processors available to a single process. platform="$(uname)" if [[ "$platform" == "FreeBSD" ]]; then - __NumProc=$(($(sysctl -n hw.ncpu)+1)) + __NumProc="$(($(sysctl -n hw.ncpu)+1))" elif [[ "$platform" == "NetBSD" || "$platform" == "SunOS" ]]; then - __NumProc=$(($(getconf NPROCESSORS_ONLN)+1)) + __NumProc="$(($(getconf NPROCESSORS_ONLN)+1))" elif [[ "$platform" == "Darwin" ]]; then - __NumProc=$(($(getconf _NPROCESSORS_ONLN)+1)) + __NumProc="$(($(getconf _NPROCESSORS_ONLN)+1))" +elif command -v nproc > /dev/null 2>&1; then + __NumProc="$(nproc)" +elif (NAME=""; . /etc/os-release; test "$NAME" = "Tizen"); then + __NumProc="$(getconf _NPROCESSORS_ONLN)" else - if command -v nproc > /dev/null 2>&1; then - __NumProc=$(nproc --all) - elif (NAME=""; . /etc/os-release; test "$NAME" = "Tizen"); then - __NumProc=$(getconf _NPROCESSORS_ONLN) - else - __NumProc=1 - fi + __NumProc=1 fi while :; do diff --git a/eng/native/configurecompiler.cmake b/eng/native/configurecompiler.cmake index 9594de561b452e..a0163845e63e8c 100644 --- a/eng/native/configurecompiler.cmake +++ b/eng/native/configurecompiler.cmake @@ -787,6 +787,13 @@ if (CLR_CMAKE_HOST_WIN32) endif() elseif (NOT CLR_CMAKE_HOST_BROWSER) + # This is a workaround for upstream issue: https://gitlab.kitware.com/cmake/cmake/-/issues/22995. + # + # In Clang.cmake, the decision to use single or double hyphen for target and gcc-toolchain + # is made based on CMAKE_${LANG}_COMPILER_VERSION, but CMAKE_ASM_COMPILER_VERSION is empty + # so it picks up single hyphen options, which new clang versions don't recognize. + set (CMAKE_ASM_COMPILER_VERSION "${CMAKE_C_COMPILER_VERSION}") + enable_language(ASM) endif(CLR_CMAKE_HOST_WIN32) diff --git a/eng/native/configuretools.cmake b/eng/native/configuretools.cmake index 2a02d1110f7270..07a3bbfafe4dd9 100644 --- a/eng/native/configuretools.cmake +++ b/eng/native/configuretools.cmake @@ -21,7 +21,7 @@ if(NOT WIN32 AND NOT CLR_CMAKE_TARGET_BROWSER) endif() endif() - function(locate_toolchain_exec exec var) + function(locate_toolchain_exec exec var required) string(TOUPPER ${exec} EXEC_UPPERCASE) if(NOT "$ENV{CLR_${EXEC_UPPERCASE}}" STREQUAL "") set(${var} "$ENV{CLR_${EXEC_UPPERCASE}}" PARENT_SCOPE) @@ -34,33 +34,40 @@ if(NOT WIN32 AND NOT CLR_CMAKE_TARGET_BROWSER) "${TOOLSET_PREFIX}${exec}${CLR_CMAKE_COMPILER_FILE_NAME_VERSION}" "${TOOLSET_PREFIX}${exec}") - if (EXEC_LOCATION_${exec} STREQUAL "EXEC_LOCATION_${exec}-NOTFOUND") - message(FATAL_ERROR "Unable to find toolchain executable. Name: '${exec}', Prefix: '${TOOLSET_PREFIX}.'") + if (required AND EXEC_LOCATION_${exec} STREQUAL "EXEC_LOCATION_${exec}-NOTFOUND") + message(FATAL_ERROR "Unable to find toolchain executable. Name: '${exec}', Prefix: '${TOOLSET_PREFIX}'") + endif() + + if (NOT EXEC_LOCATION_${exec} STREQUAL "EXEC_LOCATION_${exec}-NOTFOUND") + set(${var} ${EXEC_LOCATION_${exec}} PARENT_SCOPE) endif() - set(${var} ${EXEC_LOCATION_${exec}} PARENT_SCOPE) endfunction() - locate_toolchain_exec(ar CMAKE_AR) - locate_toolchain_exec(nm CMAKE_NM) - locate_toolchain_exec(ranlib CMAKE_RANLIB) + locate_toolchain_exec(ar CMAKE_AR YES) + locate_toolchain_exec(nm CMAKE_NM YES) + locate_toolchain_exec(ranlib CMAKE_RANLIB YES) if(CMAKE_C_COMPILER_ID MATCHES "Clang") - locate_toolchain_exec(link CMAKE_LINKER) + locate_toolchain_exec(link CMAKE_LINKER YES) endif() if(NOT CLR_CMAKE_TARGET_OSX AND NOT CLR_CMAKE_TARGET_MACCATALYST AND NOT CLR_CMAKE_TARGET_IOS AND NOT CLR_CMAKE_TARGET_TVOS AND (NOT CLR_CMAKE_TARGET_ANDROID OR CROSS_ROOTFS)) - locate_toolchain_exec(objdump CMAKE_OBJDUMP) - locate_toolchain_exec(objcopy CMAKE_OBJCOPY) + locate_toolchain_exec(objdump CMAKE_OBJDUMP YES) - execute_process( - COMMAND ${CMAKE_OBJCOPY} --help - OUTPUT_VARIABLE OBJCOPY_HELP_OUTPUT - ) + unset(CMAKE_OBJCOPY CACHE) + locate_toolchain_exec(objcopy CMAKE_OBJCOPY NO) + + if (CMAKE_OBJCOPY) + execute_process( + COMMAND ${CMAKE_OBJCOPY} --help + OUTPUT_VARIABLE OBJCOPY_HELP_OUTPUT + ) + endif() # if llvm-objcopy does not support --only-keep-debug argument, try to locate binutils' objcopy - if (CMAKE_C_COMPILER_ID MATCHES "Clang" AND NOT "${OBJCOPY_HELP_OUTPUT}" MATCHES "--only-keep-debug") + if (NOT CMAKE_OBJCOPY OR (CMAKE_C_COMPILER_ID MATCHES "Clang" AND NOT "${OBJCOPY_HELP_OUTPUT}" MATCHES "--only-keep-debug")) set(TOOLSET_PREFIX "") - locate_toolchain_exec(objcopy CMAKE_OBJCOPY) + locate_toolchain_exec(objcopy CMAKE_OBJCOPY YES) endif () endif() diff --git a/eng/native/ijw/IJW.cmake b/eng/native/ijw/IJW.cmake index f606b5e98889fe..9a38a18dc0759b 100644 --- a/eng/native/ijw/IJW.cmake +++ b/eng/native/ijw/IJW.cmake @@ -32,7 +32,7 @@ if (CLR_CMAKE_HOST_WIN32) endfunction() # 4365 - signed/unsigned mismatch - # 4679 - Could not import member. This is an issue with IJW and static abstract methods in interfaces. + # 4679 - Could not import member. This is an issue with IJW and static abstract methods in interfaces. add_compile_options(/wd4365 /wd4679) # IJW diff --git a/eng/native/init-os-and-arch.sh b/eng/native/init-os-and-arch.sh index 4064314011391d..9f8b78984db0f9 100644 --- a/eng/native/init-os-and-arch.sh +++ b/eng/native/init-os-and-arch.sh @@ -68,11 +68,11 @@ case "$CPUName" in s390x) arch=s390x - ;; + ;; ppc64le) - arch=ppc64le - ;; + arch=ppc64le + ;; *) echo "Unknown CPU $CPUName detected!" exit 1 diff --git a/src/coreclr/debug/ee/CMakeLists.txt b/src/coreclr/debug/ee/CMakeLists.txt index 106f4bed5d0e6c..aebc2d22022629 100644 --- a/src/coreclr/debug/ee/CMakeLists.txt +++ b/src/coreclr/debug/ee/CMakeLists.txt @@ -49,11 +49,9 @@ set(CORDBEE_HEADERS_DAC list(APPEND CORDBEE_SOURCES_WKS ${ARCH_SOURCES_DIR}/walker.cpp) -if(CLR_CMAKE_TARGET_ARCH_AMD64) +if (CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_I386) list(APPEND CORDBEE_SOURCES_WKS ${ARCH_SOURCES_DIR}/debuggerregdisplayhelper.cpp) -elseif(CLR_CMAKE_TARGET_ARCH_I386) - list(APPEND CORDBEE_SOURCES_WKS ${ARCH_SOURCES_DIR}/debuggerregdisplayhelper.cpp) -endif() +endif () convert_to_absolute_path(CORDBEE_SOURCES_DAC ${CORDBEE_SOURCES_DAC}) convert_to_absolute_path(CORDBEE_SOURCES_WKS ${CORDBEE_SOURCES_WKS}) diff --git a/src/coreclr/pal/inc/pal.h b/src/coreclr/pal/inc/pal.h index 7cab500089376f..f58c854487128a 100644 --- a/src/coreclr/pal/inc/pal.h +++ b/src/coreclr/pal/inc/pal.h @@ -2653,7 +2653,7 @@ PALIMPORT BOOL PALAPI PAL_GetUnwindInfoSize(SIZE_T baseAddress, ULONG64 ehFrameH #define PAL_CS_NATIVE_DATA_SIZE 48 #elif defined(__linux__) && defined(__loongarch64) #define PAL_CS_NATIVE_DATA_SIZE 96 -#elif defined(__linux__) && defined(_riscv) && __riscv_xlen == 64 +#elif defined(__linux__) && defined(__riscv) && __riscv_xlen == 64 #define PAL_CS_NATIVE_DATA_SIZE 96 #else #error PAL_CS_NATIVE_DATA_SIZE is not defined for this architecture @@ -3742,7 +3742,7 @@ YieldProcessor() __asm__ __volatile__( "yield"); #elif defined(HOST_LOONGARCH64) __asm__ volatile( "dbar 0; \n"); -#elif defined(HOST_RISV64) +#elif defined(HOST_RISCV64) __asm__ __volatile__( "wfi"); #else return; diff --git a/src/tests/Common/scripts/bringup_runtest.sh b/src/tests/Common/scripts/bringup_runtest.sh index b5228105980ffc..e532f36631b6be 100755 --- a/src/tests/Common/scripts/bringup_runtest.sh +++ b/src/tests/Common/scripts/bringup_runtest.sh @@ -727,20 +727,22 @@ function run_test { return $testScriptExitCode } -# Variables for running tests in the background -if [ `uname` = "NetBSD" ]; then - NumProc=$(getconf NPROCESSORS_ONLN) -elif [ `uname` = "Darwin" ]; then - NumProc=$(getconf _NPROCESSORS_ONLN) +# Get the number of processors available to the scheduler +platform="$(uname)" +if [[ "$platform" == "FreeBSD" ]]; then + NumProc="$(($(sysctl -n hw.ncpu)+1))" +elif [[ "$platform" == "NetBSD" || "$platform" == "SunOS" ]]; then + NumProc="$(($(getconf NPROCESSORS_ONLN)+1))" +elif [[ "$platform" == "Darwin" ]]; then + NumProc="$(($(getconf _NPROCESSORS_ONLN)+1))" +elif command -v nproc > /dev/null 2>&1; then + NumProc="$(nproc)" +elif (NAME=""; . /etc/os-release; test "$NAME" = "Tizen"); then + NumProc="$(getconf _NPROCESSORS_ONLN)" else - if [ -x "$(command -v nproc)" ]; then - NumProc=$(nproc --all) - elif [ -x "$(command -v getconf)" ]; then - NumProc=$(getconf _NPROCESSORS_ONLN) - else - NumProc=1 - fi + NumProc=1 fi + ((maxProcesses = $NumProc * 3 / 2)) # long tests delay process creation, use a few more processors ((processCount = 0)) diff --git a/src/tests/build.sh b/src/tests/build.sh index 3e806743062fcf..c6f30ccf3670cc 100755 --- a/src/tests/build.sh +++ b/src/tests/build.sh @@ -358,17 +358,19 @@ else fi # Get the number of processors available to the scheduler -# Other techniques such as `nproc` only get the number of -# processors available to a single process. -__Platform="$(uname)" -if [[ "$__Platform" == "FreeBSD" ]]; then - __NumProc=$(($(sysctl -n hw.ncpu)+1)) -elif [[ "$__Platform" == "NetBSD" || "$__Platform" == "SunOS" ]]; then - __NumProc=$(($(getconf NPROCESSORS_ONLN)+1)) -elif [[ "$__Platform" == "Darwin" ]]; then - __NumProc=$(($(getconf _NPROCESSORS_ONLN)+1)) +platform="$(uname)" +if [[ "$platform" == "FreeBSD" ]]; then + __NumProc="$(($(sysctl -n hw.ncpu)+1))" +elif [[ "$platform" == "NetBSD" || "$platform" == "SunOS" ]]; then + __NumProc="$(($(getconf NPROCESSORS_ONLN)+1))" +elif [[ "$platform" == "Darwin" ]]; then + __NumProc="$(($(getconf _NPROCESSORS_ONLN)+1))" +elif command -v nproc > /dev/null 2>&1; then + __NumProc="$(nproc)" +elif (NAME=""; . /etc/os-release; test "$NAME" = "Tizen"); then + __NumProc="$(getconf _NPROCESSORS_ONLN)" else - __NumProc=$(nproc --all) + __NumProc=1 fi # Set dependent variables From 3346c4abacbab5ecaf1ed295aa65ce5e66db8917 Mon Sep 17 00:00:00 2001 From: Robert Henry Date: Tue, 30 Aug 2022 02:01:04 -0700 Subject: [PATCH 025/107] add a null pointer guard around a usage of comp->vnStore (#73958) --- src/coreclr/jit/gentree.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/coreclr/jit/gentree.cpp b/src/coreclr/jit/gentree.cpp index 3b7c12f25ccb12..dc0b11d6571ebf 100644 --- a/src/coreclr/jit/gentree.cpp +++ b/src/coreclr/jit/gentree.cpp @@ -7706,7 +7706,7 @@ bool GenTreeOp::UsesDivideByConstOptimized(Compiler* comp) else { ValueNum vn = divisor->gtVNPair.GetLiberal(); - if (comp->vnStore->IsVNConstant(vn)) + if (comp->vnStore && comp->vnStore->IsVNConstant(vn)) { divisorValue = comp->vnStore->CoercedConstantValue(vn); } From d564175890065c0dfc16ef6cf12c20456d740cc9 Mon Sep 17 00:00:00 2001 From: Radek Zikmund <32671551+rzikm@users.noreply.github.com> Date: Tue, 30 Aug 2022 05:00:50 -0700 Subject: [PATCH 026/107] Fix possible stack overflow in HttpListener (#74644) * Fix possible stack overflow in HttpListener * Fix assert --- .../Net/Managed/HttpEndPointListener.cs | 57 ++++++++++--------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs index 6753f34565b664..5cb7f73298a941 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs @@ -56,7 +56,7 @@ public HttpEndPointListener(HttpListener listener, IPAddress addr, int port, boo if (secure) { _secure = secure; - _cert = HttpListener.LoadCertificateAndKey (addr, port); + _cert = HttpListener.LoadCertificateAndKey(addr, port); } _endpoint = new IPEndPoint(addr, port); @@ -80,38 +80,39 @@ internal HttpListener Listener private void Accept(SocketAsyncEventArgs e) { - e.AcceptSocket = null; - bool asyn; - try - { - asyn = _socket.AcceptAsync(e); - } - catch (ObjectDisposedException) - { - // Once the listener starts running, it kicks off an async accept, - // and each subsequent accept initiates the next async accept. At - // point if the listener is torn down, the socket will be disposed - // and the AcceptAsync on the socket can fail with an ODE. Far from - // ideal, but for now just eat such exceptions. - return; - } - if (!asyn) + bool asyn = false; + while (!asyn) { - ProcessAccept(e); + try + { + e.AcceptSocket = null; + asyn = _socket.AcceptAsync(e); + } + catch (ObjectDisposedException) + { + // Once the listener starts running, it kicks off an async accept, + // and each subsequent accept initiates the next async accept. At + // point if the listener is torn down, the socket will be disposed + // and the AcceptAsync on the socket can fail with an ODE. Far from + // ideal, but for now just eat such exceptions. + return; + } + + if (!asyn) + { + ProcessAccept(e); + } } } - private static void ProcessAccept(SocketAsyncEventArgs args) + private void ProcessAccept(SocketAsyncEventArgs args) { - HttpEndPointListener epl = (HttpEndPointListener)args.UserToken!; - Socket? accepted = args.SocketError == SocketError.Success ? args.AcceptSocket : null; - epl.Accept(args); if (accepted == null) return; - if (epl._secure && epl._cert == null) + if (_secure && _cert == null) { accepted.Close(); return; @@ -120,7 +121,7 @@ private static void ProcessAccept(SocketAsyncEventArgs args) HttpConnection conn; try { - conn = new HttpConnection(accepted, epl, epl._secure, epl._cert!); + conn = new HttpConnection(accepted, this, _secure, _cert!); } catch { @@ -128,16 +129,18 @@ private static void ProcessAccept(SocketAsyncEventArgs args) return; } - lock (epl._unregisteredConnections) + lock (_unregisteredConnections) { - epl._unregisteredConnections[conn] = conn; + _unregisteredConnections[conn] = conn; } conn.BeginReadRequest(); } private static void OnAccept(object? sender, SocketAsyncEventArgs e) { - ProcessAccept(e); + HttpEndPointListener epl = (HttpEndPointListener)e.UserToken!; + epl.ProcessAccept(e); + epl.Accept(e); } internal void RemoveConnection(HttpConnection conn) From d196d850079ba88e904123c725e0f358142349c7 Mon Sep 17 00:00:00 2001 From: Steve Pfister Date: Tue, 30 Aug 2022 08:29:03 -0400 Subject: [PATCH 027/107] Skip System.Net.Requests tests on mono linux-arm64 (#74668) The suite crashes on mono linux-arm64 and is being tracked by #74667 --- .../tests/TestUtilities/System/PlatformDetection.Unix.cs | 3 +++ src/libraries/System.Net.Requests/tests/AssemblyInfo.cs | 2 ++ 2 files changed, 5 insertions(+) diff --git a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs index 33c4f5f9304230..0f5223965afabb 100644 --- a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs +++ b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs @@ -34,6 +34,9 @@ public static partial class PlatformDetection public static bool IsFedora => IsDistroAndVersion("fedora"); public static bool IsLinuxBionic => IsBionic(); + public static bool IsMonoLinuxArm64 => IsMonoRuntime && IsLinux && IsArm64Process; + public static bool IsNotMonoLinuxArm64 => !IsMonoLinuxArm64; + // OSX family public static bool IsOSXLike => IsOSX || IsiOS || IstvOS || IsMacCatalyst; public static bool IsOSX => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); diff --git a/src/libraries/System.Net.Requests/tests/AssemblyInfo.cs b/src/libraries/System.Net.Requests/tests/AssemblyInfo.cs index 82a9ebd805e958..3e5956a3d6fb35 100644 --- a/src/libraries/System.Net.Requests/tests/AssemblyInfo.cs +++ b/src/libraries/System.Net.Requests/tests/AssemblyInfo.cs @@ -1,7 +1,9 @@ // 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; [assembly: ActiveIssue("https://github.com/dotnet/runtime/issues/34690", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] +[assembly: ActiveIssue("https://github.com/dotnet/runtime/issues/74667", typeof(PlatformDetection), nameof(PlatformDetection.IsMonoLinuxArm64))] [assembly: SkipOnPlatform(TestPlatforms.Browser, "System.Net.Requests is not supported on Browser.")] From a17dcda94f1a2e6ad0f20e77aa68cef5eaf131a8 Mon Sep 17 00:00:00 2001 From: Steve Pfister Date: Tue, 30 Aug 2022 10:13:40 -0400 Subject: [PATCH 028/107] Move more legs out of runtime-staging (#74783) This change does the following: - Drops CoreCLR arm64 build and libraries test run as it seems to already be done in the runtime pipeline - Moves Android arm64 runtime tests to runtime-extra-platforms --- .../runtime-extra-platforms-other.yml | 41 +++++++++++ eng/pipelines/runtime-staging.yml | 70 ------------------- 2 files changed, 41 insertions(+), 70 deletions(-) diff --git a/eng/pipelines/runtime-extra-platforms-other.yml b/eng/pipelines/runtime-extra-platforms-other.yml index 55304308dfdd34..983f239077762f 100644 --- a/eng/pipelines/runtime-extra-platforms-other.yml +++ b/eng/pipelines/runtime-extra-platforms-other.yml @@ -568,6 +568,47 @@ jobs: creator: dotnet-bot testRunNamePrefixSuffix: Mono_$(_BuildConfig) +# +# Build the whole product using Mono for Android and run runtime tests with Android devices +# +- template: /eng/pipelines/common/platform-matrix.yml + parameters: + jobTemplate: /eng/pipelines/common/global-build-job.yml + helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml + buildConfig: Release + runtimeFlavor: mono + platforms: + - Android_arm64 + variables: + - ${{ if and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }}: + - name: _HelixSource + value: pr/dotnet/runtime/$(Build.SourceBranch) + - ${{ if and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }}: + - name: _HelixSource + value: ci/dotnet/runtime/$(Build.SourceBranch) + - name: timeoutPerTestInMinutes + value: 60 + - name: timeoutPerTestCollectionInMinutes + value: 180 + jobParameters: + testGroup: innerloop + nameSuffix: AllSubsets_Mono_RuntimeTests + buildArgs: -s mono+libs -c $(_BuildConfig) + timeoutInMinutes: 240 + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(variables['isRollingBuild'], true)) + # don't run tests on PRs until we can get significantly more devices + # Turn off the testing for now, until https://github.com/dotnet/runtime/issues/60128 gets resolved + # ${{ if eq(variables['isRollingBuild'], true) }}: + # # extra steps, run tests + # extraStepsTemplate: /eng/pipelines/common/templates/runtimes/android-runtime-and-send-to-helix.yml + # extraStepsParameters: + # creator: dotnet-bot + # testRunNamePrefixSuffix: Mono_$(_BuildConfig) + # # Mono CoreCLR runtime Test executions using live libraries in jit mode # Only when Mono is changed diff --git a/eng/pipelines/runtime-staging.yml b/eng/pipelines/runtime-staging.yml index b69cfcf4594e92..e4cf2237a70707 100644 --- a/eng/pipelines/runtime-staging.yml +++ b/eng/pipelines/runtime-staging.yml @@ -96,73 +96,3 @@ jobs: extraStepsParameters: creator: dotnet-bot testRunNamePrefixSuffix: Mono_$(_BuildConfig) - -# -# Build the whole product using Mono for Android and run runtime tests with Android devices -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono - platforms: - - Android_arm64 - variables: - - ${{ if and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: pr/dotnet/runtime/$(Build.SourceBranch) - - ${{ if and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: ci/dotnet/runtime/$(Build.SourceBranch) - - name: timeoutPerTestInMinutes - value: 60 - - name: timeoutPerTestCollectionInMinutes - value: 180 - jobParameters: - testGroup: innerloop - nameSuffix: AllSubsets_Mono_RuntimeTests - buildArgs: -s mono+libs -c $(_BuildConfig) - timeoutInMinutes: 240 - condition: >- - or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(variables['isRollingBuild'], true)) - # don't run tests on PRs until we can get significantly more devices - # Turn off the testing for now, until https://github.com/dotnet/runtime/issues/60128 gets resolved - # ${{ if eq(variables['isRollingBuild'], true) }}: - # # extra steps, run tests - # extraStepsTemplate: /eng/pipelines/common/templates/runtimes/android-runtime-and-send-to-helix.yml - # extraStepsParameters: - # creator: dotnet-bot - # testRunNamePrefixSuffix: Mono_$(_BuildConfig) - -# -# CoreCLR Build for running Apple Silicon libraries-innerloop -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/coreclr/templates/build-job.yml - buildConfig: release - platforms: - - ${{ if eq(variables['isRollingBuild'], true) }}: - - OSX_arm64 - jobParameters: - testGroup: innerloop -# -# Libraries Build for running Apple Silicon libraries-innerloop -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/libraries/build-job.yml - buildConfig: Release - platforms: - - ${{ if eq(variables['isRollingBuild'], true) }}: - - OSX_arm64 - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - jobParameters: - isOfficialBuild: ${{ variables['isOfficialBuild'] }} - runTests: true - testScope: innerloop - liveRuntimeBuildConfig: release From c96f5047b20fa43d27ba0822f2e051b0c80e3fa2 Mon Sep 17 00:00:00 2001 From: Will Smith Date: Tue, 30 Aug 2022 08:47:49 -0700 Subject: [PATCH 029/107] ARM64 - Disasm is consistent with values of zero and commas (#74717) --- src/coreclr/jit/emitarm64.cpp | 51 ++++++++++++++++++++++------------- src/coreclr/jit/emitarm64.h | 1 + 2 files changed, 34 insertions(+), 18 deletions(-) diff --git a/src/coreclr/jit/emitarm64.cpp b/src/coreclr/jit/emitarm64.cpp index 499b0470ff298e..084eb496191bab 100644 --- a/src/coreclr/jit/emitarm64.cpp +++ b/src/coreclr/jit/emitarm64.cpp @@ -11763,6 +11763,15 @@ size_t emitter::emitOutputInstr(insGroup* ig, instrDesc* id, BYTE** dp) /*****************************************************************************/ /*****************************************************************************/ +/***************************************************************************** + * + * Display a comma + */ +void emitter::emitDispComma() +{ + printf(", "); +} + /***************************************************************************** * * Display the instruction name @@ -11796,6 +11805,12 @@ void emitter::emitDispImm(ssize_t imm, bool addComma, bool alwaysHex /* =false * { alwaysHex = true; } + else if (imm == 0) + { + // Non-offset values of zero are never displayed as hex. + alwaysHex = false; + } + if (strictArmAsm) { printf("#"); @@ -11841,7 +11856,7 @@ void emitter::emitDispImm(ssize_t imm, bool addComma, bool alwaysHex /* =false * } if (addComma) - printf(", "); + emitDispComma(); } /***************************************************************************** @@ -12010,7 +12025,7 @@ void emitter::emitDispReg(regNumber reg, emitAttr attr, bool addComma) printf(emitRegName(reg, size)); if (addComma) - printf(", "); + emitDispComma(); } //------------------------------------------------------------------------ @@ -12023,7 +12038,7 @@ void emitter::emitDispVectorReg(regNumber reg, insOpts opt, bool addComma) emitDispArrangement(opt); if (addComma) - printf(", "); + emitDispComma(); } //------------------------------------------------------------------------ @@ -12037,7 +12052,7 @@ void emitter::emitDispVectorRegIndex(regNumber reg, emitAttr elemsize, ssize_t i printf("[%d]", (int)index); if (addComma) - printf(", "); + emitDispComma(); } //------------------------------------------------------------------------ @@ -12060,7 +12075,7 @@ void emitter::emitDispVectorRegList(regNumber firstReg, unsigned listSize, insOp if (addComma) { - printf(", "); + emitDispComma(); } } @@ -12082,7 +12097,7 @@ void emitter::emitDispVectorElemList( const bool notLastRegister = (i != listSize - 1); if (notLastRegister) { - printf(", "); + emitDispComma(); } currReg = (currReg == REG_V31) ? REG_V0 : REG_NEXT(currReg); } @@ -12091,7 +12106,7 @@ void emitter::emitDispVectorElemList( if (addComma) { - printf(", "); + emitDispComma(); } } @@ -12181,7 +12196,7 @@ void emitter::emitDispShiftedReg(regNumber reg, insOpts opt, ssize_t imm, emitAt { if (strictArmAsm) { - printf(","); + emitDispComma(); } emitDispShiftOpts(opt); emitDispImm(imm, false); @@ -12263,7 +12278,7 @@ void emitter::emitDispAddrRI(regNumber reg, insOpts opt, ssize_t imm) if (!insOptsPostIndex(opt) && (imm != 0)) { - printf(","); + emitDispComma(); emitDispImm(imm, false, true, true); } printf("]"); @@ -12274,7 +12289,7 @@ void emitter::emitDispAddrRI(regNumber reg, insOpts opt, ssize_t imm) } else if (insOptsPostIndex(opt)) { - printf(","); + emitDispComma(); emitDispImm(imm, false, true, true); } } @@ -12303,7 +12318,7 @@ void emitter::emitDispAddrRI(regNumber reg, insOpts opt, ssize_t imm) if (insOptsIndexed(opt)) { - printf(", "); + emitDispComma(); } else { @@ -13004,7 +13019,7 @@ void emitter::emitDispInsHelp( cfi.immCFVal = (unsigned)emitGetInsSC(id); emitDispImm(cfi.imm5, true); emitDispFlags(cfi.flags); - printf(", "); + emitDispComma(); emitDispCond(cfi.cond); break; @@ -13074,7 +13089,7 @@ void emitter::emitDispInsHelp( emitDispReg(id->idReg2(), size, true); cfi.immCFVal = (unsigned)emitGetInsSC(id); emitDispFlags(cfi.flags); - printf(", "); + emitDispComma(); emitDispCond(cfi.cond); break; @@ -13241,8 +13256,8 @@ void emitter::emitDispInsHelp( } if (ins == INS_fcmeq || ins == INS_fcmge || ins == INS_fcmgt || ins == INS_fcmle || ins == INS_fcmlt) { - printf(", "); - emitDispImm(0, false); + emitDispComma(); + emitDispFloatZero(); } break; @@ -13265,7 +13280,7 @@ void emitter::emitDispInsHelp( } if (ins == INS_cmeq || ins == INS_cmge || ins == INS_cmgt || ins == INS_cmle || ins == INS_cmlt) { - printf(", "); + emitDispComma(); emitDispImm(0, false); } break; @@ -13392,7 +13407,7 @@ void emitter::emitDispInsHelp( { emitDispReg(id->idReg1(), size, true); emitDispReg(id->idReg2(), size, true); - emitDispImm(0, false); + emitDispFloatZero(); } else if (emitInsIsVectorNarrow(ins)) { @@ -13407,7 +13422,7 @@ void emitter::emitDispInsHelp( if (fmt == IF_DV_2L && (ins == INS_cmeq || ins == INS_cmge || ins == INS_cmgt || ins == INS_cmle || ins == INS_cmlt)) { - printf(", "); + emitDispComma(); emitDispImm(0, false); } break; diff --git a/src/coreclr/jit/emitarm64.h b/src/coreclr/jit/emitarm64.h index e2be5a939c9d80..2e86245e611cf5 100644 --- a/src/coreclr/jit/emitarm64.h +++ b/src/coreclr/jit/emitarm64.h @@ -25,6 +25,7 @@ void emitDispInsHelp( instrDesc* id, bool isNew, bool doffs, bool asmfm, unsigned offset, BYTE* pCode, size_t sz, insGroup* ig); void emitDispLargeJmp( instrDesc* id, bool isNew, bool doffs, bool asmfm, unsigned offset, BYTE* pCode, size_t sz, insGroup* ig); +void emitDispComma(); void emitDispInst(instruction ins); void emitDispImm(ssize_t imm, bool addComma, bool alwaysHex = false, bool isAddrOffset = false); void emitDispFloatZero(); From 704c739c40ce1c776680813e1fccaf4a3b266cde Mon Sep 17 00:00:00 2001 From: Simon Rozsival Date: Tue, 30 Aug 2022 18:01:31 +0200 Subject: [PATCH 030/107] [wasm-mt] Log exit codes in browser samples to prevent tests from timeouting (#74637) * Update browser-thread sample * Update the browser-eventpipe sample * Fix wasm_exit * Revert eventpipe sample changes that didn't resolve the problem * Use new JS api * Try to use the new API also for the eventpipe sample * Revert "Try to use the new API also for the eventpipe sample" This reverts commit 9a10dc4abefcb7a27314be8349b3b93fcc00c3f7. --- src/mono/sample/wasm/browser-threads/main.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/mono/sample/wasm/browser-threads/main.js b/src/mono/sample/wasm/browser-threads/main.js index fe5efc7735dbb5..9b739d474e943b 100644 --- a/src/mono/sample/wasm/browser-threads/main.js +++ b/src/mono/sample/wasm/browser-threads/main.js @@ -54,6 +54,8 @@ try { const inputElement = document.getElementById("inputN"); const { setModuleImports, getAssemblyExports, runMain } = await dotnet .withEnvironmentVariable("MONO_LOG_LEVEL", "debug") + .withElementOnExit() + .withExitCodeLogging() .create(); setModuleImports("main.js", { From 28aa8619042b6674f4fa70ad628d0091e27cbc66 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Tue, 30 Aug 2022 19:06:38 +0300 Subject: [PATCH 031/107] Fix TransactionInterop.GetDtcTransaction() (#74776) Incorrect COM interop definition Fixes #74745 --- .../DtcProxyShim/DtcInterfaces/ITransaction.cs | 10 ++++++++-- .../DtcProxyShim/DtcInterfaces/ITransactionCloner.cs | 12 ++++++++++++ .../System.Transactions.Local/tests/OleTxTests.cs | 4 ++-- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/DtcInterfaces/ITransaction.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/DtcInterfaces/ITransaction.cs index e516d2c0d038fc..a06acb7668a582 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/DtcInterfaces/ITransaction.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/DtcInterfaces/ITransaction.cs @@ -11,9 +11,15 @@ namespace System.Transactions.DtcProxyShim.DtcInterfaces; [ComImport, Guid(Guids.IID_ITransaction), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ITransaction { - void Commit([MarshalAs(UnmanagedType.Bool)] bool fRetainingt, [MarshalAs(UnmanagedType.U4)] OletxXacttc grfTC, uint grfRM); + void Commit( + [MarshalAs(UnmanagedType.Bool)] bool fRetainingt, + [MarshalAs(UnmanagedType.U4)] OletxXacttc grfTC, + uint grfRM); - void Abort(IntPtr reason, [MarshalAs(UnmanagedType.Bool)] bool retaining, [MarshalAs(UnmanagedType.Bool)] bool async); + void Abort( + IntPtr reason, + [MarshalAs(UnmanagedType.Bool)] bool retaining, + [MarshalAs(UnmanagedType.Bool)] bool async); void GetTransactionInfo(out OletxXactTransInfo xactInfo); } diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/DtcInterfaces/ITransactionCloner.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/DtcInterfaces/ITransactionCloner.cs index 7ce0b361bdf5ff..731e72214f45a5 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/DtcInterfaces/ITransactionCloner.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/DtcInterfaces/ITransactionCloner.cs @@ -10,5 +10,17 @@ namespace System.Transactions.DtcProxyShim.DtcInterfaces; [ComImport, Guid("02656950-2152-11d0-944C-00A0C905416E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ITransactionCloner { + void Commit( + [MarshalAs(UnmanagedType.Bool)] bool fRetainingt, + [MarshalAs(UnmanagedType.U4)] OletxXacttc grfTC, + uint grfRM); + + void Abort( + IntPtr reason, + [MarshalAs(UnmanagedType.Bool)] bool retaining, + [MarshalAs(UnmanagedType.Bool)] bool async); + + void GetTransactionInfo(out OletxXactTransInfo xactInfo); + void CloneWithCommitDisabled([MarshalAs(UnmanagedType.Interface)] out ITransaction ppITransaction); } diff --git a/src/libraries/System.Transactions.Local/tests/OleTxTests.cs b/src/libraries/System.Transactions.Local/tests/OleTxTests.cs index e646c09a59326c..eaf2d1b972bc26 100644 --- a/src/libraries/System.Transactions.Local/tests/OleTxTests.cs +++ b/src/libraries/System.Transactions.Local/tests/OleTxTests.cs @@ -433,8 +433,8 @@ public void GetExportCookie() Assert.Equal(tx.TransactionInformation.DistributedIdentifier, tx2.TransactionInformation.DistributedIdentifier); }); - // Test currently skipped, #74745 - private void GetDtcTransaction() + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] + public void GetDtcTransaction() => Test(() => { using var tx = new CommittableTransaction(); From e00bd40840603aa68c74568338751979b5d59351 Mon Sep 17 00:00:00 2001 From: madelson <1269046+madelson@users.noreply.github.com> Date: Tue, 30 Aug 2022 12:13:51 -0400 Subject: [PATCH 032/107] Add CancellationToken-accepting overloads for SendPingAsync (#72338) * Add CancellationToken-accepting overloads for SendPingAsync (initial work). Provides "true" cancellation for async ping methods using either a token or the existing SendAsyncCancel() API. Fix #67260 * Address feedback from https://github.com/dotnet/runtime/pull/72338 * Feedback from https://github.com/dotnet/runtime/pull/72338 * Address feedback from https://github.com/dotnet/runtime/pull/72338#discussion_r946258155 --- .../System.Net.Ping/ref/System.Net.Ping.cs | 2 + .../System/Net/NetworkInformation/Ping.OSX.cs | 14 +- .../NetworkInformation/Ping.PingUtility.cs | 42 +++--- .../Net/NetworkInformation/Ping.RawSocket.cs | 96 ++++++------ .../Net/NetworkInformation/Ping.Unix.cs | 13 +- .../src/System/Net/NetworkInformation/Ping.cs | 137 ++++++++++++++---- .../tests/FunctionalTests/PingTest.cs | 49 +++++++ 7 files changed, 229 insertions(+), 124 deletions(-) diff --git a/src/libraries/System.Net.Ping/ref/System.Net.Ping.cs b/src/libraries/System.Net.Ping/ref/System.Net.Ping.cs index 53053181659f3d..d549c5e306575a 100644 --- a/src/libraries/System.Net.Ping/ref/System.Net.Ping.cs +++ b/src/libraries/System.Net.Ping/ref/System.Net.Ping.cs @@ -62,10 +62,12 @@ public void SendAsyncCancel() { } public System.Threading.Tasks.Task SendPingAsync(System.Net.IPAddress address, int timeout) { throw null; } public System.Threading.Tasks.Task SendPingAsync(System.Net.IPAddress address, int timeout, byte[] buffer) { throw null; } public System.Threading.Tasks.Task SendPingAsync(System.Net.IPAddress address, int timeout, byte[] buffer, System.Net.NetworkInformation.PingOptions? options) { throw null; } + public System.Threading.Tasks.Task SendPingAsync(System.Net.IPAddress address, System.TimeSpan timeout, byte[]? buffer = null, System.Net.NetworkInformation.PingOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { throw null; } public System.Threading.Tasks.Task SendPingAsync(string hostNameOrAddress) { throw null; } public System.Threading.Tasks.Task SendPingAsync(string hostNameOrAddress, int timeout) { throw null; } public System.Threading.Tasks.Task SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer) { throw null; } public System.Threading.Tasks.Task SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer, System.Net.NetworkInformation.PingOptions? options) { throw null; } + public System.Threading.Tasks.Task SendPingAsync(string hostNameOrAddress, System.TimeSpan timeout, byte[]? buffer = null, System.Net.NetworkInformation.PingOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { throw null; } } public partial class PingCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.OSX.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.OSX.cs index 98d561df06e1b8..b1258f3e560161 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.OSX.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.OSX.cs @@ -22,17 +22,7 @@ public partial class Ping private static PingReply SendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions? options) => SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options); - private async Task SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions? options) - { - Task t = SendIcmpEchoRequestOverRawSocketAsync(address, buffer, timeout, options); - PingReply reply = await t.ConfigureAwait(false); - - if (_canceled) - { - throw new OperationCanceledException(); - } - - return reply; - } + private Task SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions? options) + => SendIcmpEchoRequestOverRawSocketAsync(address, buffer, timeout, options); } } diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.PingUtility.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.PingUtility.cs index 7bdc4120cdb537..d887eb860be9d0 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.PingUtility.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.PingUtility.cs @@ -73,33 +73,35 @@ private PingReply SendWithPingUtility(IPAddress address, byte[] buffer, int time private async Task SendWithPingUtilityAsync(IPAddress address, byte[] buffer, int timeout, PingOptions? options) { - using (Process p = GetPingProcess(address, buffer, timeout, options)) + CancellationToken timeoutOrCancellationToken = _timeoutOrCancellationSource!.Token; + + using Process pingProcess = GetPingProcess(address, buffer, timeout, options); + pingProcess.Start(); + + try { - var processCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - p.EnableRaisingEvents = true; - p.Exited += (s, e) => processCompletion.SetResult(); - p.Start(); + await pingProcess.WaitForExitAsync(timeoutOrCancellationToken).ConfigureAwait(false); - try - { - await processCompletion.Task.WaitAsync(TimeSpan.FromMilliseconds(timeout)).ConfigureAwait(false); - } - catch (TimeoutException) - { - p.Kill(); - return CreatePingReply(IPStatus.TimedOut); - } + string stdout = await pingProcess.StandardOutput.ReadToEndAsync(timeoutOrCancellationToken).ConfigureAwait(false); - try + return ParsePingUtilityOutput(address, pingProcess.ExitCode, stdout); + } + catch (OperationCanceledException) when (timeoutOrCancellationToken.IsCancellationRequested) + { + if (!pingProcess.HasExited) { - string stdout = await p.StandardOutput.ReadToEndAsync().ConfigureAwait(false); - return ParsePingUtilityOutput(address, p.ExitCode, stdout); + pingProcess.Kill(); } - catch (Exception) + if (_canceled) { - // If the standard output cannot be successfully parsed, throw a generic PingException. - throw new PingException(SR.net_ping); + throw; } + return CreatePingReply(IPStatus.TimedOut); + } + catch (Exception e) + { + // If the standard output cannot be successfully read/parsed, throw a generic PingException. + throw new PingException(SR.net_ping, e); } } diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.RawSocket.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.RawSocket.cs index 2e1b213bf7e950..471c7453b7d853 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.RawSocket.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.RawSocket.cs @@ -276,67 +276,63 @@ private static PingReply SendIcmpEchoRequestOverRawSocket(IPAddress address, byt } } - private static async Task SendIcmpEchoRequestOverRawSocketAsync(IPAddress address, byte[] buffer, int timeout, PingOptions? options) + private async Task SendIcmpEchoRequestOverRawSocketAsync(IPAddress address, byte[] buffer, int timeout, PingOptions? options) { SocketConfig socketConfig = GetSocketConfig(address, buffer, timeout, options); - using (Socket socket = GetRawSocket(socketConfig)) - { - int ipHeaderLength = socketConfig.IsIpv4 ? MinIpHeaderLengthInBytes : 0; - CancellationTokenSource timeoutTokenSource = new CancellationTokenSource(timeout); + using Socket socket = GetRawSocket(socketConfig); + int ipHeaderLength = socketConfig.IsIpv4 ? MinIpHeaderLengthInBytes : 0; - try + try + { + CancellationToken timeoutOrCancellationToken = _timeoutOrCancellationSource!.Token; + + await socket.SendToAsync( + socketConfig.SendBuffer.AsMemory(), + SocketFlags.None, + socketConfig.EndPoint, + timeoutOrCancellationToken) + .ConfigureAwait(false); + + byte[] receiveBuffer = new byte[2 * (MaxIpHeaderLengthInBytes + IcmpHeaderLengthInBytes) + buffer.Length]; + + // Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response + // to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout. + // For example, when pinging the local host, we need to filter out our own echo requests that the socket reads. + long startingTimestamp = Stopwatch.GetTimestamp(); + while (!timeoutOrCancellationToken.IsCancellationRequested) { - await socket.SendToAsync( - new ArraySegment(socketConfig.SendBuffer), - SocketFlags.None, socketConfig.EndPoint, - timeoutTokenSource.Token) + SocketReceiveFromResult receiveResult = await socket.ReceiveFromAsync( + receiveBuffer.AsMemory(), + SocketFlags.None, + socketConfig.EndPoint, + timeoutOrCancellationToken) .ConfigureAwait(false); - byte[] receiveBuffer = new byte[2 * (MaxIpHeaderLengthInBytes + IcmpHeaderLengthInBytes) + buffer.Length]; - - // Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response - // to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout. - // For example, when pinging the local host, we need to filter out our own echo requests that the socket reads. - long startingTimestamp = Stopwatch.GetTimestamp(); - while (!timeoutTokenSource.IsCancellationRequested) + int bytesReceived = receiveResult.ReceivedBytes; + if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes) { - SocketReceiveFromResult receiveResult = await socket.ReceiveFromAsync( - new ArraySegment(receiveBuffer), - SocketFlags.None, - socketConfig.EndPoint, - timeoutTokenSource.Token) - .ConfigureAwait(false); - - int bytesReceived = receiveResult.ReceivedBytes; - if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes) - { - continue; // Not enough bytes to reconstruct IP header + ICMP header. - } + continue; // Not enough bytes to reconstruct IP header + ICMP header. + } - if (TryGetPingReply(socketConfig, receiveBuffer, bytesReceived, startingTimestamp, ref ipHeaderLength, out PingReply? reply)) - { - return reply; - } + if (TryGetPingReply(socketConfig, receiveBuffer, bytesReceived, startingTimestamp, ref ipHeaderLength, out PingReply? reply)) + { + return reply; } } - catch (SocketException ex) when (ex.SocketErrorCode == SocketError.TimedOut) - { - } - catch (SocketException ex) when (ex.SocketErrorCode == SocketError.MessageSize) - { - return CreatePingReply(IPStatus.PacketTooBig); - } - catch (OperationCanceledException) - { - } - finally - { - timeoutTokenSource.Dispose(); - } - - // We have exceeded our timeout duration, and no reply has been received. - return CreatePingReply(IPStatus.TimedOut); } + catch (SocketException ex) when (ex.SocketErrorCode == SocketError.TimedOut) + { + } + catch (SocketException ex) when (ex.SocketErrorCode == SocketError.MessageSize) + { + return CreatePingReply(IPStatus.PacketTooBig); + } + catch (OperationCanceledException) when (!_canceled) + { + } + + // We have exceeded our timeout duration, and no reply has been received. + return CreatePingReply(IPStatus.TimedOut); } private static PingReply CreatePingReply(IPStatus status, IPAddress? address = null, long rtt = 0) diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Unix.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Unix.cs index 987d0462d70cae..9a9bb7b167c649 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Unix.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.Unix.cs @@ -27,20 +27,11 @@ private PingReply SendPingCore(IPAddress address, byte[] buffer, int timeout, Pi return reply; } - private async Task SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions? options) + private Task SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions? options) { - Task t = RawSocketPermissions.CanUseRawSockets(address.AddressFamily) ? + return RawSocketPermissions.CanUseRawSockets(address.AddressFamily) ? SendIcmpEchoRequestOverRawSocketAsync(address, buffer, timeout, options) : SendWithPingUtilityAsync(address, buffer, timeout, options); - - PingReply reply = await t.ConfigureAwait(false); - - if (_canceled) - { - throw new OperationCanceledException(); - } - - return reply; } } } diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs index ca781ec245110b..c52263fcf6de8f 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs @@ -3,6 +3,7 @@ using System.ComponentModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; @@ -19,6 +20,8 @@ public partial class Ping : Component private SendOrPostCallback? _onPingCompletedDelegate; private bool _disposeRequested; private byte[]? _defaultSendBuffer; + private CancellationTokenSource? _timeoutOrCancellationSource; + // Used to differentiate between timeout and cancellation when _timeoutOrCancellationSource triggers private bool _canceled; // Thread safety: @@ -75,6 +78,7 @@ private void CheckDisposed() ObjectDisposedException.ThrowIf(_disposeRequested, this); } + [MemberNotNull(nameof(_timeoutOrCancellationSource))] private void CheckStart() { int currentStatus; @@ -83,6 +87,7 @@ private void CheckStart() currentStatus = _status; if (currentStatus == Free) { + _timeoutOrCancellationSource ??= new(); _canceled = false; _status = InProgress; _lockObject.Reset(); @@ -118,6 +123,10 @@ private void Finish() { Debug.Assert(_status == InProgress, $"Invalid status: {_status}"); _status = Free; + if (!_timeoutOrCancellationSource!.TryReset()) + { + _timeoutOrCancellationSource = null; + } _lockObject.Set(); } @@ -127,7 +136,6 @@ private void Finish() } } - // Cancels pending async requests, closes the handles. private void InternalDispose() { _disposeRequested = true; @@ -142,6 +150,8 @@ private void InternalDispose() _status = Disposed; } + _timeoutOrCancellationSource?.Dispose(); + InternalDisposeCore(); } @@ -555,33 +565,73 @@ public Task SendPingAsync(string hostNameOrAddress, int timeout, byte public Task SendPingAsync(IPAddress address, int timeout, byte[] buffer, PingOptions? options) { - CheckArgs(address, timeout, buffer, options); - return SendPingAsyncInternal(address, timeout, buffer, options); + return SendPingAsync(address, timeout, buffer, options, CancellationToken.None); } - private async Task SendPingAsyncInternal(IPAddress address, int timeout, byte[] buffer, PingOptions? options) + /// + /// Sends an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the computer that has the specified + /// , and receives a corresponding ICMP echo reply message from that computer as an asynchronous operation. This + /// overload allows you to specify a time-out value for the operation, a buffer to use for send and receive, control fragmentation and + /// Time-to-Live values, and a for the ICMP echo message packet. + /// + /// An IP address that identifies the computer that is the destination for the ICMP echo message. + /// The amount of time (after sending the echo message) to wait for the ICMP echo reply message. + /// + /// A array that contains data to be sent with the ICMP echo message and returned in the ICMP echo reply message. + /// The array cannot contain more than 65,500 bytes. + /// + /// A object used to control fragmentation and Time-to-Live values for the ICMP echo message packet. + /// The token to monitor for cancellation requests. The default value is . + /// The task object representing the asynchronous operation. + public Task SendPingAsync(IPAddress address, TimeSpan timeout, byte[]? buffer = null, PingOptions? options = null, CancellationToken cancellationToken = default) { - // Need to snapshot the address here, so we're sure that it's not changed between now - // and the operation, and to be sure that IPAddress.ToString() is called and not some override. - IPAddress addressSnapshot = GetAddressSnapshot(address); + return SendPingAsync(address, ToTimeoutMilliseconds(timeout), buffer ?? DefaultSendBuffer, options, cancellationToken); + } - CheckStart(); - try - { - Task pingReplyTask = SendPingAsyncCore(addressSnapshot, buffer, timeout, options); - return await pingReplyTask.ConfigureAwait(false); - } - catch (Exception e) when (e is not PlatformNotSupportedException) - { - throw new PingException(SR.net_ping, e); - } - finally - { - Finish(); - } + private Task SendPingAsync(IPAddress address, int timeout, byte[] buffer, PingOptions? options, CancellationToken cancellationToken) + { + CheckArgs(address, timeout, buffer, options); + + return SendPingAsyncInternal( + // Need to snapshot the address here, so we're sure that it's not changed between now + // and the operation, and to be sure that IPAddress.ToString() is called and not some override. + GetAddressSnapshot(address), + static (address, cancellationToken) => new ValueTask(address), + timeout, + buffer, + options, + cancellationToken); } public Task SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions? options) + { + return SendPingAsync(hostNameOrAddress, timeout, buffer, options, CancellationToken.None); + } + + /// + /// Sends an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the specified computer, and + /// receives a corresponding ICMP echo reply message from that computer as an asynchronous operation. This overload allows you to + /// specify a time-out value for the operation, a buffer to use for send and receive, control fragmentation and Time-to-Live values, + /// and a for the ICMP echo message packet. + /// + /// + /// The computer that is the destination for the ICMP echo message. The value specified for this parameter can be a host name or a + /// string representation of an IP address. + /// + /// The amount of time (after sending the echo message) to wait for the ICMP echo reply message. + /// + /// A array that contains data to be sent with the ICMP echo message and returned in the ICMP echo reply message. + /// The array cannot contain more than 65,500 bytes. + /// + /// A object used to control fragmentation and Time-to-Live values for the ICMP echo message packet. + /// The token to monitor for cancellation requests. The default value is . + /// The task object representing the asynchronous operation. + public Task SendPingAsync(string hostNameOrAddress, TimeSpan timeout, byte[]? buffer = null, PingOptions? options = null, CancellationToken cancellationToken = default) + { + return SendPingAsync(hostNameOrAddress, ToTimeoutMilliseconds(timeout), buffer ?? DefaultSendBuffer, options, cancellationToken); + } + + private Task SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions? options, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(hostNameOrAddress)) { @@ -590,12 +640,19 @@ public Task SendPingAsync(string hostNameOrAddress, int timeout, byte if (IPAddress.TryParse(hostNameOrAddress, out IPAddress? address)) { - return SendPingAsync(address, timeout, buffer, options); + return SendPingAsync(address, timeout, buffer, options, cancellationToken); } CheckArgs(timeout, buffer, options); - return GetAddressAndSendAsync(hostNameOrAddress, timeout, buffer, options); + return SendPingAsyncInternal( + hostNameOrAddress, + static async (hostName, cancellationToken) => + (await Dns.GetHostAddressesAsync(hostName, cancellationToken).ConfigureAwait(false))[0], + timeout, + buffer, + options, + cancellationToken); } private static int ToTimeoutMilliseconds(TimeSpan timeout) @@ -614,9 +671,7 @@ public void SendAsyncCancel() { if (!_lockObject.IsSet) { - // As in the .NET Framework, this doesn't actually cancel an in-progress operation. It just marks it such that - // when the operation completes, it's flagged as canceled. - _canceled = true; + SetCanceled(); } } @@ -625,6 +680,12 @@ public void SendAsyncCancel() _lockObject.Wait(); } + private void SetCanceled() + { + _canceled = true; + _timeoutOrCancellationSource?.Cancel(); + } + private PingReply GetAddressAndSend(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions? options) { CheckStart(); @@ -643,16 +704,30 @@ private PingReply GetAddressAndSend(string hostNameOrAddress, int timeout, byte[ } } - private async Task GetAddressAndSendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions? options) + private async Task SendPingAsyncInternal( + TArg getAddressArg, + Func> getAddress, + int timeout, + byte[] buffer, + PingOptions? options, + CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); + CheckStart(); try { - IPAddress[] addresses = await Dns.GetHostAddressesAsync(hostNameOrAddress).ConfigureAwait(false); - Task pingReplyTask = SendPingAsyncCore(addresses[0], buffer, timeout, options); - return await pingReplyTask.ConfigureAwait(false); + using CancellationTokenRegistration _ = cancellationToken.UnsafeRegister(static state => ((Ping)state!).SetCanceled(), this); + + IPAddress address = await getAddress(getAddressArg, _timeoutOrCancellationSource.Token).ConfigureAwait(false); + + Task pingTask = SendPingAsyncCore(address, buffer, timeout, options); + // Note: we set the cancellation-based timeout only after resolving the address and initiating the ping with the + // intent that the timeout applies solely to the ping operation rather than to any setup steps. + _timeoutOrCancellationSource.CancelAfter(timeout); + return await pingTask.ConfigureAwait(false); } - catch (Exception e) when (e is not PlatformNotSupportedException) + catch (Exception e) when (e is not PlatformNotSupportedException && !(e is OperationCanceledException && _canceled)) { throw new PingException(SR.net_ping, e); } diff --git a/src/libraries/System.Net.Ping/tests/FunctionalTests/PingTest.cs b/src/libraries/System.Net.Ping/tests/FunctionalTests/PingTest.cs index 253642e5f592f5..754a26a60fd4ed 100644 --- a/src/libraries/System.Net.Ping/tests/FunctionalTests/PingTest.cs +++ b/src/libraries/System.Net.Ping/tests/FunctionalTests/PingTest.cs @@ -12,6 +12,7 @@ using Xunit; using Xunit.Abstractions; +using System.Threading; namespace System.Net.NetworkInformation.Tests { @@ -663,6 +664,54 @@ await SendBatchPingAsync( }); } + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] + [InlineData(true)] + [InlineData(false)] + public async Task SendPingAsyncWithAlreadyCanceledToken(bool useIPAddress) + { + using CancellationTokenSource source = new(); + source.Cancel(); + + using Ping ping = new(); + Task pingTask = useIPAddress + ? ping.SendPingAsync(await TestSettings.GetLocalIPAddressAsync(), TimeSpan.FromSeconds(5), cancellationToken: source.Token) + : ping.SendPingAsync(TestSettings.LocalHost, TimeSpan.FromSeconds(5), cancellationToken: source.Token); + await Assert.ThrowsAnyAsync(() => pingTask); + Assert.True(pingTask.IsCanceled); + + // ensure that previous cancellation does not prevent future success + PingReply reply = useIPAddress + ? await ping.SendPingAsync(await TestSettings.GetLocalIPAddressAsync(), TimeSpan.FromSeconds(5)) + : await ping.SendPingAsync(TestSettings.LocalHost, TimeSpan.FromSeconds(5)); + Assert.Equal(IPStatus.Success, reply.Status); + } + + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + [OuterLoop] // Depends on external host and assumption that successful ping takes long enough for cancellation to go through first + public async Task CancelSendPingAsync(bool useIPAddress, bool useCancellationToken) + { + using CancellationTokenSource source = new(); + + using Ping ping = new(); + Task pingTask = useIPAddress + ? ping.SendPingAsync((await Dns.GetHostAddressesAsync(Test.Common.Configuration.Ping.PingHost))[0], TimeSpan.FromSeconds(5), cancellationToken: source.Token) + : ping.SendPingAsync(Test.Common.Configuration.Ping.PingHost, TimeSpan.FromSeconds(5), cancellationToken: source.Token); + if (useCancellationToken) + { + source.Cancel(); + } + else + { + ping.SendAsyncCancel(); + } + await Assert.ThrowsAnyAsync(() => pingTask); + Assert.True(pingTask.IsCanceled); + } + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] [OuterLoop] // Depends on external host and assumption that network respects and does not change TTL public async Task SendPingToExternalHostWithLowTtlTest() From 2ed931d06a662eb416e363f2dde798729eae4c25 Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Tue, 30 Aug 2022 12:22:37 -0400 Subject: [PATCH 033/107] CI: Fix helix test results reporting (#74788) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * CI: Fix helix test results reporting PR #73060 broke uploading of helix test results. This was caused by the change: ```xml @(HelixPostCommand) ``` This is overwriting the existing value of `$(HelixPostCommands)`, which gets set to have the upload script invocation in https://github.com/dotnet/arcade/blob/34dff939b4a91e4693f78a856e0e055c1a3f3fba/src/Microsoft.DotNet.Helix/Sdk/tools/azure-pipelines/AzurePipelines.MonoQueue.targets#L8-L15 at evaluation time. Fix by *appending* to the property. Thanks to ChadNedzlek for finding the cause! Fixes https://github.com/dotnet/runtime/issues/74699 . * Disable failing tests, see https://github.com/dotnet/runtime/issues/74781 Co-authored-by: Alexander Köplinger --- .../System.Numerics.Vectors/tests/GenericVectorTests.cs | 2 ++ src/libraries/sendtohelixhelp.proj | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/libraries/System.Numerics.Vectors/tests/GenericVectorTests.cs b/src/libraries/System.Numerics.Vectors/tests/GenericVectorTests.cs index f4d2904a753614..3d095d04b64520 100644 --- a/src/libraries/System.Numerics.Vectors/tests/GenericVectorTests.cs +++ b/src/libraries/System.Numerics.Vectors/tests/GenericVectorTests.cs @@ -848,6 +848,7 @@ public void VectorSingleEqualsNaNTest() } [Fact] + [ActiveIssue("https://github.com/dotnet/runtime/issues/74781", TestRuntimes.Mono)] public void VectorDoubleEqualsNonCanonicalNaNTest() { // max 8 bit exponent, just under half max mantissa @@ -872,6 +873,7 @@ public void VectorDoubleEqualsNonCanonicalNaNTest() } [Fact] + [ActiveIssue("https://github.com/dotnet/runtime/issues/74781", TestRuntimes.Mono)] public void VectorSingleEqualsNonCanonicalNaNTest() { // max 11 bit exponent, just under half max mantissa diff --git a/src/libraries/sendtohelixhelp.proj b/src/libraries/sendtohelixhelp.proj index f7fadf8a6323fe..6fc601db985d6e 100644 --- a/src/libraries/sendtohelixhelp.proj +++ b/src/libraries/sendtohelixhelp.proj @@ -172,8 +172,8 @@ - @(HelixPreCommand) - @(HelixPostCommand) + $(HelixPreCommands);@(HelixPreCommand) + $(HelixPostCommands);@(HelixPostCommand) $(HelixCommandPrefix) @(HelixCommandPrefixItem -> 'set "%(Identity)"', ' & ') $(HelixCommandPrefix) @(HelixCommandPrefixItem, ' ') true From f825814b3561c5c7aa8d66773b338944c2c72a3c Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Tue, 30 Aug 2022 09:35:55 -0700 Subject: [PATCH 034/107] Fix incorrect "illegal XML comment chars" check (#74787) Also adds regression tests --- .../src/System/Xml/Core/XmlTextWriter.cs | 2 +- .../System.Xml.RW.XmlWriter.Tests.csproj | 1 + .../tests/XmlWriter/XmlTextWriterTests.cs | 92 +++++++++++++++++++ 3 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 src/libraries/System.Private.Xml/tests/XmlWriter/XmlTextWriterTests.cs diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs index c2aa7970b546f6..d593a97e7d56ec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs @@ -760,7 +760,7 @@ public override void WriteComment(string? text) { try { - if (null != text && (text.Contains("--") || text.StartsWith('-'))) + if (null != text && (text.Contains("--") || text.EndsWith('-'))) { throw new ArgumentException(SR.Xml_InvalidCommentChars); } diff --git a/src/libraries/System.Private.Xml/tests/XmlWriter/System.Xml.RW.XmlWriter.Tests.csproj b/src/libraries/System.Private.Xml/tests/XmlWriter/System.Xml.RW.XmlWriter.Tests.csproj index c3e76cb1a30474..3e074e9a835e3f 100644 --- a/src/libraries/System.Private.Xml/tests/XmlWriter/System.Xml.RW.XmlWriter.Tests.csproj +++ b/src/libraries/System.Private.Xml/tests/XmlWriter/System.Xml.RW.XmlWriter.Tests.csproj @@ -7,5 +7,6 @@ + \ No newline at end of file diff --git a/src/libraries/System.Private.Xml/tests/XmlWriter/XmlTextWriterTests.cs b/src/libraries/System.Private.Xml/tests/XmlWriter/XmlTextWriterTests.cs new file mode 100644 index 00000000000000..5b1063a1fc6060 --- /dev/null +++ b/src/libraries/System.Private.Xml/tests/XmlWriter/XmlTextWriterTests.cs @@ -0,0 +1,92 @@ +// 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.IO; +using Xunit; + +namespace System.Xml.Tests +{ + public class XmlTextWriterTests + { + public static IEnumerable PositiveTestCases + { + get + { + yield return new string[] { null }; // will be normalized to empty string + yield return new string[] { "" }; + yield return new string[] { "This is some data." }; + yield return new string[] { " << brackets and whitespace >> " }; // brackets & surrounding whitespace are ok + yield return new string[] { "&" }; // entities are ok (treated opaquely) + yield return new string[] { "Hello\r\nthere." }; // newlines are ok + yield return new string[] { "\U0001F643 Upside-down smiley \U0001F643" }; // correctly paired surrogates are ok + yield return new string[] { "\uFFFD\uFFFE\uFFFF" }; // replacement char & private use are ok + } + } + + public static IEnumerable BadSurrogateTestCases + { + get + { + yield return new string[] { "\uD800 Unpaired high surrogate." }; + yield return new string[] { "\uDFFF Unpaired low surrogate." }; + yield return new string[] { "Unpaired high surrogate at end. \uD800" }; + yield return new string[] { "Unpaired low surrogate at end. \uDFFF" }; + yield return new string[] { "Unpaired surrogates \uDFFF\uD800 in middle." }; + } + } + + [Theory] + [MemberData(nameof(PositiveTestCases))] + [InlineData("]]")] // ]] without trailing > is ok + [InlineData("-->")] // end of comment marker ok (meaningless to cdata tag) + public void WriteCData_SuccessCases(string cdataText) + { + StringWriter sw = new StringWriter(); + XmlTextWriter xw = new XmlTextWriter(sw); + + xw.WriteCData(cdataText); + + Assert.Equal($"", sw.ToString()); + } + + [Theory] + [MemberData(nameof(BadSurrogateTestCases), DisableDiscoveryEnumeration = true)] // disable enumeration to avoid test harness misinterpreting unpaired surrogates + [InlineData("]]>")] // end of cdata marker forbidden (ambiguous close tag) + public void WriteCData_FailureCases(string cdataText) + { + StringWriter sw = new StringWriter(); + XmlTextWriter xw = new XmlTextWriter(sw); + + Assert.Throws(() => xw.WriteCData(cdataText)); + } + + [Theory] + [MemberData(nameof(PositiveTestCases))] + [InlineData("-12345")] // hyphen at beginning is ok + [InlineData("123- -45")] // single hyphens are ok in middle + [InlineData("]]>")] // end of cdata marker ok (meaningless to comment tag) + public void WriteComment_SuccessCases(string commentText) + { + StringWriter sw = new StringWriter(); + XmlTextWriter xw = new XmlTextWriter(sw); + + xw.WriteComment(commentText); + + Assert.Equal($"", sw.ToString()); + } + + [Theory] + [MemberData(nameof(BadSurrogateTestCases), DisableDiscoveryEnumeration = true)] // disable enumeration to avoid test harness misinterpreting unpaired surrogates + [InlineData("123--45")] // double-hyphen in middle is forbidden (ambiguous comment close tag) + [InlineData("12345-")] // hyphen at end is forbidden (ambiguous comment close tag) + [InlineData("-->")] // end of comment marker forbidden (ambiguous close tag) + public void WriteComment_FailureCases(string commentText) + { + StringWriter sw = new StringWriter(); + XmlTextWriter xw = new XmlTextWriter(sw); + + Assert.Throws(() => xw.WriteComment(commentText)); + } + } +} From 06f944a6e7ec9f8e87d84fbb0d62a4a6a37d7361 Mon Sep 17 00:00:00 2001 From: Pavel Savara Date: Tue, 30 Aug 2022 19:09:07 +0200 Subject: [PATCH 035/107] [wasm][test] install handlers for unhandled exceptions on browser (#74751) add internal test handler for unhandled exceptions on browser --- .../Wasm.Build.Tests/WasmTemplateTests.cs | 2 +- src/mono/wasm/runtime/run-outer.ts | 23 +++++++++++++++++++ src/mono/wasm/runtime/run.ts | 16 +++++++------ src/mono/wasm/test-main.js | 3 ++- 4 files changed, 35 insertions(+), 9 deletions(-) diff --git a/src/mono/wasm/Wasm.Build.Tests/WasmTemplateTests.cs b/src/mono/wasm/Wasm.Build.Tests/WasmTemplateTests.cs index 08fc1180c849bd..5b41e3a1b03021 100644 --- a/src/mono/wasm/Wasm.Build.Tests/WasmTemplateTests.cs +++ b/src/mono/wasm/Wasm.Build.Tests/WasmTemplateTests.cs @@ -41,7 +41,7 @@ private void UpdateBrowserMainJs() string mainJsPath = Path.Combine(_projectDir!, "main.js"); string mainJsContent = File.ReadAllText(mainJsPath); - mainJsContent = mainJsContent.Replace(".create()", ".withConsoleForwarding().withElementOnExit().withExitCodeLogging().create()"); + mainJsContent = mainJsContent.Replace(".create()", ".withConsoleForwarding().withElementOnExit().withExitCodeLogging().withExitOnUnhandledError().create()"); File.WriteAllText(mainJsPath, mainJsContent); } diff --git a/src/mono/wasm/runtime/run-outer.ts b/src/mono/wasm/runtime/run-outer.ts index eb0a83a12c54ae..4ff468fce4bb69 100644 --- a/src/mono/wasm/runtime/run-outer.ts +++ b/src/mono/wasm/runtime/run-outer.ts @@ -57,6 +57,29 @@ class HostBuilder implements DotnetHostBuilder { } } + // internal + withExitOnUnhandledError(): DotnetHostBuilder { + const handler = function fatal_handler(event: Event, error: any) { + event.preventDefault(); + try { + mono_exit(1, error); + } catch (err) { + // no not re-throw from the fatal handler + } + }; + try { + // it seems that emscripten already does the right thing for NodeJs and that there is no good solution for V8 shell. + if (ENVIRONMENT_IS_WEB) { + window.addEventListener("unhandledrejection", (event) => handler(event, event.reason)); + window.addEventListener("error", (event) => handler(event, event.error)); + } + return this; + } catch (err) { + mono_exit(1, err); + throw err; + } + } + // internal withAsyncFlushOnExit(): DotnetHostBuilder { try { diff --git a/src/mono/wasm/runtime/run.ts b/src/mono/wasm/runtime/run.ts index 2dca623792ad45..1e224837222ca0 100644 --- a/src/mono/wasm/runtime/run.ts +++ b/src/mono/wasm/runtime/run.ts @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { ENVIRONMENT_IS_WEB, INTERNAL, Module, runtimeHelpers } from "./imports"; +import { ENVIRONMENT_IS_WEB, Module, runtimeHelpers } from "./imports"; import { mono_wasm_wait_for_debugger } from "./debug"; import { abort_startup, mono_wasm_set_main_args } from "./startup"; import cwraps from "./cwraps"; @@ -108,12 +108,14 @@ async function flush_node_streams() { function set_exit_code_and_quit_now(exit_code: number, reason?: any): void { if (runtimeHelpers.ExitStatus) { if (reason && !(reason instanceof runtimeHelpers.ExitStatus)) { - if (reason instanceof Error) - Module.printErr(INTERNAL.mono_wasm_stringify_as_error_with_stack(reason)); - else if (typeof reason == "string") - Module.printErr(reason); - else - Module.printErr(JSON.stringify(reason)); + if (!runtimeHelpers.config.logExitCode) { + if (reason instanceof Error) + Module.printErr(mono_wasm_stringify_as_error_with_stack(reason)); + else if (typeof reason == "string") + Module.printErr(reason); + else + Module.printErr(JSON.stringify(reason)); + } } else { reason = new runtimeHelpers.ExitStatus(exit_code); diff --git a/src/mono/wasm/test-main.js b/src/mono/wasm/test-main.js index bac3f856160c57..8d9c391c981907 100644 --- a/src/mono/wasm/test-main.js +++ b/src/mono/wasm/test-main.js @@ -259,6 +259,7 @@ async function run() { .withVirtualWorkingDirectory(runArgs.workingDirectory) .withEnvironmentVariables(runArgs.environmentVariables) .withDiagnosticTracing(runArgs.diagnosticTracing) + .withExitOnUnhandledError() .withExitCodeLogging() .withElementOnExit(); @@ -266,7 +267,7 @@ async function run() { dotnet .withEnvironmentVariable("NodeJSPlatform", process.platform) .withAsyncFlushOnExit(); - + const modulesToLoad = runArgs.environmentVariables["NPM_MODULES"]; if (modulesToLoad) { dotnet.withModuleConfig({ From c43a30c57336cad0fc7d4cb5029f61592a38c67f Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Tue, 30 Aug 2022 10:13:38 -0700 Subject: [PATCH 036/107] Use current version of clang and llvm in Linux prereqs (#74811) Fixes #74790 --- docs/workflow/requirements/linux-requirements.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/workflow/requirements/linux-requirements.md b/docs/workflow/requirements/linux-requirements.md index 6f9c9e0d5a6750..8a3f8521b34fbe 100644 --- a/docs/workflow/requirements/linux-requirements.md +++ b/docs/workflow/requirements/linux-requirements.md @@ -30,14 +30,14 @@ Building the repo requires CMake 3.14.5 or newer on Linux. Add Kitware's APT fee Install the following packages for the toolchain: - cmake -- llvm-9 -- clang-9 +- llvm +- clang - build-essential - python - curl - git -- lldb-6.0 -- liblldb-6.0-dev +- lldb +- liblldb-dev - libunwind8 - libunwind8-dev - gettext @@ -50,8 +50,8 @@ Install the following packages for the toolchain: - ninja-build (optional, enables building native code with ninja instead of make) ``` -sudo apt-get install -y cmake llvm-9 clang-9 \ -build-essential python curl git lldb-6.0 liblldb-6.0-dev \ +sudo apt-get install -y cmake llvm clang \ +build-essential python curl git lldb liblldb-dev \ libunwind8 libunwind8-dev gettext libicu-dev liblttng-ust-dev \ libssl-dev libnuma-dev libkrb5-dev zlib1g-dev ninja-build ``` From 84454ad44d5f91c40b8cdd04e4df2b90a50d49cb Mon Sep 17 00:00:00 2001 From: Hyungju Lee Date: Wed, 31 Aug 2022 02:53:37 +0900 Subject: [PATCH 037/107] Fix to skip adding self as next unrelated code list (#74208) Co-authored-by: Dong-Heon Jung Co-authored-by: Dong-Heon Jung --- src/coreclr/vm/readytoruninfo.cpp | 4 ++-- src/coreclr/vm/readytoruninfo.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/coreclr/vm/readytoruninfo.cpp b/src/coreclr/vm/readytoruninfo.cpp index 0b93ff8aebd60b..0abafc160adeb4 100644 --- a/src/coreclr/vm/readytoruninfo.cpp +++ b/src/coreclr/vm/readytoruninfo.cpp @@ -619,7 +619,7 @@ void ReadyToRunInfo::RegisterUnrelatedR2RModule() { ReadyToRunInfo* oldGlobalValue; oldGlobalValue = s_pGlobalR2RModules; - if (InterlockedCompareExchangeT(&m_pNextR2RForUnrelatedCode, oldGlobalValue, NULL) != NULL) + if (InterlockedCompareExchangeT(&m_pNextR2RForUnrelatedCode, dac_cast(dac_cast(oldGlobalValue) | 0x1), NULL) != NULL) { // Some other thread is registering or has registered this R2R image for unrelated generics // ReadyToRun code loading. we can simply return, as this process cannot fail. @@ -629,7 +629,7 @@ void ReadyToRunInfo::RegisterUnrelatedR2RModule() while (InterlockedCompareExchangeT(&s_pGlobalR2RModules, this, oldGlobalValue) != oldGlobalValue) { oldGlobalValue = s_pGlobalR2RModules; - m_pNextR2RForUnrelatedCode = oldGlobalValue; + m_pNextR2RForUnrelatedCode = dac_cast(dac_cast(oldGlobalValue) | 0x1); } } } diff --git a/src/coreclr/vm/readytoruninfo.h b/src/coreclr/vm/readytoruninfo.h index ca5950a530f26d..5b400d19dbbadc 100644 --- a/src/coreclr/vm/readytoruninfo.h +++ b/src/coreclr/vm/readytoruninfo.h @@ -94,7 +94,7 @@ class ReadyToRunInfo static PTR_ReadyToRunInfo ComputeAlternateGenericLocationForR2RCode(MethodDesc *pMethod); static PTR_ReadyToRunInfo GetUnrelatedR2RModules(); - PTR_ReadyToRunInfo GetNextUnrelatedR2RModule() { LIMITED_METHOD_CONTRACT; return m_pNextR2RForUnrelatedCode; } + PTR_ReadyToRunInfo GetNextUnrelatedR2RModule() { LIMITED_METHOD_CONTRACT; return dac_cast(dac_cast(m_pNextR2RForUnrelatedCode) & ~0x1); } void RegisterUnrelatedR2RModule(); static PTR_ReadyToRunInfo Initialize(Module * pModule, AllocMemTracker *pamTracker); From a755524d0b797774bb3741b0a6ed24414f8c2ad6 Mon Sep 17 00:00:00 2001 From: Tlakaelel Axayakatl Ceja Date: Tue, 30 Aug 2022 11:07:42 -0700 Subject: [PATCH 038/107] Add support for Requires in events (#72651) Add support to ask for Requires in events Add support for printing correctly event members Move PropertyPseudoDesc to be ilc specific --- .../Common/Compiler/DisplayNameHelpers.cs | 17 ++++++ .../tools/Common/Compiler/MethodExtensions.cs | 20 ------- .../Compiler/Dataflow/DiagnosticUtilities.cs | 21 ++++++++ .../DynamicDependencyAttributeAlgorithm.cs | 2 - .../Compiler/EventPseudoDesc.cs | 8 +++ .../Compiler/PropertyPseudoDesc.cs | 0 .../Compiler/PseudoDescExtensions.cs | 54 +++++++++++++++++++ .../ILCompiler.Compiler.csproj | 5 +- .../ILCompiler.ReadyToRun.csproj | 1 - 9 files changed, 103 insertions(+), 25 deletions(-) rename src/coreclr/tools/{Common => aot/ILCompiler.Compiler}/Compiler/PropertyPseudoDesc.cs (100%) create mode 100644 src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/PseudoDescExtensions.cs diff --git a/src/coreclr/tools/Common/Compiler/DisplayNameHelpers.cs b/src/coreclr/tools/Common/Compiler/DisplayNameHelpers.cs index 4ff382a8bf6e1b..55be359be4bea0 100644 --- a/src/coreclr/tools/Common/Compiler/DisplayNameHelpers.cs +++ b/src/coreclr/tools/Common/Compiler/DisplayNameHelpers.cs @@ -39,6 +39,7 @@ public static string GetDisplayName(this MethodDesc method) { sb.Append(method.OwningType.GetDisplayNameWithoutNamespace()); } +#if !READYTORUN else if (method.GetPropertyForAccessor() is PropertyPseudoDesc property) { sb.Append(property.Name); @@ -46,6 +47,22 @@ public static string GetDisplayName(this MethodDesc method) sb.Append(property.GetMethod == method ? "get" : "set"); return sb.ToString(); } + else if (method.GetEventForAccessor() is EventPseudoDesc @event) + { + sb.Append(@event.Name); + sb.Append('.'); + string accessor; + if (method.Name == @event.AddMethod.Name) + accessor = "add"; + else if (method.Name == @event.RemoveMethod.Name) + accessor = "remove"; + else if (method.Name == @event.RaiseMethod.Name) + accessor = "raise"; + else + throw new NotSupportedException(); + sb.Append(accessor); + } +#endif else { sb.Append(method.Name); diff --git a/src/coreclr/tools/Common/Compiler/MethodExtensions.cs b/src/coreclr/tools/Common/Compiler/MethodExtensions.cs index 7e22fe2c4a7b87..6b7513410e3188 100644 --- a/src/coreclr/tools/Common/Compiler/MethodExtensions.cs +++ b/src/coreclr/tools/Common/Compiler/MethodExtensions.cs @@ -114,25 +114,5 @@ public static bool NotCallableWithoutOwningEEType(this MethodDesc method) (owningType is not MetadataType mdType || !mdType.IsModuleType) && /* Compiler parks some instance methods on the type */ !method.IsSharedByGenericInstantiations; /* Current impl limitation; can be lifted */ } - - public static PropertyPseudoDesc GetPropertyForAccessor(this MethodDesc accessor) - { - if (accessor.GetTypicalMethodDefinition() is not EcmaMethod ecmaAccessor) - return null; - - var type = (EcmaType)ecmaAccessor.OwningType; - var reader = type.MetadataReader; - foreach (var propertyHandle in reader.GetTypeDefinition(type.Handle).GetProperties()) - { - var accessors = reader.GetPropertyDefinition(propertyHandle).GetAccessors(); - if (ecmaAccessor.Handle == accessors.Getter - || ecmaAccessor.Handle == accessors.Setter) - { - return new PropertyPseudoDesc(type, propertyHandle); - } - } - - return null; - } } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/DiagnosticUtilities.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/DiagnosticUtilities.cs index 18246282ca012c..af70f21e31233b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/DiagnosticUtilities.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/DiagnosticUtilities.cs @@ -78,6 +78,9 @@ internal static bool TryGetRequiresAttribute(TypeSystemEntity member, string req case PropertyPseudoDesc property: decoded = property.GetDecodedCustomAttribute("System.Diagnostics.CodeAnalysis", requiresAttributeName); break; + case EventPseudoDesc @event: + decoded = @event.GetDecodedCustomAttribute("System.Diagnostics.CodeAnalysis", requiresAttributeName); + break; default: Debug.Fail("Trying to operate with unsupported TypeSystemEntity " + member.GetType().ToString()); break; @@ -103,6 +106,20 @@ internal static bool TryGetRequiresAttribute(TypeSystemEntity member, string req return metadataReader.GetCustomAttribute(attributeHandle).DecodeValue(new CustomAttributeTypeProvider(ecmaType.EcmaModule)); } + public static CustomAttributeValue? GetDecodedCustomAttribute(this EventPseudoDesc @event, string attributeNamespace, string attributeName) + { + var ecmaType = @event.OwningType as EcmaType; + var metadataReader = ecmaType.MetadataReader; + + var attributeHandle = metadataReader.GetCustomAttributeHandle(@event.GetCustomAttributes, + attributeNamespace, attributeName); + + if (attributeHandle.IsNil) + return null; + + return metadataReader.GetCustomAttribute(attributeHandle).DecodeValue(new CustomAttributeTypeProvider(ecmaType.EcmaModule)); + } + internal static string GetRequiresAttributeMessage(CustomAttributeValue attribute) { if (attribute.FixedArguments.Length != 0) @@ -183,6 +200,9 @@ internal static bool DoesFieldRequire(this FieldDesc field, string requiresAttri internal static bool DoesPropertyRequire(this PropertyPseudoDesc property, string requiresAttribute, [NotNullWhen(returnValue: true)] out CustomAttributeValue? attribute) => TryGetRequiresAttribute(property, requiresAttribute, out attribute); + internal static bool DoesEventRequire(this EventPseudoDesc @event, string requiresAttribute, [NotNullWhen(returnValue: true)] out CustomAttributeValue? attribute) => + TryGetRequiresAttribute(@event, requiresAttribute, out attribute); + /// /// Determines if member requires (and thus any usage of such method should be warned about). /// @@ -196,6 +216,7 @@ internal static bool DoesMemberRequire(this TypeSystemEntity member, string requ MethodDesc method => DoesMethodRequire(method, requiresAttribute, out attribute), FieldDesc field => DoesFieldRequire(field, requiresAttribute, out attribute), PropertyPseudoDesc property => DoesPropertyRequire(property, requiresAttribute, out attribute), + EventPseudoDesc @event => DoesEventRequire(@event, requiresAttribute, out attribute), _ => false }; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DynamicDependencyAttributeAlgorithm.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DynamicDependencyAttributeAlgorithm.cs index 4e3afab67672f0..8b59f34554f9e0 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DynamicDependencyAttributeAlgorithm.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DynamicDependencyAttributeAlgorithm.cs @@ -1,11 +1,9 @@ // 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.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Reflection.Metadata; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/EventPseudoDesc.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/EventPseudoDesc.cs index a21a309781b8f7..041d825d9cf5fc 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/EventPseudoDesc.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/EventPseudoDesc.cs @@ -47,6 +47,14 @@ public MethodDesc RaiseMethod } } + public CustomAttributeHandleCollection GetCustomAttributes + { + get + { + return Definition.GetCustomAttributes(); + } + } + public MetadataType OwningType { get diff --git a/src/coreclr/tools/Common/Compiler/PropertyPseudoDesc.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/PropertyPseudoDesc.cs similarity index 100% rename from src/coreclr/tools/Common/Compiler/PropertyPseudoDesc.cs rename to src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/PropertyPseudoDesc.cs diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/PseudoDescExtensions.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/PseudoDescExtensions.cs new file mode 100644 index 00000000000000..ef5c83d194f064 --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/PseudoDescExtensions.cs @@ -0,0 +1,54 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Internal.TypeSystem; +using Internal.TypeSystem.Ecma; + +using Debug = System.Diagnostics.Debug; + +namespace ILCompiler +{ + public static class PseudoDescExtensions + { + public static PropertyPseudoDesc GetPropertyForAccessor(this MethodDesc accessor) + { + if (accessor.GetTypicalMethodDefinition() is not EcmaMethod ecmaAccessor) + return null; + + var type = (EcmaType)ecmaAccessor.OwningType; + var reader = type.MetadataReader; + foreach (var propertyHandle in reader.GetTypeDefinition(type.Handle).GetProperties()) + { + var accessors = reader.GetPropertyDefinition(propertyHandle).GetAccessors(); + if (ecmaAccessor.Handle == accessors.Getter + || ecmaAccessor.Handle == accessors.Setter) + { + return new PropertyPseudoDesc(type, propertyHandle); + } + } + + return null; + } + + public static EventPseudoDesc GetEventForAccessor(this MethodDesc accessor) + { + if (accessor.GetTypicalMethodDefinition() is not EcmaMethod ecmaAccessor) + return null; + + var type = (EcmaType)ecmaAccessor.OwningType; + var reader = type.MetadataReader; + foreach (var eventHandle in reader.GetTypeDefinition(type.Handle).GetEvents()) + { + var accessors = reader.GetEventDefinition(eventHandle).GetAccessors(); + if (ecmaAccessor.Handle == accessors.Adder + || ecmaAccessor.Handle == accessors.Remover + || ecmaAccessor.Handle == accessors.Raiser) + { + return new EventPseudoDesc(type, eventHandle); + } + } + + return null; + } + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj index c87928b82911aa..214570667ca971 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj @@ -310,7 +310,6 @@ - @@ -320,6 +319,7 @@ + @@ -408,8 +408,8 @@ - + @@ -578,6 +578,7 @@ + diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj index 458daf1781a737..7957233a37ee51 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj @@ -101,7 +101,6 @@ - From cfd6cd10a6afcf7e60c4adaa78e5aad176cabb7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20K=C3=B6plinger?= Date: Tue, 30 Aug 2022 20:14:11 +0200 Subject: [PATCH 039/107] Fix Linux armv6 build on runtime-community.yml (#74757) Add missing HOST_ARM define to armv6 in configurecompiler.cmake, it was missed in https://github.com/dotnet/runtime/pull/73530, before that we defined `HOST_ARM` for armv6 in pal.h too because of `defined(__arm__)` We also only need the `clr.iltools+clr.packages` subset, not all of CoreCLR. Also fix some dependencies that weren't working for FreeBSD since we missed the local variables. We don't need installer subset conditions there but we need to trigger on rolling builds. --- eng/native/configurecompiler.cmake | 1 + eng/pipelines/runtime-community.yml | 12 ++++++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/eng/native/configurecompiler.cmake b/eng/native/configurecompiler.cmake index a0163845e63e8c..da893f7da616ba 100644 --- a/eng/native/configurecompiler.cmake +++ b/eng/native/configurecompiler.cmake @@ -220,6 +220,7 @@ elseif (CLR_CMAKE_HOST_ARCH_ARM) add_definitions(-DHOST_ARM) elseif (CLR_CMAKE_HOST_ARCH_ARMV6) set(ARCH_HOST_NAME armv6) + add_definitions(-DHOST_ARM) add_definitions(-DHOST_ARMV6) elseif (CLR_CMAKE_HOST_ARCH_ARM64) set(ARCH_HOST_NAME arm64) diff --git a/eng/pipelines/runtime-community.yml b/eng/pipelines/runtime-community.yml index 4da1a6605ee893..3eace877e55222 100644 --- a/eng/pipelines/runtime-community.yml +++ b/eng/pipelines/runtime-community.yml @@ -65,7 +65,6 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml @@ -89,6 +88,12 @@ jobs: runtimeFlavor: mono platforms: - FreeBSD_x64 + variables: + # map dependencies variables to local variables + - name: librariesContainsChange + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] + - name: monoContainsChange + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] jobParameters: testScope: innerloop nameSuffix: AllSubsets_Mono @@ -98,7 +103,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true)) + eq(variables['isRollingBuild'], true)) # # Build the whole product using Mono and run libraries tests @@ -120,13 +125,12 @@ jobs: jobParameters: testScope: innerloop nameSuffix: AllSubsets_Mono - buildArgs: -s mono+clr+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true + buildArgs: -s mono+clr.iltools+clr.packages+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true timeoutInMinutes: 120 condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) ${{ if eq(variables['isRollingBuild'], true) }}: # extra steps, run tests From d5e3a5c2ca46691d65c81d520cb95f13f7a94652 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Tue, 30 Aug 2022 14:17:03 -0400 Subject: [PATCH 040/107] Fix two auto-atomicity Regex bugs (#74726) * Stop coalescing some adjacent Regex atomic loops We walk concatenations in order to combine adjacent loops, e.g. `a+a+a+` becomes `a{3,}`. We also combine loops with individual items that are compatible, e.g. `a+ab` becomes `a{2,}b`. However, we're doing these operations on atomic loops as well, which is sometimes wrong. Since an atomic loop consumes as much as possible and never gives anything back, combining it with a subsequent loop will end up essentially ignoring any minimum specified in the latter loop. We thus can't combine atomic loops if the second loop has a minimum; this includes the case where the second "loop" is just an individual item. * Fix auto-atomicity handling of \w and \b We currently consider \w and \b non-overlapping, which allows a \w loop followed by a \b to be made atomic. The problem with this is that \b is zero-width, and it could be followed by something that does overlap with the \w. When matching at a location that is a word boundary, it is possible the first loop could give up something that matches the subsequent construct, and thus it can't be made atomic. (We could probably restrict this further to still allow atomicity when the first loop has a non-0 lower bound, but it doesn't appear to be worth the complication.) * Add a few more tests --- .../Text/RegularExpressions/RegexNode.cs | 55 +++++++----- .../FunctionalTests/Regex.Match.Tests.cs | 9 ++ .../Regex.MultipleMatches.Tests.cs | 30 +++++++ .../tests/UnitTests/RegexReductionTests.cs | 87 ++++++++++--------- 4 files changed, 119 insertions(+), 62 deletions(-) diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs index ee8e487dd96ad9..3ed8102ed49d1f 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs @@ -1606,22 +1606,33 @@ static bool CanCombineCounts(int nodeMin, int nodeMax, int nextMin, int nextMax) // Coalescing a loop with its same type case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy when nextNode.Kind == currentNode.Kind && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when nextNode.Kind == currentNode.Kind && currentNode.Str == nextNode.Str: - if (CanCombineCounts(currentNode.M, currentNode.N, nextNode.M, nextNode.N)) + if (nextNode.M > 0 && + currentNode.Kind is RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloopatomic) { - currentNode.M += nextNode.M; - if (currentNode.N != int.MaxValue) - { - currentNode.N = nextNode.N == int.MaxValue ? int.MaxValue : currentNode.N + nextNode.N; - } - next++; - continue; + // Atomic loops can only be combined if the second loop has no lower bound, as if it has a lower bound, + // combining them changes behavior. Uncombined, the first loop can consume all matching items; + // the second loop might then not be able to meet its minimum and fail. But if they're combined, the combined + // minimum of the sole loop could now be met, introducing matches where there shouldn't have been any. + break; } - break; + + if (!CanCombineCounts(currentNode.M, currentNode.N, nextNode.M, nextNode.N)) + { + break; + } + + currentNode.M += nextNode.M; + if (currentNode.N != int.MaxValue) + { + currentNode.N = nextNode.N == int.MaxValue ? int.MaxValue : currentNode.N + nextNode.N; + } + next++; + continue; // Coalescing a loop with an additional item of the same type - case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when nextNode.Kind == RegexNodeKind.One && currentNode.Ch == nextNode.Ch: - case RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy when nextNode.Kind == RegexNodeKind.Notone && currentNode.Ch == nextNode.Ch: - case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when nextNode.Kind == RegexNodeKind.Set && currentNode.Str == nextNode.Str: + case RegexNodeKind.Oneloop or RegexNodeKind.Onelazy when nextNode.Kind == RegexNodeKind.One && currentNode.Ch == nextNode.Ch: + case RegexNodeKind.Notoneloop or RegexNodeKind.Notonelazy when nextNode.Kind == RegexNodeKind.Notone && currentNode.Ch == nextNode.Ch: + case RegexNodeKind.Setloop or RegexNodeKind.Setlazy when nextNode.Kind == RegexNodeKind.Set && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, 1, 1)) { currentNode.M++; @@ -1635,7 +1646,7 @@ static bool CanCombineCounts(int nodeMin, int nodeMax, int nextMin, int nextMax) break; // Coalescing a loop with a subsequent string - case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when nextNode.Kind == RegexNodeKind.Multi && currentNode.Ch == nextNode.Str![0]: + case RegexNodeKind.Oneloop or RegexNodeKind.Onelazy when nextNode.Kind == RegexNodeKind.Multi && currentNode.Ch == nextNode.Str![0]: { // Determine how many of the multi's characters can be combined. // We already checked for the first, so we know it's at least one. @@ -2056,15 +2067,15 @@ private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent, bool i case RegexNodeKind.Multi when node.Ch != subsequent.Str![0]: case RegexNodeKind.End: case RegexNodeKind.EndZ or RegexNodeKind.Eol when node.Ch != '\n': - case RegexNodeKind.Boundary when RegexCharClass.IsBoundaryWordChar(node.Ch): - case RegexNodeKind.NonBoundary when !RegexCharClass.IsBoundaryWordChar(node.Ch): - case RegexNodeKind.ECMABoundary when RegexCharClass.IsECMAWordChar(node.Ch): - case RegexNodeKind.NonECMABoundary when !RegexCharClass.IsECMAWordChar(node.Ch): return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && node.Ch != subsequent.Ch: case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic when subsequent.M == 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M == 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): + case RegexNodeKind.Boundary when RegexCharClass.IsBoundaryWordChar(node.Ch): + case RegexNodeKind.NonBoundary when !RegexCharClass.IsBoundaryWordChar(node.Ch): + case RegexNodeKind.ECMABoundary when RegexCharClass.IsECMAWordChar(node.Ch): + case RegexNodeKind.NonECMABoundary when !RegexCharClass.IsECMAWordChar(node.Ch): // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; @@ -2103,14 +2114,14 @@ private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent, bool i case RegexNodeKind.Multi when !RegexCharClass.CharInClass(subsequent.Str![0], node.Str!): case RegexNodeKind.End: case RegexNodeKind.EndZ or RegexNodeKind.Eol when !RegexCharClass.CharInClass('\n', node.Str!): - case RegexNodeKind.Boundary when node.Str is RegexCharClass.WordClass or RegexCharClass.DigitClass: - case RegexNodeKind.NonBoundary when node.Str is RegexCharClass.NotWordClass or RegexCharClass.NotDigitClass: - case RegexNodeKind.ECMABoundary when node.Str is RegexCharClass.ECMAWordClass or RegexCharClass.ECMADigitClass: - case RegexNodeKind.NonECMABoundary when node.Str is RegexCharClass.NotECMAWordClass or RegexCharClass.NotDigitClass: return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M == 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): + case RegexNodeKind.Boundary when node.Str is RegexCharClass.WordClass or RegexCharClass.DigitClass: + case RegexNodeKind.NonBoundary when node.Str is RegexCharClass.NotWordClass or RegexCharClass.NotDigitClass: + case RegexNodeKind.ECMABoundary when node.Str is RegexCharClass.ECMAWordClass or RegexCharClass.ECMADigitClass: + case RegexNodeKind.NonECMABoundary when node.Str is RegexCharClass.NotECMAWordClass or RegexCharClass.NotDigitClass: // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; @@ -2125,8 +2136,6 @@ private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent, bool i // We only get here if the node could be made atomic based on subsequent but subsequent has a lower bound of zero // and thus we need to move subsequent to be the next node in sequence and loop around to try again. - Debug.Assert(subsequent.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy); - Debug.Assert(subsequent.M == 0); if (!iterateNullableSubsequent) { return false; diff --git a/src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.Match.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.Match.Tests.cs index 02182bd87ede6e..9f73f9f1c30e88 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.Match.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.Match.Tests.cs @@ -149,6 +149,15 @@ public static IEnumerable Match_MemberData() yield return (Case("(?>[^z]+)z"), "zzzzxyxyxyz123", options, 4, 9, true, "xyxyxyz"); yield return (Case("(?>(?>[^z]+))z"), "zzzzxyxyxyz123", options, 4, 9, true, "xyxyxyz"); yield return (Case("(?>[^z]*)z123"), "zzzzxyxyxyz123", options, 4, 10, true, "xyxyxyz123"); + yield return (Case("(?>a*)a"), "aaa", options, 0, 3, false, ""); + yield return (Case("(?>a*)a+"), "aaa", options, 0, 3, false, ""); + yield return (Case("(?>a+)a+"), "aaa", options, 0, 3, false, ""); + yield return (Case("(?>.*)."), "aaa", options, 0, 3, false, ""); + yield return (Case("(?>.*).+"), "aaa", options, 0, 3, false, ""); + yield return (Case("(?>.+).+"), "aaa", options, 0, 3, false, ""); + yield return (Case("(?>\\w*)\\w"), "aaa", options, 0, 3, false, ""); + yield return (Case("(?>\\w*)\\w+"), "aaa", options, 0, 3, false, ""); + yield return (Case("(?>\\w+)\\w+"), "aaa", options, 0, 3, false, ""); yield return (Case("(?>[^12]+)1"), "121231", options, 0, 6, true, "31"); yield return (Case("(?>[^123]+)1"), "12312341", options, 0, 8, true, "41"); diff --git a/src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.MultipleMatches.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.MultipleMatches.Tests.cs index 744fd174351171..bd0b1eab45ce37 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.MultipleMatches.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.MultipleMatches.Tests.cs @@ -276,6 +276,22 @@ public static IEnumerable Matches_TestData() } }; + yield return new object[] + { + engine, + @"\w*\b\w+", "abc def ghij kl m nop qrstuv", RegexOptions.None, + new[] + { + new CaptureData("abc", 0, 3), + new CaptureData("def", 4, 3), + new CaptureData("ghij", 8, 4), + new CaptureData("kl", 13, 2), + new CaptureData("m", 16, 1), + new CaptureData("nop", 18, 3), + new CaptureData("qrstuv", 22, 6), + } + }; + if (!PlatformDetection.IsNetFramework) { // .NET Framework missing fix in https://github.com/dotnet/runtime/pull/1075 @@ -294,6 +310,20 @@ public static IEnumerable Matches_TestData() if (!RegexHelpers.IsNonBacktracking(engine)) { + yield return new object[] + { + engine, + @"(\b(?!ab|nop)\w*\b)\w+", "abc def ghij kl m nop qrstuv", RegexOptions.None, + new[] + { + new CaptureData("def", 4, 3), + new CaptureData("ghij", 8, 4), + new CaptureData("kl", 13, 2), + new CaptureData("m", 16, 1), + new CaptureData("qrstuv", 22, 6), + } + }; + yield return new object[] { engine, diff --git a/src/libraries/System.Text.RegularExpressions/tests/UnitTests/RegexReductionTests.cs b/src/libraries/System.Text.RegularExpressions/tests/UnitTests/RegexReductionTests.cs index b21b26071bc2e6..dbb22cf5026485 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/UnitTests/RegexReductionTests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/UnitTests/RegexReductionTests.cs @@ -50,26 +50,14 @@ public class RegexReductionTests // Two atomic one loops [InlineData("(?>a*)(?>a*)", "(?>a*)")] [InlineData("(?>a*)(?>(?:a*))", "(?>a*)")] - [InlineData("(?>a*)(?>a+)", "(?>a+)")] [InlineData("(?>a*)(?>a?)", "(?>a*)")] - [InlineData("(?>a*)(?>a{1,3})", "(?>a+)")] [InlineData("(?>a+)(?>a*)", "(?>a+)")] - [InlineData("(?>a+)(?>a+)", "(?>a{2,})")] [InlineData("(?>a+)(?>a?)", "(?>a+)")] - [InlineData("(?>a+)(?>a{1,3})", "(?>a{2,})")] [InlineData("(?>a?)(?>a*)", "(?>a*)")] - [InlineData("(?>a?)(?>a+)", "(?>a+)")] [InlineData("(?>a?)(?>a?)", "(?>a{0,2})")] - [InlineData("(?>a?)(?>a{1,3})", "(?>a{1,4})")] [InlineData("(?>a{1,3})(?>a*)", "(?>a+)")] - [InlineData("(?>a{1,3})(?>a+)", "(?>a{2,})")] [InlineData("(?>a{1,3})(?>a?)", "(?>a{1,4})")] - [InlineData("(?>a{1,3})(?>a{1,3})", "(?>a{2,6})")] - // Atomic one loop and one - [InlineData("(?>a*)a", "(?>a+)")] - [InlineData("(?>a+)a", "(?>a{2,})")] - [InlineData("(?>a?)a", "(?>a{1,2})")] - [InlineData("(?>a{1,3})a", "(?>a{2,4})")] + // One and atomic one loop [InlineData("a(?>a*)", "(?>a+)")] [InlineData("a(?>a+)", "(?>a{2,})")] [InlineData("a(?>a?)", "(?>a{1,2})")] @@ -136,21 +124,13 @@ public class RegexReductionTests [InlineData("[^a]{1,3}?[^a]{1,3}?", "[^a]{2,6}?")] // Two atomic notone loops [InlineData("(?>[^a]*)(?>[^a]*)", "(?>[^a]*)")] - [InlineData("(?>[^a]*)(?>[^a]+)", "(?>[^a]+)")] [InlineData("(?>[^a]*)(?>[^a]?)", "(?>[^a]*)")] - [InlineData("(?>[^a]*)(?>[^a]{1,3})", "(?>[^a]+)")] [InlineData("(?>[^a]+)(?>[^a]*)", "(?>[^a]+)")] - [InlineData("(?>[^a]+)(?>[^a]+)", "(?>[^a]{2,})")] [InlineData("(?>[^a]+)(?>[^a]?)", "(?>[^a]+)")] - [InlineData("(?>[^a]+)(?>[^a]{1,3})", "(?>[^a]{2,})")] [InlineData("(?>[^a]?)(?>[^a]*)", "(?>[^a]*)")] - [InlineData("(?>[^a]?)(?>[^a]+)", "(?>[^a]+)")] [InlineData("(?>[^a]?)(?>[^a]?)", "(?>[^a]{0,2})")] - [InlineData("(?>[^a]?)(?>[^a]{1,3})", "(?>[^a]{1,4})")] [InlineData("(?>[^a]{1,3})(?>[^a]*)", "(?>[^a]+)")] - [InlineData("(?>[^a]{1,3})(?>[^a]+)", "(?>[^a]{2,})")] [InlineData("(?>[^a]{1,3})(?>[^a]?)", "(?>[^a]{1,4})")] - [InlineData("(?>[^a]{1,3})(?>[^a]{1,3})", "(?>[^a]{2,6})")] // Greedy notone loop and notone [InlineData("[^a]*[^a]", "[^a]+")] [InlineData("[^a]+[^a]", "[^a]{2,}")] @@ -169,11 +149,7 @@ public class RegexReductionTests [InlineData("[^a][^a]+?", "[^a]{2,}?")] [InlineData("[^a][^a]??", "[^a]{1,2}?")] [InlineData("[^a][^a]{1,3}?", "[^a]{2,4}?")] - // Atomic notone loop and notone - [InlineData("(?>[^a]*)[^a]", "(?>[^a]+)")] - [InlineData("(?>[^a]+)[^a]", "(?>[^a]{2,})")] - [InlineData("(?>[^a]?)[^a]", "(?>[^a]{1,2})")] - [InlineData("(?>[^a]{1,3})[^a]", "(?>[^a]{2,4})")] + // Notone and atomic notone loop [InlineData("[^a](?>[^a]*)", "(?>[^a]+)")] [InlineData("[^a](?>[^a]+)", "(?>[^a]{2,})")] [InlineData("[^a](?>[^a]?)", "(?>[^a]{1,2})")] @@ -206,11 +182,7 @@ public class RegexReductionTests [InlineData("[0-9][0-9]+", "[0-9]{2,}")] [InlineData("[0-9][0-9]?", "[0-9]{1,2}")] [InlineData("[0-9][0-9]{1,3}", "[0-9]{2,4}")] - // Atomic set loop and set - [InlineData("(?>[0-9]*)[0-9]", "(?>[0-9]+)")] - [InlineData("(?>[0-9]+)[0-9]", "(?>[0-9]{2,})")] - [InlineData("(?>[0-9]?)[0-9]", "(?>[0-9]{1,2})")] - [InlineData("(?>[0-9]{1,3})[0-9]", "(?>[0-9]{2,4})")] + // Set and atomic set loop [InlineData("[0-9](?>[0-9]*)", "(?>[0-9]+)")] [InlineData("[0-9](?>[0-9]+)", "(?>[0-9]{2,})")] [InlineData("[0-9](?>[0-9]?)", "(?>[0-9]{1,2})")] @@ -234,21 +206,13 @@ public class RegexReductionTests [InlineData("[0-9]{1,3}?[0-9]{1,3}?", "[0-9]{2,6}?")] // Two atomic set loops [InlineData("(?>[0-9]*)(?>[0-9]*)", "(?>[0-9]*)")] - [InlineData("(?>[0-9]*)(?>[0-9]+)", "(?>[0-9]+)")] [InlineData("(?>[0-9]*)(?>[0-9]?)", "(?>[0-9]*)")] - [InlineData("(?>[0-9]*)(?>[0-9]{1,3})", "(?>[0-9]+)")] [InlineData("(?>[0-9]+)(?>[0-9]*)", "(?>[0-9]+)")] - [InlineData("(?>[0-9]+)(?>[0-9]+)", "(?>[0-9]{2,})")] [InlineData("(?>[0-9]+)(?>[0-9]?)", "(?>[0-9]+)")] - [InlineData("(?>[0-9]+)(?>[0-9]{1,3})", "(?>[0-9]{2,})")] [InlineData("(?>[0-9]?)(?>[0-9]*)", "(?>[0-9]*)")] - [InlineData("(?>[0-9]?)(?>[0-9]+)", "(?>[0-9]+)")] [InlineData("(?>[0-9]?)(?>[0-9]?)", "(?>[0-9]{0,2})")] - [InlineData("(?>[0-9]?)(?>[0-9]{1,3})", "(?>[0-9]{1,4})")] [InlineData("(?>[0-9]{1,3})(?>[0-9]*)", "(?>[0-9]+)")] - [InlineData("(?>[0-9]{1,3})(?>[0-9]+)", "(?>[0-9]{2,})")] [InlineData("(?>[0-9]{1,3})(?>[0-9]?)", "(?>[0-9]{1,4})")] - [InlineData("(?>[0-9]{1,3})(?>[0-9]{1,3})", "(?>[0-9]{2,6})")] // Lazy set loop and set [InlineData("[0-9]*?[0-9]", "[0-9]+?")] [InlineData("[0-9]+?[0-9]", "[0-9]{2,}?")] @@ -381,6 +345,8 @@ public class RegexReductionTests [InlineData("(?:w*)+\\.", "(?>w*)+\\.")] [InlineData("(a[bcd]e*)*fg", "(a[bcd](?>e*))*fg")] [InlineData("(\\w[bcd]\\s*)*fg", "(\\w[bcd](?>\\s*))*fg")] + [InlineData(@"\b(\w+)\b", @"\b((?>\w+))\b")] + [InlineData(@"\b(?:\w+)\b ", @"\b(?>\w+)\b ")] // Nothing handling [InlineData(@"\wabc(?!)def", "(?!)")] [InlineData(@"\wabc(?!)def|ghi(?!)", "(?!)")] @@ -423,6 +389,42 @@ public void PatternsReduceIdentically(string actual, string expected) [InlineData("a*?a*", "a*")] [InlineData("a*[^a]*", "a*")] [InlineData("[^a]*a*", "a*")] + [InlineData("(?>a*)(?>a+)", "(?>a+)")] + [InlineData("(?>a*)(?>a{1,3})", "(?>a+)")] + [InlineData("(?>a+)(?>a+)", "(?>a{2,})")] + [InlineData("(?>a+)(?>a{1,3})", "(?>a{2,})")] + [InlineData("(?>a?)(?>a+)", "(?>a+)")] + [InlineData("(?>a?)(?>a{1,3})", "(?>a{1,4})")] + [InlineData("(?>a{1,3})(?>a+)", "(?>a{2,})")] + [InlineData("(?>a{1,3})(?>a{1,3})", "(?>a{2,6})")] + [InlineData("(?>[^a]*)(?>[^a]+)", "(?>[^a]+)")] + [InlineData("(?>[^a]*)(?>[^a]{1,3})", "(?>[^a]+)")] + [InlineData("(?>[^a]+)(?>[^a]+)", "(?>[^a]{2,})")] + [InlineData("(?>[^a]+)(?>[^a]{1,3})", "(?>[^a]{2,})")] + [InlineData("(?>[^a]?)(?>[^a]+)", "(?>[^a]+)")] + [InlineData("(?>[^a]?)(?>[^a]{1,3})", "(?>[^a]{1,4})")] + [InlineData("(?>[^a]{1,3})(?>[^a]+)", "(?>[^a]{2,})")] + [InlineData("(?>[^a]{1,3})(?>[^a]{1,3})", "(?>[^a]{2,6})")] + [InlineData("(?>[0-9]*)(?>[0-9]+)", "(?>[0-9]+)")] + [InlineData("(?>[0-9]*)(?>[0-9]{1,3})", "(?>[0-9]+)")] + [InlineData("(?>[0-9]+)(?>[0-9]+)", "(?>[0-9]{2,})")] + [InlineData("(?>[0-9]+)(?>[0-9]{1,3})", "(?>[0-9]{2,})")] + [InlineData("(?>[0-9]?)(?>[0-9]+)", "(?>[0-9]+)")] + [InlineData("(?>[0-9]?)(?>[0-9]{1,3})", "(?>[0-9]{1,4})")] + [InlineData("(?>[0-9]{1,3})(?>[0-9]+)", "(?>[0-9]{2,})")] + [InlineData("(?>[0-9]{1,3})(?>[0-9]{1,3})", "(?>[0-9]{2,6})")] + [InlineData("(?>a*)a", "(?>a+)")] + [InlineData("(?>a+)a", "(?>a{2,})")] + [InlineData("(?>a?)a", "(?>a{1,2})")] + [InlineData("(?>a{1,3})a", "(?>a{2,4})")] + [InlineData("(?>[^a]*)[^a]", "(?>[^a]+)")] + [InlineData("(?>[^a]+)[^a]", "(?>[^a]{2,})")] + [InlineData("(?>[^a]?)[^a]", "(?>[^a]{1,2})")] + [InlineData("(?>[^a]{1,3})[^a]", "(?>[^a]{2,4})")] + [InlineData("(?>[0-9]*)[0-9]", "(?>[0-9]+)")] + [InlineData("(?>[0-9]+)[0-9]", "(?>[0-9]{2,})")] + [InlineData("(?>[0-9]?)[0-9]", "(?>[0-9]{1,2})")] + [InlineData("(?>[0-9]{1,3})[0-9]", "(?>[0-9]{2,4})")] [InlineData("a{2147483646}a", "a{2147483647}")] [InlineData("a{2147483647}a", "a{2147483647}")] [InlineData("a{0,2147483646}a", "a{0,2147483647}")] @@ -470,6 +472,10 @@ public void PatternsReduceIdentically(string actual, string expected) [InlineData("(?:ab??){2}", "(?:a(?>b??)){2}")] [InlineData("(?:ab??){2, 3}", "(?:a(?>b??)){2, 3}")] [InlineData("ab??(b)", "a(?>b??)(b)")] + [InlineData(@"\w+\b\w+", @"(?>\w+)\b\w")] + [InlineData(@"\w*\b\w+", @"(?>\w*)\b\w+")] + [InlineData(@"\W+\B\W+", @"(?>\W+)\B\W")] + [InlineData(@"\W*\B\W+", @"(?>\W*)\B\W")] // Loops inside alternation constructs [InlineData("(abc*|def)chi", "(ab(?>c*)|def)chi")] [InlineData("(abc|def*)fhi", "(abc|de(?>f*))fhi")] @@ -505,6 +511,9 @@ public void PatternsReduceDifferently(string actual, string expected) [InlineData(@"a??", RegexOptions.None, 0, 1)] [InlineData(@"a+", RegexOptions.None, 1, null)] [InlineData(@"a+?", RegexOptions.None, 1, null)] + [InlineData(@"(?>a*)a", RegexOptions.None, 1, null)] + [InlineData(@"(?>a*)a+", RegexOptions.None, 1, null)] + [InlineData(@"(?>a*)a*", RegexOptions.None, 0, null)] [InlineData(@"a{2}", RegexOptions.None, 2, 2)] [InlineData(@"a{2}?", RegexOptions.None, 2, 2)] [InlineData(@"a{3,17}", RegexOptions.None, 3, 17)] From 07072a161df89ddc3636292afee9a7bd8ec7ddc7 Mon Sep 17 00:00:00 2001 From: Viktor Hofer Date: Tue, 30 Aug 2022 22:49:34 +0200 Subject: [PATCH 041/107] Unpin System.ValueTuple assembly version (#74817) * Unpin System.ValueTuple assembly version System.ValueTuple's assembly version had to be pinned when it was consumable by .NET Framework which isn't true anymore. The library now only ships as part of the .NETCoreApp shared framework. --- .../System.ValueTuple/ref/System.ValueTuple.csproj | 7 ++++--- .../System.ValueTuple/src/System.ValueTuple.csproj | 6 ++++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/libraries/System.ValueTuple/ref/System.ValueTuple.csproj b/src/libraries/System.ValueTuple/ref/System.ValueTuple.csproj index 4436582a08c651..f6cd757cbe927d 100644 --- a/src/libraries/System.ValueTuple/ref/System.ValueTuple.csproj +++ b/src/libraries/System.ValueTuple/ref/System.ValueTuple.csproj @@ -1,14 +1,15 @@ + - - 4.0.3.0 $(NetCoreAppCurrent) + + + diff --git a/src/libraries/System.ValueTuple/src/System.ValueTuple.csproj b/src/libraries/System.ValueTuple/src/System.ValueTuple.csproj index 42948ac64aa033..e304e33e8fadbf 100644 --- a/src/libraries/System.ValueTuple/src/System.ValueTuple.csproj +++ b/src/libraries/System.ValueTuple/src/System.ValueTuple.csproj @@ -1,10 +1,12 @@ + - - true $(NetCoreAppCurrent) + true + + From 0ce9c8c61e1bc2d7a10db5df5be6039eabe692ba Mon Sep 17 00:00:00 2001 From: Thays Grazia Date: Tue, 30 Aug 2022 18:00:57 -0300 Subject: [PATCH 042/107] [wasm][debugger] Make possible to run debugger tests using runtime in debug mode (#74830) * Make possible to run debugger tests using runtime in debug mode * Fix as @radical suggested --- .../wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj b/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj index 2b4e7bee7a5a69..45e5d54b85f467 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj +++ b/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestSuite.csproj @@ -26,7 +26,7 @@ - + From 50b426b5b233e4247af75e6f926bc1f43e6dfe70 Mon Sep 17 00:00:00 2001 From: Andy Ayers Date: Tue, 30 Aug 2022 14:25:07 -0700 Subject: [PATCH 043/107] JIT: extend copy prop to local fields (#74384) Allow copy prop to update GT_LCL_FLD nodes. Update local assertion gen for block opts to use a mid-morph (after child nodes are morphed) tree to generate copy or zero assertions, since the semantics of the post-morph tree are often obscured by the copy/zero expansions. --- src/coreclr/jit/assertionprop.cpp | 118 +++++++++++++++++++++++- src/coreclr/jit/compiler.h | 8 +- src/coreclr/jit/morph.cpp | 146 +++++++++++++++++++----------- src/coreclr/jit/morphblock.cpp | 21 ++++- 4 files changed, 235 insertions(+), 58 deletions(-) diff --git a/src/coreclr/jit/assertionprop.cpp b/src/coreclr/jit/assertionprop.cpp index c15cb42786ed7e..a066b23403609a 100644 --- a/src/coreclr/jit/assertionprop.cpp +++ b/src/coreclr/jit/assertionprop.cpp @@ -1636,8 +1636,35 @@ AssertionIndex Compiler::optCreateAssertion(GenTree* op1, // // Copy Assertions // + case GT_OBJ: + case GT_BLK: + { + // TODO-ADDR: delete once local morph folds SIMD-typed indirections. + // + GenTree* const addr = op2->AsIndir()->Addr(); + + if (addr->OperIs(GT_ADDR)) + { + GenTree* const base = addr->AsOp()->gtOp1; + + if (base->OperIs(GT_LCL_VAR) && varTypeIsStruct(base)) + { + ClassLayout* const varLayout = base->GetLayout(this); + ClassLayout* const objLayout = op2->GetLayout(this); + if (ClassLayout::AreCompatible(varLayout, objLayout)) + { + op2 = base; + goto IS_COPY; + } + } + } + + goto DONE_ASSERTION; + } + case GT_LCL_VAR: { + IS_COPY: // // Must either be an OAK_EQUAL or an OAK_NOT_EQUAL assertion // @@ -3416,7 +3443,14 @@ bool Compiler::optZeroObjAssertionProp(GenTree* tree, ASSERT_VALARG_TP assertion return false; } - unsigned lclNum = tree->AsLclVar()->GetLclNum(); + // No ZEROOBJ assertions for simd. + // + if (varTypeIsSIMD(tree)) + { + return false; + } + + const unsigned lclNum = tree->AsLclVar()->GetLclNum(); AssertionIndex assertionIndex = optLocalAssertionIsEqualOrNotEqual(O1K_LCLVAR, lclNum, O2K_ZEROOBJ, 0, assertions); if (assertionIndex == NO_ASSERTION_INDEX) { @@ -3568,6 +3602,20 @@ GenTree* Compiler::optCopyAssertionProp(AssertionDsc* curAssertion, return nullptr; } + // Heuristic: for LclFld prop, don't force the copy or its promoted fields to be in memory. + // + if (tree->OperIs(GT_LCL_FLD)) + { + if (copyVarDsc->IsEnregisterableLcl() || copyVarDsc->lvPromotedStruct()) + { + return nullptr; + } + else + { + lvaSetVarDoNotEnregister(copyLclNum DEBUGARG(DoNotEnregisterReason::LocalField)); + } + } + tree->SetLclNum(copyLclNum); tree->SetSsaNum(copySsaNum); @@ -3689,6 +3737,71 @@ GenTree* Compiler::optAssertionProp_LclVar(ASSERT_VALARG_TP assertions, GenTreeL return nullptr; } +//------------------------------------------------------------------------ +// optAssertionProp_LclFld: try and optimize a local field use via assertions +// +// Arguments: +// assertions - set of live assertions +// tree - local field use to optimize +// stmt - statement containing the tree +// +// Returns: +// Updated tree, or nullptr +// +// Notes: +// stmt may be nullptr during local assertion prop +// +GenTree* Compiler::optAssertionProp_LclFld(ASSERT_VALARG_TP assertions, GenTreeLclVarCommon* tree, Statement* stmt) +{ + // If we have a var definition then bail or + // If this is the address of the var then it will have the GTF_DONT_CSE + // flag set and we don't want to to assertion prop on it. + if (tree->gtFlags & (GTF_VAR_DEF | GTF_DONT_CSE)) + { + return nullptr; + } + + // Only run during local prop and if copies are available. + // + if (!optLocalAssertionProp || !optCanPropLclVar) + { + return nullptr; + } + + BitVecOps::Iter iter(apTraits, assertions); + unsigned index = 0; + while (iter.NextElem(&index)) + { + AssertionIndex assertionIndex = GetAssertionIndex(index); + if (assertionIndex > optAssertionCount) + { + break; + } + + // See if the variable is equal to another variable. + AssertionDsc* curAssertion = optGetAssertion(assertionIndex); + if (!curAssertion->CanPropLclVar()) + { + continue; + } + + // Copy prop. + if (curAssertion->op2.kind == O2K_LCLVAR_COPY) + { + // Perform copy assertion prop. + GenTree* newTree = optCopyAssertionProp(curAssertion, tree, stmt DEBUGARG(assertionIndex)); + if (newTree != nullptr) + { + return newTree; + } + } + + continue; + } + + return nullptr; +} + //------------------------------------------------------------------------ // optAssertionProp_Asg: Try and optimize an assignment via assertions. // @@ -4916,6 +5029,9 @@ GenTree* Compiler::optAssertionProp(ASSERT_VALARG_TP assertions, GenTree* tree, case GT_LCL_VAR: return optAssertionProp_LclVar(assertions, tree->AsLclVarCommon(), stmt); + case GT_LCL_FLD: + return optAssertionProp_LclFld(assertions, tree->AsLclVarCommon(), stmt); + case GT_ASG: return optAssertionProp_Asg(assertions, tree->AsOp(), stmt); diff --git a/src/coreclr/jit/compiler.h b/src/coreclr/jit/compiler.h index e5190a9dea64b1..03910bbb60340e 100644 --- a/src/coreclr/jit/compiler.h +++ b/src/coreclr/jit/compiler.h @@ -5767,7 +5767,7 @@ class Compiler GenTree* fgMorphCopyBlock(GenTree* tree); GenTree* fgMorphStoreDynBlock(GenTreeStoreDynBlk* tree); GenTree* fgMorphForRegisterFP(GenTree* tree); - GenTree* fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac = nullptr); + GenTree* fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac, bool* optAssertionPropDone = nullptr); GenTree* fgOptimizeCast(GenTreeCast* cast); GenTree* fgOptimizeCastOnAssignment(GenTreeOp* asg); GenTree* fgOptimizeEqualityComparisonWithConst(GenTreeOp* cmp); @@ -5786,7 +5786,7 @@ class Compiler GenTree* fgMorphRetInd(GenTreeUnOp* tree); GenTree* fgMorphModToSubMulDiv(GenTreeOp* tree); GenTree* fgMorphUModToAndSub(GenTreeOp* tree); - GenTree* fgMorphSmpOpOptional(GenTreeOp* tree); + GenTree* fgMorphSmpOpOptional(GenTreeOp* tree, bool* optAssertionPropDone); GenTree* fgMorphMultiOp(GenTreeMultiOp* multiOp); GenTree* fgMorphConst(GenTree* tree); @@ -5802,7 +5802,8 @@ class Compiler private: void fgKillDependentAssertionsSingle(unsigned lclNum DEBUGARG(GenTree* tree)); void fgKillDependentAssertions(unsigned lclNum DEBUGARG(GenTree* tree)); - void fgMorphTreeDone(GenTree* tree, GenTree* oldTree = nullptr DEBUGARG(int morphNum = 0)); + void fgMorphTreeDone(GenTree* tree); + void fgMorphTreeDone(GenTree* tree, bool optAssertionPropDone, bool isMorphedTree DEBUGARG(int morphNum = 0)); Statement* fgMorphStmt; @@ -7368,6 +7369,7 @@ class Compiler // Assertion propagation functions. GenTree* optAssertionProp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt, BasicBlock* block); GenTree* optAssertionProp_LclVar(ASSERT_VALARG_TP assertions, GenTreeLclVarCommon* tree, Statement* stmt); + GenTree* optAssertionProp_LclFld(ASSERT_VALARG_TP assertions, GenTreeLclVarCommon* tree, Statement* stmt); GenTree* optAssertionProp_Asg(ASSERT_VALARG_TP assertions, GenTreeOp* asg, Statement* stmt); GenTree* optAssertionProp_Return(ASSERT_VALARG_TP assertions, GenTreeUnOp* ret, Statement* stmt); GenTree* optAssertionProp_Ind(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt); diff --git a/src/coreclr/jit/morph.cpp b/src/coreclr/jit/morph.cpp index 7155c18207f7e7..8bee0e2cfd9143 100644 --- a/src/coreclr/jit/morph.cpp +++ b/src/coreclr/jit/morph.cpp @@ -5500,7 +5500,7 @@ GenTree* Compiler::fgMorphField(GenTree* tree, MorphAddrContext* mac) tree->gtFlags |= (GTF_IND_INVARIANT | GTF_IND_NONFAULTING | GTF_IND_NONNULL); } - return fgMorphSmpOp(tree); + return fgMorphSmpOp(tree, /* mac */ nullptr); } } @@ -9771,16 +9771,23 @@ GenTree* Compiler::fgMorphCastedBitwiseOp(GenTreeOp* tree) return nullptr; } -/***************************************************************************** - * - * Transform the given GTK_SMPOP tree for code generation. - */ - +//------------------------------------------------------------------------ +// fgMorphSmpOp: morph a GTK_SMPOP tree +// +// Arguments: +// tree - tree to morph +// mac - address context for morphing +// optAssertionPropDone - [out, optional] set true if local assertions +// were killed/genned while morphing this tree +// +// Returns: +// Tree, possibly updated +// #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable : 21000) // Suppress PREFast warning about overly large function #endif -GenTree* Compiler::fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac) +GenTree* Compiler::fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac, bool* optAssertionPropDone) { ALLOCA_CHECK(); assert(tree->OperKind() & GTK_SMPOP); @@ -11713,7 +11720,7 @@ GenTree* Compiler::fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac) return tree; } - tree = fgMorphSmpOpOptional(tree->AsOp()); + tree = fgMorphSmpOpOptional(tree->AsOp(), optAssertionPropDone); return tree; } @@ -13099,8 +13106,18 @@ GenTree* Compiler::fgMorphRetInd(GenTreeUnOp* ret) #ifdef _PREFAST_ #pragma warning(pop) #endif - -GenTree* Compiler::fgMorphSmpOpOptional(GenTreeOp* tree) +//------------------------------------------------------------- +// fgMorphSmpOpOptional: optional post-order morping of some SMP trees +// +// Arguments: +// tree - tree to morph +// optAssertionPropDone - [out, optional] set true if local assertions were +// killed/genned by the optional morphing +// +// Returns: +// Tree, possibly updated +// +GenTree* Compiler::fgMorphSmpOpOptional(GenTreeOp* tree, bool* optAssertionPropDone) { genTreeOps oper = tree->gtOper; GenTree* op1 = tree->gtOp1; @@ -13199,6 +13216,14 @@ GenTree* Compiler::fgMorphSmpOpOptional(GenTreeOp* tree) if (varTypeIsStruct(typ) && !tree->IsPhiDefn()) { + // Block ops handle assertion kill/gen specially. + // See PrepareDst and PropagateAssertions + // + if (optAssertionPropDone != nullptr) + { + *optAssertionPropDone = true; + } + if (tree->OperIsCopyBlkOp()) { return fgMorphCopyBlock(tree); @@ -14019,6 +14044,8 @@ GenTree* Compiler::fgMorphTree(GenTree* tree, MorphAddrContext* mac) } #endif + bool optAssertionPropDone = false; + /*------------------------------------------------------------------------- * fgMorphTree() can potentially replace a tree with another, and the * caller has to store the return value correctly. @@ -14083,11 +14110,11 @@ GenTree* Compiler::fgMorphTree(GenTree* tree, MorphAddrContext* mac) /* Save the original un-morphed tree for fgMorphTreeDone */ - GenTree* oldTree = tree; + GenTree* const oldTree = tree; /* Figure out what kind of a node we have */ - unsigned kind = tree->OperKind(); + unsigned const kind = tree->OperKind(); /* Is this a constant node? */ @@ -14109,7 +14136,7 @@ GenTree* Compiler::fgMorphTree(GenTree* tree, MorphAddrContext* mac) if (kind & GTK_SMPOP) { - tree = fgMorphSmpOp(tree, mac); + tree = fgMorphSmpOp(tree, mac, &optAssertionPropDone); goto DONE; } @@ -14221,7 +14248,8 @@ GenTree* Compiler::fgMorphTree(GenTree* tree, MorphAddrContext* mac) } DONE: - fgMorphTreeDone(tree, oldTree DEBUGARG(thisMorphNum)); + const bool isNewTree = (oldTree != tree); + fgMorphTreeDone(tree, optAssertionPropDone, isNewTree DEBUGARG(thisMorphNum)); return tree; } @@ -14314,20 +14342,40 @@ void Compiler::fgKillDependentAssertions(unsigned lclNum DEBUGARG(GenTree* tree) } } -/***************************************************************************** - * - * This function is called to complete the morphing of a tree node - * It should only be called once for each node. - * If DEBUG is defined the flag GTF_DEBUG_NODE_MORPHED is checked and updated, - * to enforce the invariant that each node is only morphed once. - * If local assertion prop is enabled the result tree may be replaced - * by an equivalent tree. - * - */ +//------------------------------------------------------------------------ +// fgMorphTreeDone: complete the morphing of a tree node +// +// Arguments: +// tree - the tree after morphing +// +// Notes: +// Simple version where the tree has not been marked +// as morphed, and where assertion kill/gen has not yet been done. +// +void Compiler::fgMorphTreeDone(GenTree* tree) +{ + fgMorphTreeDone(tree, false, false); +} -void Compiler::fgMorphTreeDone(GenTree* tree, - GenTree* oldTree /* == NULL */ - DEBUGARG(int morphNum)) +//------------------------------------------------------------------------ +// fgMorphTreeDone: complete the morphing of a tree node +// +// Arguments: +// tree - the tree after morphing +// optAssertionPropDone - true if local assertion prop was done already +// isMorphedTree - true if caller should have marked tree as morphed +// morphNum - counts invocations of fgMorphTree +// +// Notes: +// This function is called to complete the morphing of a tree node +// It should only be called once for each node. +// If DEBUG is defined the flag GTF_DEBUG_NODE_MORPHED is checked and updated, +// to enforce the invariant that each node is only morphed once. +// +// When local assertion prop is active assertions are killed and generated +// based on tree (unless optAssertionPropDone is true). +// +void Compiler::fgMorphTreeDone(GenTree* tree, bool optAssertionPropDone, bool isMorphedTree DEBUGARG(int morphNum)) { #ifdef DEBUG if (verbose && treesBeforeAfterMorph) @@ -14343,36 +14391,33 @@ void Compiler::fgMorphTreeDone(GenTree* tree, return; } - if ((oldTree != nullptr) && (oldTree != tree)) + if (isMorphedTree) { - /* Ensure that we have morphed this node */ + // caller should have set the morphed flag + // assert((tree->gtDebugFlags & GTF_DEBUG_NODE_MORPHED) && "ERROR: Did not morph this node!"); - -#ifdef DEBUG - TransferTestDataToNode(oldTree, tree); -#endif } else { - // Ensure that we haven't morphed this node already + // caller should not have set the morphed flag + // assert(((tree->gtDebugFlags & GTF_DEBUG_NODE_MORPHED) == 0) && "ERROR: Already morphed this node!"); + INDEBUG(tree->gtDebugFlags |= GTF_DEBUG_NODE_MORPHED); } - if (tree->OperIsConst()) - { - goto DONE; - } - - if (!optLocalAssertionProp) + // Note "tree" may generate new assertions that we + // miss if we did them early... perhaps we should skip + // kills but rerun gens. + // + if (tree->OperIsConst() || !optLocalAssertionProp || optAssertionPropDone) { - goto DONE; + return; } - /* Do we have any active assertions? */ - + // Kill active assertions + // if (optAssertionCount > 0) { - /* Is this an assignment to a local variable */ GenTreeLclVarCommon* lclVarTree = nullptr; // The check below will miss LIR-style assignments. @@ -14383,23 +14428,18 @@ void Compiler::fgMorphTreeDone(GenTree* tree, // DefinesLocal can return true for some BLK op uses, so // check what gets assigned only when we're at an assignment. + // if (tree->OperIsSsaDef() && tree->DefinesLocal(this, &lclVarTree)) { - unsigned lclNum = lclVarTree->GetLclNum(); + const unsigned lclNum = lclVarTree->GetLclNum(); noway_assert(lclNum < lvaCount); fgKillDependentAssertions(lclNum DEBUGARG(tree)); } } - /* If this tree makes a new assertion - make it available */ + // Generate new assertions + // optAssertionGen(tree); - -DONE:; - -#ifdef DEBUG - /* Mark this node as being morphed */ - tree->gtDebugFlags |= GTF_DEBUG_NODE_MORPHED; -#endif } //------------------------------------------------------------------------ diff --git a/src/coreclr/jit/morphblock.cpp b/src/coreclr/jit/morphblock.cpp index a976ded54d7f83..d3db65e1785c37 100644 --- a/src/coreclr/jit/morphblock.cpp +++ b/src/coreclr/jit/morphblock.cpp @@ -19,6 +19,8 @@ class MorphInitBlockHelper virtual void TrySpecialCases(); virtual void MorphStructCases(); + void PropagateAssertions(); + virtual const char* GetHelperName() const { return "MorphInitBlock"; @@ -125,7 +127,7 @@ GenTree* MorphInitBlockHelper::Morph() PrepareDst(); PrepareSrc(); - + PropagateAssertions(); TrySpecialCases(); if (m_transformationDecision == BlockTransformation::Undefined) @@ -275,6 +277,23 @@ void MorphInitBlockHelper::PrepareDst() #endif // DEBUG } +//------------------------------------------------------------------------ +// PropagateAssertions: propagate assertions based on the original tree +// +// Notes: +// Once the init or copy tree is morphed, assertion gen can no +// longer recognize what it means. +// +// So we generate assertions based on the original tree. +// +void MorphInitBlockHelper::PropagateAssertions() +{ + if (m_comp->optLocalAssertionProp) + { + m_comp->optAssertionGen(m_asg); + } +} + //------------------------------------------------------------------------ // PrepareSrc: Transform the asg src to an appropriate form and initialize member fields // with information about it. From f8d6d8306f71d20d938478d42d8908ff0e8992bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Rylek?= Date: Wed, 31 Aug 2022 02:55:15 +0200 Subject: [PATCH 044/107] Clean up remnants of Crossgen1 from test scripts and pipelines (#74803) During my work on improving Crossgen2 PDB testing I noticed that we still have a bunch of places containing obsolete provisions for choosing between Crossgen1 and Crossgen2 (Crossgen1 was deleted from the codebase about a year ago). This change cleans them up. Thanks Tomas --- .../templates/runtimes/run-test-job.yml | 20 ++++++------------- .../templates/runtimes/send-to-helix-step.yml | 2 -- .../wasm-runtime-and-send-to-helix.yml | 4 +--- eng/pipelines/coreclr/ci.yml | 1 - eng/pipelines/coreclr/crossgen2-composite.yml | 1 - eng/pipelines/coreclr/crossgen2-gcstress.yml | 1 - eng/pipelines/coreclr/crossgen2.yml | 1 - src/tests/Common/CLRTest.CrossGen.targets | 2 -- src/tests/Common/CLRTest.Execute.Bash.targets | 8 ++++---- .../Common/CLRTest.Execute.Batch.targets | 4 ++-- src/tests/Common/helixpublishwitharcade.proj | 5 ----- src/tests/Common/scripts/bringup_runtest.sh | 2 +- 12 files changed, 14 insertions(+), 37 deletions(-) diff --git a/eng/pipelines/common/templates/runtimes/run-test-job.yml b/eng/pipelines/common/templates/runtimes/run-test-job.yml index 394097adc219f2..4bc3e519aec457 100644 --- a/eng/pipelines/common/templates/runtimes/run-test-job.yml +++ b/eng/pipelines/common/templates/runtimes/run-test-job.yml @@ -9,7 +9,6 @@ parameters: crossrootfsDir: '' readyToRun: false liveLibrariesBuildConfig: '' - crossgen2: false compositeBuildMode: false useCodeFlowEnforcement: '' helixQueues: '' @@ -127,15 +126,9 @@ jobs: - ${{ if eq(parameters.readyToRun, true) }}: - name: crossgenArg - # Switch R2R to use cg2 by default value: 'crossgen2' - name: LogNamePrefix - value: TestRunLogs_R2R - - ${{ if eq(parameters.crossgen2, true) }}: - - name: crossgenArg - value: 'crossgen2' - - name: LogNamePrefix - value: TestRunLogs_R2R_CG2 + value: TestRunLogs_R2R_CG2 - ${{ if eq(parameters.compositeBuildMode, true) }}: - name: crossgenArg value: 'composite' @@ -166,8 +159,8 @@ jobs: # Note that "timeoutInMinutes" is an Azure DevOps Pipelines parameter for a "job" that specifies the # total time allowed for a job, and is specified lower down. Make sure you set it properly for any new testGroup. # - # Please note that for Crossgen / Crossgen2 R2R runs, the "test running time" also includes the - # time needed to compile the test into native code with the Crossgen compiler. + # Please note that for Crossgen2 R2R runs, the "test running time" also includes the + # time needed to compile the test into native code with the Crossgen2 compiler. - name: timeoutPerTestInMinutes value: 10 @@ -176,7 +169,7 @@ jobs: - ${{ if in(parameters.testGroup, 'outerloop') }}: - name: timeoutPerTestCollectionInMinutes value: 120 - - ${{ if eq(parameters.crossgen2, true) }}: + - ${{ if eq(parameters.readyToRun, true) }}: - name: timeoutPerTestCollectionInMinutes value: 90 - name: timeoutPerTestInMinutes @@ -320,7 +313,7 @@ jobs: # Compose the Core_Root folder containing all artifacts needed for running - # CoreCLR tests. This step also compiles the framework using Crossgen / Crossgen2 + # CoreCLR tests. This step also compiles the framework using Crossgen2 # in ReadyToRun jobs. - script: $(Build.SourcesDirectory)/src/tests/build$(scriptExt) generatelayoutonly $(logRootNameArg)Layout $(runtimeFlavorArgs) $(crossgenArg) $(buildConfig) $(archType) $(crossArg) $(priorityArg) $(librariesOverrideArg) $(runtimeVariantArg) displayName: Generate CORE_ROOT @@ -385,8 +378,7 @@ jobs: timeoutPerTestInMinutes: $(timeoutPerTestInMinutes) timeoutPerTestCollectionInMinutes: $(timeoutPerTestCollectionInMinutes) - runCrossGen: ${{ and(eq(parameters.readyToRun, true), ne(parameters.crossgen2, true)) }} - runCrossGen2: ${{ and(eq(parameters.readyToRun, true), eq(parameters.crossgen2, true)) }} + runCrossGen2: ${{ eq(parameters.readyToRun, true) }} ${{ if and(ne(parameters.testGroup, 'innerloop'), eq(parameters.runtimeFlavor, 'coreclr')) }}: runPALTestsDir: '$(coreClrProductRootFolderPath)/paltests' diff --git a/eng/pipelines/common/templates/runtimes/send-to-helix-step.yml b/eng/pipelines/common/templates/runtimes/send-to-helix-step.yml index 99a3de5196ac14..0a0242529eb9d5 100644 --- a/eng/pipelines/common/templates/runtimes/send-to-helix-step.yml +++ b/eng/pipelines/common/templates/runtimes/send-to-helix-step.yml @@ -15,7 +15,6 @@ parameters: scenarios: '' timeoutPerTestCollectionInMinutes: '' timeoutPerTestInMinutes: '' - runCrossGen: '' runCrossGen2: '' runPALTestsDir: '' compositeBuildMode: false @@ -46,7 +45,6 @@ steps: _HelixSource: ${{ parameters.helixSource }} _HelixTargetQueues: ${{ join(',', parameters.helixQueues) }} _HelixType: ${{ parameters.helixType }} - _RunCrossGen: ${{ parameters.runCrossGen }} _RunCrossGen2: ${{ parameters.runCrossGen2 }} _CompositeBuildMode: ${{ parameters.compositeBuildMode }} _RunInUnloadableContext: ${{ parameters.runInUnloadableContext }} diff --git a/eng/pipelines/common/templates/runtimes/wasm-runtime-and-send-to-helix.yml b/eng/pipelines/common/templates/runtimes/wasm-runtime-and-send-to-helix.yml index f1b3bbe955a7c9..1f2f72caca5bde 100644 --- a/eng/pipelines/common/templates/runtimes/wasm-runtime-and-send-to-helix.yml +++ b/eng/pipelines/common/templates/runtimes/wasm-runtime-and-send-to-helix.yml @@ -9,7 +9,6 @@ parameters: crossrootfsDir: '' readyToRun: false liveLibrariesBuildConfig: '' - crossgen2: false compositeBuildMode: false helixQueues: '' stagedBuild: false @@ -66,8 +65,7 @@ steps: timeoutPerTestInMinutes: $(timeoutPerTestInMinutes) timeoutPerTestCollectionInMinutes: $(timeoutPerTestCollectionInMinutes) - runCrossGen: ${{ and(eq(parameters.readyToRun, true), ne(parameters.crossgen2, true)) }} - runCrossGen2: ${{ and(eq(parameters.readyToRun, true), eq(parameters.crossgen2, true)) }} + runCrossGen2: ${{ eq(parameters.readyToRun, true) }} compositeBuildMode: ${{ parameters.compositeBuildMode }} runInUnloadableContext: ${{ parameters.runInUnloadableContext }} diff --git a/eng/pipelines/coreclr/ci.yml b/eng/pipelines/coreclr/ci.yml index ae8e4e42180420..29a0ae0b82d98c 100644 --- a/eng/pipelines/coreclr/ci.yml +++ b/eng/pipelines/coreclr/ci.yml @@ -150,7 +150,6 @@ jobs: jobParameters: testGroup: outerloop readyToRun: true - crossgen2: true displayNameArgs: R2R_CG2 liveLibrariesBuildConfig: Release diff --git a/eng/pipelines/coreclr/crossgen2-composite.yml b/eng/pipelines/coreclr/crossgen2-composite.yml index feea85ea9d3405..6f1957e35847a7 100644 --- a/eng/pipelines/coreclr/crossgen2-composite.yml +++ b/eng/pipelines/coreclr/crossgen2-composite.yml @@ -53,7 +53,6 @@ jobs: jobParameters: testGroup: innerloop readyToRun: true - crossgen2: true compositeBuildMode: true displayNameArgs: Composite liveLibrariesBuildConfig: Release diff --git a/eng/pipelines/coreclr/crossgen2-gcstress.yml b/eng/pipelines/coreclr/crossgen2-gcstress.yml index 70a33503ece4f0..2ebcc27e6f8dba 100644 --- a/eng/pipelines/coreclr/crossgen2-gcstress.yml +++ b/eng/pipelines/coreclr/crossgen2-gcstress.yml @@ -51,7 +51,6 @@ jobs: jobParameters: testGroup: gcstress-extra readyToRun: true - crossgen2: true compositeBuildMode: true displayNameArgs: Composite liveLibrariesBuildConfig: Release diff --git a/eng/pipelines/coreclr/crossgen2.yml b/eng/pipelines/coreclr/crossgen2.yml index 35edb1df223172..bbd2372e327af3 100644 --- a/eng/pipelines/coreclr/crossgen2.yml +++ b/eng/pipelines/coreclr/crossgen2.yml @@ -49,6 +49,5 @@ jobs: jobParameters: testGroup: innerloop readyToRun: true - crossgen2: true displayNameArgs: R2R_CG2 liveLibrariesBuildConfig: Release diff --git a/src/tests/Common/CLRTest.CrossGen.targets b/src/tests/Common/CLRTest.CrossGen.targets index 8109242490fc6a..ca3bde4776b656 100644 --- a/src/tests/Common/CLRTest.CrossGen.targets +++ b/src/tests/Common/CLRTest.CrossGen.targets @@ -42,7 +42,6 @@ WARNING: When setting properties based on their current state (for example: $(TargetArchitecture) $(Configuration) $(Configuration)-$(Scenario) - false false false false $(RuntimeFlavor) - R2R R2R-CG2 $(TestRunNamePrefix)$(TargetOS) $(TargetArchitecture) $(Configuration) @ $(TestRunNamePrefix)$(TargetOS) $(TargetArchitecture) $(Configuration) $(Scenario) @ @@ -514,7 +511,6 @@ - @@ -536,7 +532,6 @@ - diff --git a/src/tests/Common/scripts/bringup_runtest.sh b/src/tests/Common/scripts/bringup_runtest.sh index e532f36631b6be..99f0fd4a966bef 100755 --- a/src/tests/Common/scripts/bringup_runtest.sh +++ b/src/tests/Common/scripts/bringup_runtest.sh @@ -1113,7 +1113,7 @@ do ((disableEventLogging = 1)) ;; --runcrossgentests) - export RunCrossGen=1 + export RunCrossGen2=1 ;; --sequential) ((maxProcesses = 1)) From 4190ef878368d552380329348129a03008fc57cc Mon Sep 17 00:00:00 2001 From: Radek Doulik Date: Wed, 31 Aug 2022 03:36:07 +0200 Subject: [PATCH 045/107] [wasm] SIMD support improvements (#73289) * Initial wasm SIMD support * Enable Vector intrinsic on wasm The llvm code generator works nicely with them. * Add missing files * Make SIMD support conditional * Remove test code * Fix debug build * Update after merge * Add Splat and ExcractLane methods * Switch i64 values for Constant method So that C# WasmBase.Constant(0xff11ff22ff33ff44, 0xff55ff66ff77ff88) is compiled into wasm code v128.const 0xff11ff22ff33ff44ff55ff66ff77ff88 [SIMD] * Update PlatformNotSupported version of WasmBase * Fix CI build * Add ReplaceLane and Swizzle * Change WasmBase.Constant to get Vector128 as input * Add Shuffle methods This will need more work, as it crashes clang during 'WebAssembly Instruction Selection' pass: WasmApp.Native.targets(353,5): error : 3. Running pass 'WebAssembly Instruction Selection' on function '@corlib_System_Runtime_Intrinsics_Wasm_WasmBase_Shuffle_System_Runtime_Intrinsics_Vector128_1_byte_System_Runtime_Intrinsics_Vector128_1_byte_System_Runtime_Intrinsics_Vector128_1_byte' * Handle SN_Shuffle * Fix crash in OP_STOREX_MEMBASE * Add build test * Fix remaining conflict * Remove unused prop * IsSupported should be static * Handle SN_get_IsSupported * Keep passing --enable-simd to wasm-opt * Add Span reverse measurements * Use WasmBase to improve perf of Span reverse | measurement | no SIMD | SIMD | |-:|-:|-:| | Span, Reverse bytes | 0.0341ms | 0.0028ms | | Span, Reverse chars | 0.0394ms | 0.0062ms | * Remove debug prints * Do not expose WasmBase API * Add BuildAdditionalArgs prop To pass args to sample builds * Handle WasmBase.get_IsSupported in the interpreter * Add IndexOf measurements * Add And intrinsic methods * Add more methods to WasmBase classes * Add implementation of the new WasmBase methods * Use WasmBase to improve Span.IndexOf performance Measurements chrome/aot/amd64: | measurement | no SIMD | SIMD | |-:|-:|-:| | Span, Reverse bytes | 0.0332ms | 0.0025ms | | Span, Reverse chars | 0.0332ms | 0.0060ms | | Span, IndexOf bytes | 0.2068us | 0.1002us | | Span, IndexOf chars | 0.0146ms | 0.0028ms | Measurements firefox/aot/amd64: | measurement | no SIMD | SIMD | |-:|-:|-:| | Span, Reverse bytes | 0.0338ms | 0.0022ms | | Span, Reverse chars | 0.0339ms | 0.0048ms | | Span, IndexOf bytes | 0.2533us | 0.1394us | | Span, IndexOf chars | 0.0201ms | 0.0039ms | * Feedback, fix string length in the comparison * Feedback, remove OP_WASM_SIMD_V128_CONST * s/WasmBase/PackedSimd And update parameter names and indentation * Remove Constant method implementation * Remove `using` clauses * One more place to remove Constant method * Fix white space --- .../System.Private.CoreLib.Shared.projitems | 6 + .../Wasm/PackedSimd.PlatformNotSupported.cs | 108 ++++++++++ .../Runtime/Intrinsics/Wasm/PackedSimd.cs | 195 ++++++++++++++++++ src/mono/mono/mini/interp/transform.c | 1 + src/mono/mono/mini/llvm-intrinsics.h | 6 + src/mono/mono/mini/mini-llvm.c | 40 +++- src/mono/mono/mini/mini-ops.h | 8 + src/mono/mono/mini/simd-intrinsics.c | 72 +++++++ src/mono/mono/mini/simd-methods.h | 6 + src/mono/sample/wasm/Directory.Build.targets | 2 +- src/mono/sample/wasm/browser-bench/Program.cs | 1 + src/mono/sample/wasm/browser-bench/Span.cs | 127 ++++++++++++ 12 files changed, 570 insertions(+), 2 deletions(-) create mode 100644 src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Wasm/PackedSimd.PlatformNotSupported.cs create mode 100644 src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Wasm/PackedSimd.cs create mode 100644 src/mono/sample/wasm/browser-bench/Span.cs diff --git a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems index 125ecf85ac0572..86bde088f4ad7b 100644 --- a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems +++ b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems @@ -2363,6 +2363,12 @@ + + + + + + diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Wasm/PackedSimd.PlatformNotSupported.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Wasm/PackedSimd.PlatformNotSupported.cs new file mode 100644 index 00000000000000..00e7b452ec32c4 --- /dev/null +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Wasm/PackedSimd.PlatformNotSupported.cs @@ -0,0 +1,108 @@ +// 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; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.Wasm +{ + internal abstract class PackedSimd + { + public static bool IsSupported { [Intrinsic] get { return false; } } + + public static Vector128 Splat(sbyte value) { throw new PlatformNotSupportedException(); } + public static Vector128 Splat(byte value) { throw new PlatformNotSupportedException(); } + public static Vector128 Splat(short value) { throw new PlatformNotSupportedException(); } + public static Vector128 Splat(ushort value) { throw new PlatformNotSupportedException(); } + public static Vector128 Splat(int value) { throw new PlatformNotSupportedException(); } + public static Vector128 Splat(uint value) { throw new PlatformNotSupportedException(); } + public static Vector128 Splat(long value) { throw new PlatformNotSupportedException(); } + public static Vector128 Splat(ulong value) { throw new PlatformNotSupportedException(); } + public static Vector128 Splat(float value) { throw new PlatformNotSupportedException(); } + public static Vector128 Splat(double value) { throw new PlatformNotSupportedException(); } + public static Vector128 Splat(nint value) { throw new PlatformNotSupportedException(); } + public static Vector128 Splat(nuint value) { throw new PlatformNotSupportedException(); } + + public static int ExtractLane(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + public static uint ExtractLane(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + public static int ExtractLane(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + public static uint ExtractLane(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + public static int ExtractLane(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + public static uint ExtractLane(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + public static long ExtractLane(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + public static ulong ExtractLane(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + public static float ExtractLane(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + public static double ExtractLane(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + public static nint ExtractLane(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + public static nuint ExtractLane(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } + + public static Vector128 ReplaceLane(Vector128 vector, byte imm, int value) { throw new PlatformNotSupportedException(); } + public static Vector128 ReplaceLane(Vector128 vector, byte imm, uint value) { throw new PlatformNotSupportedException(); } + public static Vector128 ReplaceLane(Vector128 vector, byte imm, int value) { throw new PlatformNotSupportedException(); } + public static Vector128 ReplaceLane(Vector128 vector, byte imm, uint value) { throw new PlatformNotSupportedException(); } + public static Vector128 ReplaceLane(Vector128 vector, byte imm, int value) { throw new PlatformNotSupportedException(); } + public static Vector128 ReplaceLane(Vector128 vector, byte imm, uint value) { throw new PlatformNotSupportedException(); } + public static Vector128 ReplaceLane(Vector128 vector, byte imm, long value) { throw new PlatformNotSupportedException(); } + public static Vector128 ReplaceLane(Vector128 vector, byte imm, ulong value) { throw new PlatformNotSupportedException(); } + public static Vector128 ReplaceLane(Vector128 vector, byte imm, float value) { throw new PlatformNotSupportedException(); } + public static Vector128 ReplaceLane(Vector128 vector, byte imm, double value) { throw new PlatformNotSupportedException(); } + public static Vector128 ReplaceLane(Vector128 vector, byte imm, nint value) { throw new PlatformNotSupportedException(); } + public static Vector128 ReplaceLane(Vector128 vector, byte imm, nuint value) { throw new PlatformNotSupportedException(); } + + public static Vector128 Shuffle(Vector128 lower, Vector128 upper, Vector128 indices) { throw new PlatformNotSupportedException(); } + public static Vector128 Shuffle(Vector128 lower, Vector128 upper, Vector128 indices) { throw new PlatformNotSupportedException(); } + + public static Vector128 Swizzle(Vector128 vector, Vector128 indices) { throw new PlatformNotSupportedException(); } + public static Vector128 Swizzle(Vector128 vector, Vector128 indices) { throw new PlatformNotSupportedException(); } + + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + public static int Bitmask(Vector128 value) { throw new PlatformNotSupportedException(); } + public static int Bitmask(Vector128 value) { throw new PlatformNotSupportedException(); } + public static int Bitmask(Vector128 value) { throw new PlatformNotSupportedException(); } + public static int Bitmask(Vector128 value) { throw new PlatformNotSupportedException(); } + public static int Bitmask(Vector128 value) { throw new PlatformNotSupportedException(); } + public static int Bitmask(Vector128 value) { throw new PlatformNotSupportedException(); } + public static int Bitmask(Vector128 value) { throw new PlatformNotSupportedException(); } + public static int Bitmask(Vector128 value) { throw new PlatformNotSupportedException(); } + public static int Bitmask(Vector128 value) { throw new PlatformNotSupportedException(); } + public static int Bitmask(Vector128 value) { throw new PlatformNotSupportedException(); } + + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } + } +} diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Wasm/PackedSimd.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Wasm/PackedSimd.cs new file mode 100644 index 00000000000000..3e5e22ce596275 --- /dev/null +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Wasm/PackedSimd.cs @@ -0,0 +1,195 @@ +// 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; +using System.Runtime.Intrinsics; + +namespace System.Runtime.Intrinsics.Wasm +{ + [Intrinsic] + internal abstract class PackedSimd + { + public static bool IsSupported { [Intrinsic] get { return false; } } + + [Intrinsic] + public static Vector128 Splat(sbyte value) => Splat(value); + [Intrinsic] + public static Vector128 Splat(byte value) => Splat(value); + [Intrinsic] + public static Vector128 Splat(short value) => Splat(value); + [Intrinsic] + public static Vector128 Splat(ushort value) => Splat(value); + [Intrinsic] + public static Vector128 Splat(int value) => Splat(value); + [Intrinsic] + public static Vector128 Splat(uint value) => Splat(value); + [Intrinsic] + public static Vector128 Splat(long value) => Splat(value); + [Intrinsic] + public static Vector128 Splat(ulong value) => Splat(value); + [Intrinsic] + public static Vector128 Splat(float value) => Splat(value); + [Intrinsic] + public static Vector128 Splat(double value) => Splat(value); + [Intrinsic] + public static Vector128 Splat(nint value) => Splat(value); + [Intrinsic] + public static Vector128 Splat(nuint value) => Splat(value); + + [Intrinsic] + public static int ExtractLane(Vector128 value, byte index) => ExtractLane(value, index); // takes ImmLaneIdx16 + [Intrinsic] + public static uint ExtractLane(Vector128 value, byte index) => ExtractLane(value, index); // takes ImmLaneIdx16 + [Intrinsic] + public static int ExtractLane(Vector128 value, byte index) => ExtractLane(value, index); // takes ImmLaneIdx8 + [Intrinsic] + public static uint ExtractLane(Vector128 value, byte index) => ExtractLane(value, index); // takes ImmLaneIdx8 + [Intrinsic] + public static int ExtractLane(Vector128 value, byte index) => ExtractLane(value, index); // takes ImmLaneIdx4 + [Intrinsic] + public static uint ExtractLane(Vector128 value, byte index) => ExtractLane(value, index); // takes ImmLaneIdx4 + [Intrinsic] + public static long ExtractLane(Vector128 value, byte index) => ExtractLane(value, index); // takes ImmLaneIdx2 + [Intrinsic] + public static ulong ExtractLane(Vector128 value, byte index) => ExtractLane(value, index); // takes ImmLaneIdx2 + [Intrinsic] + public static float ExtractLane(Vector128 value, byte index) => ExtractLane(value, index); // takes ImmLaneIdx4 + [Intrinsic] + public static double ExtractLane(Vector128 value, byte index) => ExtractLane(value, index); // takes ImmLaneIdx2 + [Intrinsic] + public static nint ExtractLane(Vector128 value, byte index) => ExtractLane(value, index); + [Intrinsic] + public static nuint ExtractLane(Vector128 value, byte index) => ExtractLane(value, index); + + [Intrinsic] + public static Vector128 ReplaceLane(Vector128 vector, byte imm, int value) => ReplaceLane(vector, imm, value); // takes ImmLaneIdx16 + [Intrinsic] + public static Vector128 ReplaceLane(Vector128 vector, byte imm, uint value) => ReplaceLane(vector, imm, value); // takes ImmLaneIdx16 + [Intrinsic] + public static Vector128 ReplaceLane(Vector128 vector, byte imm, int value) => ReplaceLane(vector, imm, value); // takes ImmLaneIdx8 + [Intrinsic] + public static Vector128 ReplaceLane(Vector128 vector, byte imm, uint value) => ReplaceLane(vector, imm, value); // takes ImmLaneIdx8 + [Intrinsic] + public static Vector128 ReplaceLane(Vector128 vector, byte imm, int value) => ReplaceLane(vector, imm, value); // takes ImmLaneIdx4 + [Intrinsic] + public static Vector128 ReplaceLane(Vector128 vector, byte imm, uint value) => ReplaceLane(vector, imm, value); // takes ImmLaneIdx4 + [Intrinsic] + public static Vector128 ReplaceLane(Vector128 vector, byte imm, long value) => ReplaceLane(vector, imm, value); // takes ImmLaneIdx2 + [Intrinsic] + public static Vector128 ReplaceLane(Vector128 vector, byte imm, ulong value) => ReplaceLane(vector, imm, value); // takes ImmLaneIdx2 + [Intrinsic] + public static Vector128 ReplaceLane(Vector128 vector, byte imm, float value) => ReplaceLane(vector, imm, value); // takes ImmLaneIdx4 + [Intrinsic] + public static Vector128 ReplaceLane(Vector128 vector, byte imm, double value) => ReplaceLane(vector, imm, value); // takes ImmLaneIdx2 + [Intrinsic] + public static Vector128 ReplaceLane(Vector128 vector, byte imm, nint value) => ReplaceLane(vector, imm, value); + [Intrinsic] + public static Vector128 ReplaceLane(Vector128 vector, byte imm, nuint value) => ReplaceLane(vector, imm, value); + + [Intrinsic] + public static Vector128 Shuffle(Vector128 lower, Vector128 upper, Vector128 indices) => Shuffle(lower, upper, indices); + [Intrinsic] + public static Vector128 Shuffle(Vector128 lower, Vector128 upper, Vector128 indices) => Shuffle(lower, upper, indices); + + [Intrinsic] + public static Vector128 Swizzle(Vector128 vector, Vector128 indices) => Swizzle(vector, indices); + [Intrinsic] + public static Vector128 Swizzle(Vector128 vector, Vector128 indices) => Swizzle(vector, indices); + + [Intrinsic] + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + [Intrinsic] + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + [Intrinsic] + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + [Intrinsic] + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + [Intrinsic] + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + [Intrinsic] + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + [Intrinsic] + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + [Intrinsic] + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + [Intrinsic] + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + [Intrinsic] + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + [Intrinsic] + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + [Intrinsic] + public static Vector128 And(Vector128 left, Vector128 right) => And(left, right); + + [Intrinsic] + public static int Bitmask(Vector128 value) => Bitmask(value); + [Intrinsic] + public static int Bitmask(Vector128 value) => Bitmask(value); + [Intrinsic] + public static int Bitmask(Vector128 value) => Bitmask(value); + [Intrinsic] + public static int Bitmask(Vector128 value) => Bitmask(value); + [Intrinsic] + public static int Bitmask(Vector128 value) => Bitmask(value); + [Intrinsic] + public static int Bitmask(Vector128 value) => Bitmask(value); + [Intrinsic] + public static int Bitmask(Vector128 value) => Bitmask(value); + [Intrinsic] + public static int Bitmask(Vector128 value) => Bitmask(value); + [Intrinsic] + public static int Bitmask(Vector128 value) => Bitmask(value); + [Intrinsic] + public static int Bitmask(Vector128 value) => Bitmask(value); + + [Intrinsic] + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + [Intrinsic] + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + [Intrinsic] + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + [Intrinsic] + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + [Intrinsic] + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + [Intrinsic] + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + [Intrinsic] + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + [Intrinsic] + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + [Intrinsic] + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + [Intrinsic] + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + [Intrinsic] + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + [Intrinsic] + public static Vector128 CompareEqual(Vector128 left, Vector128 right) => CompareEqual(left, right); + + [Intrinsic] + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + [Intrinsic] + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + [Intrinsic] + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + [Intrinsic] + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + [Intrinsic] + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + [Intrinsic] + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + [Intrinsic] + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + [Intrinsic] + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + [Intrinsic] + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + [Intrinsic] + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + [Intrinsic] + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + [Intrinsic] + public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) => CompareNotEqual(left, right); + } +} diff --git a/src/mono/mono/mini/interp/transform.c b/src/mono/mono/mini/interp/transform.c index d8679166af3fd6..d76a5c121b789c 100644 --- a/src/mono/mono/mini/interp/transform.c +++ b/src/mono/mono/mini/interp/transform.c @@ -2462,6 +2462,7 @@ interp_handle_intrinsics (TransformData *td, MonoMethod *target_method, MonoClas *op = MINT_LDC_I4_0; } else if (in_corlib && (!strncmp ("System.Runtime.Intrinsics.Arm", klass_name_space, 29) || + !strncmp ("System.Runtime.Intrinsics.PackedSimd", klass_name_space, 36) || !strncmp ("System.Runtime.Intrinsics.X86", klass_name_space, 29)) && !strcmp (tm, "get_IsSupported")) { *op = MINT_LDC_I4_0; diff --git a/src/mono/mono/mini/llvm-intrinsics.h b/src/mono/mono/mini/llvm-intrinsics.h index 7981b3f9d6dfda..ce6e4ef7ac5ddc 100644 --- a/src/mono/mono/mini/llvm-intrinsics.h +++ b/src/mono/mono/mini/llvm-intrinsics.h @@ -257,6 +257,12 @@ INTRINS_OVR(WASM_ANYTRUE_V16, wasm_anytrue, Wasm, sse_i1_t) INTRINS_OVR(WASM_ANYTRUE_V8, wasm_anytrue, Wasm, sse_i2_t) INTRINS_OVR(WASM_ANYTRUE_V4, wasm_anytrue, Wasm, sse_i4_t) INTRINS_OVR(WASM_ANYTRUE_V2, wasm_anytrue, Wasm, sse_i8_t) +INTRINS_OVR(WASM_BITMASK_V16, wasm_bitmask, Wasm, sse_i1_t) +INTRINS_OVR(WASM_BITMASK_V8, wasm_bitmask, Wasm, sse_i1_t) +INTRINS_OVR(WASM_BITMASK_V4, wasm_bitmask, Wasm, sse_i4_t) +INTRINS_OVR(WASM_BITMASK_V2, wasm_bitmask, Wasm, sse_i8_t) +INTRINS(WASM_SHUFFLE, wasm_shuffle, Wasm) +INTRINS(WASM_SWIZZLE, wasm_swizzle, Wasm) #endif #if defined(TARGET_ARM64) INTRINS_OVR(BITREVERSE_I32, bitreverse, Generic, LLVMInt32Type ()) diff --git a/src/mono/mono/mini/mini-llvm.c b/src/mono/mono/mini/mini-llvm.c index 3d7a809c2173a8..b43892dcb1de47 100644 --- a/src/mono/mono/mini/mini-llvm.c +++ b/src/mono/mono/mini/mini-llvm.c @@ -9683,7 +9683,45 @@ MONO_RESTORE_WARNING break; } #endif - +#if defined(TARGET_WASM) + case OP_WASM_SIMD_BITMASK: { + LLVMValueRef args [] = { lhs }; + int nelems = LLVMGetVectorSize (LLVMTypeOf (lhs)); + IntrinsicId intrins = (IntrinsicId)0; + switch (nelems) { + case 16: + intrins = INTRINS_WASM_BITMASK_V16; + break; + case 8: + intrins = INTRINS_WASM_BITMASK_V8; + break; + case 4: + intrins = INTRINS_WASM_BITMASK_V4; + break; + case 2: + intrins = INTRINS_WASM_BITMASK_V2; + break; + default: + g_assert_not_reached (); + } + values [ins->dreg] = call_intrins (ctx, intrins, args, ""); + break; + } + case OP_WASM_SIMD_SHUFFLE: { + /* FIXME: this crashes 'WebAssembly Instruction Selection' pass in some cases */ + LLVMValueRef args [18] = { lhs, rhs }; + for (int i = 0; i < 16; i++) { + args[2 + i] = LLVMBuildZExt (builder, LLVMBuildExtractElement (builder, arg3, const_int32 (i), ""), LLVMInt32Type (), ""); + } + values [ins->dreg] = call_intrins (ctx, INTRINS_WASM_SHUFFLE, args, "i8x16.shuffle"); + break; + } + case OP_WASM_SIMD_SWIZZLE: { + LLVMValueRef args [] = { lhs, rhs }; + values [ins->dreg] = call_intrins (ctx, INTRINS_WASM_SWIZZLE, args, ""); + break; + } +#endif #if defined(TARGET_ARM64) || defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_WASM) case OP_XEQUAL: { LLVMTypeRef t; diff --git a/src/mono/mono/mini/mini-ops.h b/src/mono/mono/mini/mini-ops.h index c53e081ff07bc4..7e17f88030bdc9 100644 --- a/src/mono/mono/mini/mini-ops.h +++ b/src/mono/mono/mini/mini-ops.h @@ -846,6 +846,14 @@ MINI_OP(OP_EXPAND_R8, "expand_r8", XREG, FREG, NONE) #endif +// wasm specific SIMD v128 + +#if defined(TARGET_WASM) +MINI_OP(OP_WASM_SIMD_BITMASK, "wasm_bitmask", IREG, XREG, NONE) +MINI_OP3(OP_WASM_SIMD_SHUFFLE, "wasm_shuffle", VREG, XREG, XREG, XREG) +MINI_OP(OP_WASM_SIMD_SWIZZLE, "wasm_swizzle", VREG, XREG, XREG) +#endif + #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_WASM) MINI_OP(OP_ADDPS, "addps", XREG, XREG, XREG) diff --git a/src/mono/mono/mini/simd-intrinsics.c b/src/mono/mono/mini/simd-intrinsics.c index 376f2b69386ceb..ccc1f0d4e81c89 100644 --- a/src/mono/mono/mini/simd-intrinsics.c +++ b/src/mono/mono/mini/simd-intrinsics.c @@ -4009,6 +4009,72 @@ emit_amd64_intrinsics (const char *class_ns, const char *class_name, MonoCompile } #endif // !TARGET_ARM64 +#ifdef TARGET_WASM + +static SimdIntrinsic packedsimd_methods [] = { + {SN_And}, + {SN_Bitmask}, + {SN_CompareEqual}, + {SN_CompareNotEqual}, + {SN_ExtractLane}, + {SN_ReplaceLane}, + {SN_Shuffle}, + {SN_Splat}, + {SN_Swizzle}, + {SN_get_IsSupported}, +}; + +static const IntrinGroup supported_wasm_intrinsics [] = { + { "PackedSimd", 0, packedsimd_methods, sizeof (packedsimd_methods) }, +}; + +static MonoInst* +emit_packedsimd_intrinsics ( + MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, + MonoClass *klass, const IntrinGroup *intrin_group, + const SimdIntrinsic *info, int id, MonoTypeEnum arg0_type, + gboolean is_64bit) +{ + if (!is_element_type_primitive (fsig->params [0])) + return NULL; + + switch (id) { + case SN_And: + return emit_simd_ins_for_sig (cfg, klass, OP_XBINOP_FORCEINT, XBINOP_FORCEINT_AND, arg0_type, fsig, args); + case SN_Bitmask: + return emit_simd_ins_for_sig (cfg, klass, OP_WASM_SIMD_BITMASK, -1, -1, fsig, args); + case SN_CompareEqual: + return emit_simd_ins_for_sig (cfg, klass, type_enum_is_float (arg0_type) ? OP_XCOMPARE_FP : OP_XCOMPARE, CMP_EQ, arg0_type, fsig, args); + case SN_CompareNotEqual: + return emit_simd_ins_for_sig (cfg, klass, type_enum_is_float (arg0_type) ? OP_XCOMPARE_FP : OP_XCOMPARE, CMP_NE, arg0_type, fsig, args); + case SN_ExtractLane: { + int extract_op = type_to_xextract_op (arg0_type); + return emit_simd_ins_for_sig (cfg, klass, extract_op, -1, arg0_type, fsig, args); + } + case SN_ReplaceLane: { + int insert_op = type_to_xinsert_op (arg0_type); + MonoInst *ins = emit_simd_ins (cfg, klass, insert_op, args [0]->dreg, args [2]->dreg); + ins->sreg3 = args [1]->dreg; + ins->inst_c1 = arg0_type; + return ins; + } + case SN_Splat: { + MonoType *etype = get_vector_t_elem_type (fsig->ret); + g_assert (fsig->param_count == 1 && mono_metadata_type_equal (fsig->params [0], etype)); + return emit_simd_ins (cfg, klass, type_to_expand_op (etype), args [0]->dreg, -1); + } + case SN_Shuffle: + return emit_simd_ins_for_sig (cfg, klass, OP_WASM_SIMD_SHUFFLE, -1, -1, fsig, args); + case SN_Swizzle: + return emit_simd_ins_for_sig (cfg, klass, OP_WASM_SIMD_SWIZZLE, -1, -1, fsig, args); + } + g_assert_not_reached (); + + return NULL; +} + +#endif // TARGET_WASM + #ifdef TARGET_ARM64 static MonoInst* @@ -4078,6 +4144,12 @@ static MonoInst* arch_emit_simd_intrinsics (const char *class_ns, const char *class_name, MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args) { + if (!strcmp (class_ns, "System.Runtime.Intrinsics.Wasm")) { + return emit_hardware_intrinsics (cfg, cmethod, fsig, args, + supported_wasm_intrinsics, sizeof (supported_wasm_intrinsics), + emit_packedsimd_intrinsics); + } + if (!strcmp (class_ns, "System.Runtime.Intrinsics")) { if (!strcmp (class_name, "Vector128")) return emit_sri_vector (cfg, cmethod, fsig, args); diff --git a/src/mono/mono/mini/simd-methods.h b/src/mono/mono/mini/simd-methods.h index aa7d3a82df8890..98073ca2de86ac 100644 --- a/src/mono/mono/mini/simd-methods.h +++ b/src/mono/mono/mini/simd-methods.h @@ -619,3 +619,9 @@ METHOD(MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh) METHOD(MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh) // Arm.Dp METHOD(DotProductBySelectedQuadruplet) +// Wasm +METHOD(Bitmask) +METHOD(Splat) +METHOD(ExtractLane) +METHOD(ReplaceLane) +METHOD(Swizzle) diff --git a/src/mono/sample/wasm/Directory.Build.targets b/src/mono/sample/wasm/Directory.Build.targets index 6905d9d6d7e369..cf7244f6ecb464 100644 --- a/src/mono/sample/wasm/Directory.Build.targets +++ b/src/mono/sample/wasm/Directory.Build.targets @@ -26,7 +26,7 @@ <_AOTFlag Condition="'$(RunAOTCompilation)' != ''">/p:RunAOTCompilation=$(RunAOTCompilation) <_WasmMainJSFileName>$([System.IO.Path]::GetFileName('$(WasmMainJSPath)')) - + diff --git a/src/mono/sample/wasm/browser-bench/Program.cs b/src/mono/sample/wasm/browser-bench/Program.cs index 9dc00caa3473a1..1c524821af0eb7 100644 --- a/src/mono/sample/wasm/browser-bench/Program.cs +++ b/src/mono/sample/wasm/browser-bench/Program.cs @@ -23,6 +23,7 @@ public partial class Test new AppStartTask(), new ExceptionsTask(), new JsonTask(), + new SpanTask(), new VectorTask(), new JSInteropTask(), new WebSocketTask(), diff --git a/src/mono/sample/wasm/browser-bench/Span.cs b/src/mono/sample/wasm/browser-bench/Span.cs new file mode 100644 index 00000000000000..e282098c8de029 --- /dev/null +++ b/src/mono/sample/wasm/browser-bench/Span.cs @@ -0,0 +1,127 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Runtime.InteropServices; +using System.Threading.Tasks; + +namespace Sample +{ + class SpanTask : BenchTask + { + public override string Name => "Span"; + Measurement[] measurements; + + public SpanTask() + { + measurements = new Measurement[] { + new ReverseByte(), + new ReverseChar(), + new IndexOfByte(), + new IndexOfChar(), + }; + } + + public override Measurement[] Measurements + { + get + { + return measurements; + } + } + + public abstract class SpanMeasurement : BenchTask.Measurement + { + public override int InitialSamples => 30; + protected Random random; + } + + abstract class SpanByteMeasurement : SpanMeasurement + { + protected byte[] data; + int len = 64 * 1024; + + public override Task BeforeBatch() + { + data = new byte[len]; + random = new(123456); + random.NextBytes(data); + + return Task.CompletedTask; + } + + public override Task AfterBatch() + { + data = null; + + return Task.CompletedTask; + } + } + + class ReverseByte : SpanByteMeasurement + { + public override string Name => "Reverse bytes"; + + public override void RunStep() + { + var span = new Span(data); + span.Reverse(); + } + } + + class IndexOfByte : SpanByteMeasurement + { + public override string Name => "IndexOf bytes"; + public override int InitialSamples => 1000; + + public override void RunStep() + { + var span = new Span(data); + span.IndexOf ((byte)random.Next(256)); + } + } + + abstract class SpanCharMeasurement : SpanMeasurement + { + protected char[] data; + int len = 64 * 1024; + + public override Task BeforeBatch() + { + data = new char[len]; + random = new(123456); + for (int i = 0; i < len; i++) + data[i] = (char)random.Next(0x10000); + + return Task.CompletedTask; + } + + public override Task AfterBatch() + { + data = null; + + return Task.CompletedTask; + } + } + + class ReverseChar : SpanCharMeasurement + { + public override string Name => "Reverse chars"; + public override void RunStep() + { + var span = new Span(data); + span.Reverse(); + } + } + + class IndexOfChar : SpanCharMeasurement + { + public override string Name => "IndexOf chars"; + public override void RunStep() + { + var span = new Span(data); + span.IndexOf((char)random.Next(0x10000)); + } + } + } +} From 51f3ca60ed119375fe55fd300b219ee2317dbb75 Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Wed, 31 Aug 2022 00:31:58 -0400 Subject: [PATCH 046/107] [wasm] Avoid duplicate jobs in `runtime-wasm` (#74837) * CI: On runtime-wasm skip the jobs that would run on runtime * CI: Enable evaluate-default-paths for runtime-wasm * CI: In runtime-extra-platforms, run wasm jobs only on rolling builds --- .../common/templates/wasm-build-only.yml | 32 ++++++++--- .../common/templates/wasm-build-tests.yml | 27 ++++++++- .../common/templates/wasm-debugger-tests.yml | 28 ++++++++-- .../templates/wasm-library-aot-tests.yml | 7 ++- .../common/templates/wasm-library-tests.yml | 32 ++++++++--- .../common/templates/wasm-runtime-tests.yml | 30 ++++++++-- eng/pipelines/common/variables.yml | 2 +- eng/pipelines/common/xplat-setup.yml | 2 +- .../runtime-extra-platforms-wasm.yml | 56 +++++++++++++------ eng/pipelines/runtime-extra-platforms.yml | 12 ++-- eng/pipelines/runtime-wasm.yml | 4 +- 11 files changed, 177 insertions(+), 55 deletions(-) diff --git a/eng/pipelines/common/templates/wasm-build-only.yml b/eng/pipelines/common/templates/wasm-build-only.yml index cfb6f40f09532e..761de04536d07c 100644 --- a/eng/pipelines/common/templates/wasm-build-only.yml +++ b/eng/pipelines/common/templates/wasm-build-only.yml @@ -27,20 +27,36 @@ jobs: value: ${{ parameters.alwaysRun }} - name: allWasmContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] + - name: isDefaultPipeline + # default pipeline, so not runtime-wasm, and not + # runtime-extra-platforms+rolling build + value: ${{ + and( + ne(parameters.isWasmOnlyBuild, true), + or( + ne(parameters.isExtraPlatformsBuild, true), + eq(variables['isRollingBuild'], true))) + }} + - name: shouldRunOnDefaultPipelines + value: $[ + or( + eq(variables['wasmDarcDependenciesChanged'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true)) + ] jobParameters: isExtraPlatforms: ${{ parameters.isExtraPlatformsBuild }} testGroup: innerloop nameSuffix: ${{ parameters.nameSuffix }}_BuildOnly buildArgs: -s mono+libs+host -c $(_BuildConfig) /p:ArchiveTests=true /p:BrowserHost=$(_hostedOs) ${{ parameters.extraBuildArgs }} timeoutInMinutes: 240 - # always run for runtime-wasm builds (triggered manually) - # Always run for rolling builds - # Else run on path changes + # if !alwaysRun, then: + # if this is runtime-wasm (isWasmOnlyBuild): + # - then run only if it would not have run on default pipelines (based + # on path changes) + # - else run based on path changes condition: >- or( eq(variables['alwaysRunVar'], true), - eq(variables['wasmDarcDependenciesChanged'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true)) - + eq(variables['isDefaultPipeline'], variables['shouldRunOnDefaultPipelines'])) diff --git a/eng/pipelines/common/templates/wasm-build-tests.yml b/eng/pipelines/common/templates/wasm-build-tests.yml index c9c8689fa671e3..7ce2176f19a84d 100644 --- a/eng/pipelines/common/templates/wasm-build-tests.yml +++ b/eng/pipelines/common/templates/wasm-build-tests.yml @@ -1,6 +1,7 @@ parameters: alwaysRun: false isExtraPlatformsBuild: false + isWasmOnlyBuild: false platforms: [] shouldContinueOnError: false @@ -25,18 +26,38 @@ jobs: value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] - name: alwaysRunVar value: ${{ parameters.alwaysRun }} + - name: isDefaultPipeline + # default pipeline, so not runtime-wasm, and not + # runtime-extra-platforms+rolling build + value: ${{ + and( + ne(parameters.isWasmOnlyBuild, true), + or( + ne(parameters.isExtraPlatformsBuild, true), + eq(variables['isRollingBuild'], true))) + }} + - name: shouldRunOnDefaultPipelines + value: $[ + or( + eq(variables['wasmDarcDependenciesChanged'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_wasmbuildtests.containsChange'], true)) + ] jobParameters: isExtraPlatforms: ${{ parameters.isExtraPlatformsBuild }} testGroup: innerloop nameSuffix: WasmBuildTests buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:TestWasmBuildTests=true /p:TestAssemblies=false /p:BrowserHost=$(_hostedOs) timeoutInMinutes: 180 + # if !alwaysRun, then: + # if this is runtime-wasm (isWasmOnlyBuild): + # - then run only if it would not have run on default pipelines (based + # on path changes) + # - else run based on path changes condition: >- or( eq(variables['alwaysRunVar'], true), - eq(variables['wasmDarcDependenciesChanged'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_wasmbuildtests.containsChange'], true)) + eq(variables['isDefaultPipeline'], variables['shouldRunOnDefaultPipelines'])) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: diff --git a/eng/pipelines/common/templates/wasm-debugger-tests.yml b/eng/pipelines/common/templates/wasm-debugger-tests.yml index 5ac7c3ee5dccf8..2bd104a6592036 100644 --- a/eng/pipelines/common/templates/wasm-debugger-tests.yml +++ b/eng/pipelines/common/templates/wasm-debugger-tests.yml @@ -1,6 +1,7 @@ parameters: alwaysRun: false isExtraPlatformsBuild: false + isWasmOnlyBuild: false browser: 'chrome' shouldContinueOnError: false platforms: [] @@ -24,19 +25,38 @@ jobs: value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] - name: alwaysRunVar value: ${{ parameters.alwaysRun }} + - name: isDefaultPipeline + # default pipeline, so not runtime-wasm, and not + # runtime-extra-platforms+rolling build + value: ${{ + and( + ne(parameters.isWasmOnlyBuild, true), + or( + ne(parameters.isExtraPlatformsBuild, true), + eq(variables['isRollingBuild'], true))) + }} + - name: shouldRunOnDefaultPipelines + value: $[ + or( + eq(variables['wasmDarcDependenciesChanged'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_wasmdebuggertests.containsChange'], true)) + ] jobParameters: testGroup: innerloop isExtraPlatforms: ${{ parameters.isExtraPlatformsBuild }} nameSuffix: Mono_DebuggerTests_${{ parameters.browser }} buildArgs: -s mono+libs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:TestWasmDebuggerTests=true /p:TestAssemblies=false /p:BrowserHost=$(_hostedOs) /p:DebuggerHost=${{ parameters.browser }} timeoutInMinutes: 180 + # if !alwaysRun, then: + # if this is runtime-wasm (isWasmOnlyBuild): + # - then run only if it would not have run on default pipelines (based + # on path changes) + # - else run based on path changes condition: >- or( eq(variables['alwaysRunVar'], true), - eq(variables['wasmDarcDependenciesChanged'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_wasmdebuggertests.containsChange'], true)) - # extra steps, run tests + eq(variables['isDefaultPipeline'], variables['shouldRunOnDefaultPipelines'])) extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: creator: dotnet-bot diff --git a/eng/pipelines/common/templates/wasm-library-aot-tests.yml b/eng/pipelines/common/templates/wasm-library-aot-tests.yml index 3f15283cf6b3fa..0a50a752c408d4 100644 --- a/eng/pipelines/common/templates/wasm-library-aot-tests.yml +++ b/eng/pipelines/common/templates/wasm-library-aot-tests.yml @@ -3,6 +3,7 @@ parameters: extraBuildArgs: '' extraHelixArgs: '' isExtraPlatformsBuild: false + isWasmOnlyBuild: false buildAOTOnHelix: true nameSuffix: '' platforms: [] @@ -22,7 +23,8 @@ jobs: platforms: - Browser_wasm nameSuffix: ${{ parameters.nameSuffix }} - isExtraPlatforms: ${{ parameters.isExtraPlatformsBuild }} + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} extraBuildArgs: /p:EnableAggressiveTrimming=true /p:BuildAOTTestsOnHelix=${{ parameters.buildAOTOnHelix }} /p:RunAOTCompilation=${{ parameters.runAOT }} ${{ parameters.extraBuildArgs }} extraHelixArgs: /p:NeedsToBuildWasmAppsOnHelix=true ${{ parameters.extraHelixArgs }} alwaysRun: ${{ parameters.alwaysRun }} @@ -38,7 +40,8 @@ jobs: platforms: - Browser_wasm_win nameSuffix: ${{ parameters.nameSuffix }} - isExtraPlatforms: ${{ parameters.isExtraPlatformsBuild }} + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} extraBuildArgs: /p:EnableAggressiveTrimming=true /p:BuildAOTTestsOnHelix=${{ parameters.buildAOTOnHelix }} /p:RunAOTCompilation=${{ parameters.runAOT }} ${{ parameters.extraBuildArgs }} extraHelixArgs: /p:NeedsToBuildWasmAppsOnHelix=true ${{ parameters.extraHelixArgs }} alwaysRun: ${{ parameters.alwaysRun }} diff --git a/eng/pipelines/common/templates/wasm-library-tests.yml b/eng/pipelines/common/templates/wasm-library-tests.yml index a1f28093bfc9f2..f96ca8aa1aabeb 100644 --- a/eng/pipelines/common/templates/wasm-library-tests.yml +++ b/eng/pipelines/common/templates/wasm-library-tests.yml @@ -4,6 +4,7 @@ parameters: extraBuildArgs: '' extraHelixArgs: '' isExtraPlatformsBuild: false + isWasmOnlyBuild: false nameSuffix: '' platforms: [] runSmokeOnlyArg: '' @@ -33,22 +34,39 @@ jobs: value: ${{ parameters.alwaysRun }} - name: allWasmContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] + - name: isDefaultPipeline + # default pipeline, so not runtime-wasm, and not + # runtime-extra-platforms+rolling build + value: ${{ + and( + ne(parameters.isWasmOnlyBuild, true), + or( + ne(parameters.isExtraPlatformsBuild, true), + eq(variables['isRollingBuild'], true))) + }} + - name: shouldRunOnDefaultPipelines + value: $[ + or( + eq(variables['wasmDarcDependenciesChanged'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true)) + ] jobParameters: isExtraPlatforms: ${{ parameters.isExtraPlatformsBuild }} testGroup: innerloop nameSuffix: LibraryTests${{ parameters.nameSuffix }} buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:BrowserHost=$(_hostedOs) ${{ parameters.runSmokeOnlyArg }} ${{ parameters.extraBuildArgs }} timeoutInMinutes: 240 - # always run for runtime-wasm builds (triggered manually) - # Always run for rolling builds - # Else run on path changes + # if !alwaysRun, then: + # if this is runtime-wasm (isWasmOnlyBuild): + # - then run only if it would not have run on default pipelines (based + # on path changes) + # - else run based on path changes condition: >- or( eq(variables['alwaysRunVar'], true), - eq(variables['wasmDarcDependenciesChanged'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true)) + eq(variables['isDefaultPipeline'], variables['shouldRunOnDefaultPipelines'])) # extra steps, run tests extraStepsTemplate: /eng/pipelines/common/templates/additional-steps-then-helix.yml extraStepsParameters: diff --git a/eng/pipelines/common/templates/wasm-runtime-tests.yml b/eng/pipelines/common/templates/wasm-runtime-tests.yml index 37154b3c6e86d4..b244949340241c 100644 --- a/eng/pipelines/common/templates/wasm-runtime-tests.yml +++ b/eng/pipelines/common/templates/wasm-runtime-tests.yml @@ -1,6 +1,7 @@ parameters: alwaysRun: false isExtraPlatformsBuild: false + isWasmOnlyBuild: false platforms: [] jobs: @@ -24,20 +25,39 @@ jobs: value: 10 - name: timeoutPerTestCollectionInMinutes value: 200 + - name: isDefaultPipeline + # default pipeline, so not runtime-wasm, and not + # runtime-extra-platforms+!rolling build + value: ${{ + and( + ne(parameters.isWasmOnlyBuild, true), + or( + ne(parameters.isExtraPlatformsBuild, true), + eq(variables['isRollingBuild'], true))) + }} + - name: shouldRunOnDefaultPipelines + value: $[ + or( + eq(variables['wasmDarcDependenciesChanged'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true)) + ] jobParameters: testGroup: innerloop isExtraPlatforms: ${{ parameters.isExtraPlatformsBuild }} nameSuffix: AllSubsets_Mono_RuntimeTests runtimeVariant: monointerpreter buildArgs: -s mono+libs -c $(_BuildConfig) - timeoutInMinutes: 180 + # if !alwaysRun, then: + # if this is runtime-wasm (isWasmOnlyBuild): + # - then run only if it would not have run on default pipelines (based + # on path changes) + # - else run based on path changes condition: >- or( eq(variables['alwaysRunVar'], true), - eq(variables['wasmDarcDependenciesChanged'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true)) + eq(variables['isDefaultPipeline'], variables['shouldRunOnDefaultPipelines'])) extraStepsTemplate: /eng/pipelines/common/templates/runtimes/wasm-runtime-and-send-to-helix.yml extraStepsParameters: creator: dotnet-bot diff --git a/eng/pipelines/common/variables.yml b/eng/pipelines/common/variables.yml index 76156f4821f604..ea0836fc802440 100644 --- a/eng/pipelines/common/variables.yml +++ b/eng/pipelines/common/variables.yml @@ -27,7 +27,7 @@ variables: # We only run evaluate paths on runtime, runtime-staging and runtime-community pipelines on PRs # keep in sync with /eng/pipelines/common/xplat-setup.yml - name: dependOnEvaluatePaths - value: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community', 'runtime-extra-platforms')) }} + value: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community', 'runtime-extra-platforms', 'runtime-wasm')) }} - name: debugOnPrReleaseOnRolling ${{ if ne(variables['Build.Reason'], 'PullRequest') }}: value: Release diff --git a/eng/pipelines/common/xplat-setup.yml b/eng/pipelines/common/xplat-setup.yml index 02b09633753874..9d91ccd891da39 100644 --- a/eng/pipelines/common/xplat-setup.yml +++ b/eng/pipelines/common/xplat-setup.yml @@ -18,7 +18,7 @@ jobs: shouldContinueOnError: ${{ or(eq(parameters.shouldContinueOnError, true), and(ne(parameters.shouldContinueOnError, 'forceFalse'), endsWith(variables['Build.DefinitionName'], 'staging'), eq(variables['Build.Reason'], 'PullRequest'))) }} # keep in sync with /eng/pipelines/common/variables.yml - dependOnEvaluatePaths: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community', 'runtime-extra-platforms')) }} + dependOnEvaluatePaths: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community', 'runtime-extra-platforms', 'runtime-wasm')) }} variables: # Disable component governance in our CI builds. These builds are not shipping nor diff --git a/eng/pipelines/runtime-extra-platforms-wasm.yml b/eng/pipelines/runtime-extra-platforms-wasm.yml index f1eaae46b9fe65..26152f51cf3a47 100644 --- a/eng/pipelines/runtime-extra-platforms-wasm.yml +++ b/eng/pipelines/runtime-extra-platforms-wasm.yml @@ -4,6 +4,7 @@ # /azp run runtime-wasm parameters: + isExtraPlatformsBuild: false isWasmOnlyBuild: false isRollingBuild: false @@ -15,15 +16,6 @@ jobs: # - rest are covered by runtime, and runtime-staging # - ${{ if eq(parameters.isRollingBuild, true) }}: - # EAT Library tests - only run on linux - - template: /eng/pipelines/common/templates/wasm-library-aot-tests.yml - parameters: - platforms: - - Browser_wasm - nameSuffix: _EAT - runAOT: false - alwaysRun: true - # AOT Library tests - template: /eng/pipelines/common/templates/wasm-library-aot-tests.yml parameters: @@ -70,15 +62,28 @@ jobs: # - ${{ if ne(parameters.isRollingBuild, true) }}: # Library tests + # these run on runtime also - template: /eng/pipelines/common/templates/wasm-library-tests.yml parameters: platforms: - Browser_wasm # Don't run for rolling builds, as this is covered - alwaysRun: ${{ parameters.isWasmOnlyBuild }} + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} scenarios: - normal - WasmTestOnBrowser + + # this only runs on the extra pipeline + - template: /eng/pipelines/common/templates/wasm-library-tests.yml + parameters: + platforms: + - Browser_wasm + nameSuffix: _NodeJs + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} + alwaysRun: ${{ parameters.isWasmOnlyBuild }} + scenarios: - WasmTestOnNodeJs # Library tests - Windows @@ -87,7 +92,8 @@ jobs: platforms: - Browser_wasm_win # Don't run for rolling builds, as this is covered - alwaysRun: ${{ parameters.isWasmOnlyBuild }} + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} scenarios: - WasmTestOnBrowser - WasmTestOnNodeJs @@ -100,8 +106,11 @@ jobs: #- Browser_wasm_win nameSuffix: _Threading extraBuildArgs: /p:WasmEnableThreads=true - # Don't run for rolling builds, as this is covered + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} + # Always run for runtime-wasm because tests are not run in runtime alwaysRun: ${{ parameters.isWasmOnlyBuild }} + # NOTE - Since threading is experimental, we don't want to block mainline work shouldContinueOnError: true scenarios: @@ -117,8 +126,11 @@ jobs: #- Browser_wasm_win nameSuffix: _Threading_PerfTracing extraBuildArgs: /p:WasmEnablePerfTracing=true - # Don't run for rolling builds, as this is covered + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} + # Always run for runtime-wasm because tests are not run in runtime alwaysRun: ${{ parameters.isWasmOnlyBuild }} + # NOTE - Since threading is experimental, we don't want to block mainline work shouldContinueOnError: true scenarios: @@ -133,7 +145,8 @@ jobs: - Browser_wasm nameSuffix: _EAT runAOT: false - alwaysRun: ${{ parameters.isWasmOnlyBuild }} + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} # AOT Library tests - template: /eng/pipelines/common/templates/wasm-library-aot-tests.yml @@ -143,6 +156,8 @@ jobs: - Browser_wasm_win nameSuffix: _AOT runAOT: true + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} alwaysRun: ${{ parameters.isWasmOnlyBuild }} # High resource AOT Library tests @@ -155,6 +170,8 @@ jobs: extraBuildArgs: /p:TestAssemblies=false /p:RunHighAOTResourceRequiringTestsOnly=true buildAOTOnHelix: false runAOT: true + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} alwaysRun: ${{ parameters.isWasmOnlyBuild }} # Wasm.Build.Tests @@ -163,7 +180,8 @@ jobs: platforms: - Browser_wasm - Browser_wasm_win - alwaysRun: ${{ parameters.isWasmOnlyBuild }} + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} # Debugger tests - template: /eng/pipelines/common/templates/wasm-debugger-tests.yml @@ -171,19 +189,23 @@ jobs: platforms: - Browser_wasm - Browser_wasm_win - alwaysRun: ${{ parameters.isWasmOnlyBuild }} + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} - template: /eng/pipelines/common/templates/wasm-runtime-tests.yml parameters: platforms: - Browser_wasm - alwaysRun: ${{ parameters.isWasmOnlyBuild }} + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} - template: /eng/pipelines/common/templates/wasm-debugger-tests.yml parameters: platforms: - Browser_wasm_firefox browser: firefox + isExtraPlatformsBuild: ${{ parameters.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} alwaysRun: ${{ parameters.isWasmOnlyBuild }} # ff tests are unstable currently shouldContinueOnError: true diff --git a/eng/pipelines/runtime-extra-platforms.yml b/eng/pipelines/runtime-extra-platforms.yml index 02591d91b6b0e3..174d14cd51bae1 100644 --- a/eng/pipelines/runtime-extra-platforms.yml +++ b/eng/pipelines/runtime-extra-platforms.yml @@ -34,11 +34,13 @@ jobs: - ${{ if eq(variables.dependOnEvaluatePaths, true) }}: - template: /eng/pipelines/common/evaluate-default-paths.yml -# include this unconditionally, because it has per job conditions -- template: /eng/pipelines/runtime-extra-platforms-wasm.yml - parameters: - isWasmOnlyBuild: ${{ variables.isWasmOnlyBuild }} - isRollingBuild: ${{ variables.isRollingBuild }} +# Add wasm jobs only for rolling builds +- ${{ if eq(variables.isRollingBuild, true) }}: + - template: /eng/pipelines/runtime-extra-platforms-wasm.yml + parameters: + isExtraPlatformsBuild: ${{ variables.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ variables.isWasmOnlyBuild }} + isRollingBuild: ${{ variables.isRollingBuild }} # Any jobs that are not specific to any platform - ${{ if eq(variables.isNotSpecificPlatformOnlyBuild, true) }}: diff --git a/eng/pipelines/runtime-wasm.yml b/eng/pipelines/runtime-wasm.yml index 62de930be9d1f9..55f678c144522f 100644 --- a/eng/pipelines/runtime-wasm.yml +++ b/eng/pipelines/runtime-wasm.yml @@ -12,10 +12,10 @@ jobs: # # Evaluate paths # -- ${{ if eq(variables.dependOnEvaluatePaths, true) }}: - - template: /eng/pipelines/common/evaluate-default-paths.yml +- template: /eng/pipelines/common/evaluate-default-paths.yml - template: /eng/pipelines/runtime-extra-platforms-wasm.yml parameters: + isExtraPlatformsBuild: ${{ variables.isExtraPlatformsBuild }} isWasmOnlyBuild: ${{ variables.isWasmOnlyBuild }} isRollingBuild: ${{ variables.isRollingBuild }} From 68d55a633d0d4f5d80b029f8fa6872d676950e5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Wed, 31 Aug 2022 17:28:06 +0900 Subject: [PATCH 047/107] Do not R2R NativeAOT compiler on ARM64 machines (#74856) --- src/coreclr/tools/aot/ILCompiler/ILCompiler.csproj | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/coreclr/tools/aot/ILCompiler/ILCompiler.csproj b/src/coreclr/tools/aot/ILCompiler/ILCompiler.csproj index 0f53c52bca6bb7..263d814a99de62 100644 --- a/src/coreclr/tools/aot/ILCompiler/ILCompiler.csproj +++ b/src/coreclr/tools/aot/ILCompiler/ILCompiler.csproj @@ -11,7 +11,8 @@ $(RuntimeBinDir)ilc-published/ true - true + + true true From 62948580b4d3547473cb567bff6cc61308136d81 Mon Sep 17 00:00:00 2001 From: Krzysztof Wicher Date: Wed, 31 Aug 2022 10:31:18 +0200 Subject: [PATCH 048/107] Disable nullability warnings in JSON source generator (#74801) * Disable nullability warnings in JSON source generator * Add testcase for #61734 --- .../gen/JsonSourceGenerator.Emitter.cs | 4 +- .../JsonSerializerContextTests.cs | 40 +++++++++++++++++++ ...m.Text.Json.SourceGeneration.Tests.targets | 4 ++ .../TestClasses.cs | 12 ++++++ 4 files changed, 59 insertions(+), 1 deletion(-) diff --git a/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs b/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs index d9698c71ce3f00..68b0bf76bf9757 100644 --- a/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs +++ b/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Emitter.cs @@ -152,7 +152,9 @@ private void AddSource(string fileName, string source, bool isRootContextDef = f bool isInGlobalNamespace = @namespace == JsonConstants.GlobalNamespaceValue; StringBuilder sb = new(@"// -#nullable enable + +#nullable enable annotations +#nullable disable warnings // Suppress warnings about [Obsolete] member usage in generated code. #pragma warning disable CS0618"); diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSerializerContextTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSerializerContextTests.cs index 7e97443adfabc4..b89fcf34ed5ce0 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSerializerContextTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSerializerContextTests.cs @@ -380,6 +380,37 @@ public static void SupportsGenericParameterWithCustomConverterFactory() Assert.Equal(@"[""Cee""]", json); } + // Regression test for https://github.com/dotnet/runtime/issues/74652 + [Fact] + public static void ClassWithStringValuesRoundtrips() + { + JsonSerializerOptions options = ClassWithStringValuesContext.Default.Options; + + ClassWithStringValues obj = new() + { + StringValuesProperty = new(new[] { "abc", "def" }) + }; + + string json = JsonSerializer.Serialize(obj, options); + Assert.Equal("""{"StringValuesProperty":["abc","def"]}""", json); + } + + // Regression test for https://github.com/dotnet/runtime/issues/61734 + [Fact] + public static void ClassWithDictionaryPropertyRoundtrips() + { + JsonSerializerOptions options = ClassWithDictionaryPropertyContext.Default.Options; + + ClassWithDictionaryProperty obj = new(new Dictionary() + { + ["foo"] = "bar", + ["test"] = "baz", + }); + + string json = JsonSerializer.Serialize(obj, options); + Assert.Equal("""{"DictionaryProperty":{"foo":"bar","test":"baz"}}""", json); + } + [JsonConverter(typeof(JsonStringEnumConverter))] public enum TestEnum { @@ -394,7 +425,16 @@ internal partial class GenericParameterWithCustomConverterFactoryContext : JsonS [JsonSerializable(typeof(ClassWithPocoListDictionaryAndNullable))] internal partial class ClassWithPocoListDictionaryAndNullablePropertyContext : JsonSerializerContext { + } + [JsonSerializable(typeof(ClassWithStringValues))] + internal partial class ClassWithStringValuesContext : JsonSerializerContext + { + } + + [JsonSerializable(typeof(ClassWithDictionaryProperty))] + internal partial class ClassWithDictionaryPropertyContext : JsonSerializerContext + { } internal class ClassWithPocoListDictionaryAndNullable diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/System.Text.Json.SourceGeneration.Tests.targets b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/System.Text.Json.SourceGeneration.Tests.targets index a759efb7739842..1b9e0d17b199e8 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/System.Text.Json.SourceGeneration.Tests.targets +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/System.Text.Json.SourceGeneration.Tests.targets @@ -112,6 +112,10 @@ + + + + diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/TestClasses.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/TestClasses.cs index 4a52c8ce8179b0..eb4da1df79f20e 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/TestClasses.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/TestClasses.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Text.Json.Serialization; +using Microsoft.Extensions.Primitives; namespace System.Text.Json.SourceGeneration.Tests.RepeatedTypes { @@ -275,4 +276,15 @@ public class PublicTestClass { internal class InternalNestedClass { } } + + public sealed class ClassWithStringValues + { + public StringValues StringValuesProperty { get; set; } + } + + public class ClassWithDictionaryProperty + { + public ClassWithDictionaryProperty(Dictionary property) => DictionaryProperty = property; + public Dictionary DictionaryProperty { get; } + } } From 7e22e4166f20791b5b475501f8cf8365f739b311 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20K=C3=B6plinger?= Date: Wed, 31 Aug 2022 11:13:52 +0200 Subject: [PATCH 049/107] Extensions.Logging.Console: Only check for Android/Apple mobile on netcoreapp configs (#74798) We can keep the previous behavior before https://github.com/dotnet/runtime/pull/74496 on non-netcoreapp configs since they only apply to legacy Xamarin.iOS/Android. That allows us to use the more efficient `OperatingSystem.Is*()` APIs. Co-authored-by: Jan Kotas --- .../src/SimpleConsoleFormatter.cs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/SimpleConsoleFormatter.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/SimpleConsoleFormatter.cs index 2bdfef2b5153ad..d2c189d1767d9d 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/SimpleConsoleFormatter.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/SimpleConsoleFormatter.cs @@ -15,10 +15,13 @@ internal sealed class SimpleConsoleFormatter : ConsoleFormatter, IDisposable private const string LoglevelPadding = ": "; private static readonly string _messagePadding = new string(' ', GetLogLevelString(LogLevel.Information).Length + LoglevelPadding.Length); private static readonly string _newLineWithMessagePadding = Environment.NewLine + _messagePadding; - private static readonly bool _isAndroidOrAppleMobile = RuntimeInformation.IsOSPlatform(OSPlatform.Create("ANDROID")) - || RuntimeInformation.IsOSPlatform(OSPlatform.Create("TVOS")) - || RuntimeInformation.IsOSPlatform(OSPlatform.Create("IOS")) - || RuntimeInformation.IsOSPlatform(OSPlatform.Create("MACCATALYST")); +#if NETCOREAPP + private static bool IsAndroidOrAppleMobile => OperatingSystem.IsAndroid() || + OperatingSystem.IsTvOS() || + OperatingSystem.IsIOS(); // returns true on MacCatalyst +#else + private static bool IsAndroidOrAppleMobile => false; +#endif private IDisposable? _optionsReloadToken; public SimpleConsoleFormatter(IOptionsMonitor options) @@ -165,7 +168,7 @@ private ConsoleColors GetLogLevelConsoleColors(LogLevel logLevel) // We shouldn't be outputting color codes for Android/Apple mobile platforms, // they have no shell (adb shell is not meant for running apps) and all the output gets redirected to some log file. bool disableColors = (FormatterOptions.ColorBehavior == LoggerColorBehavior.Disabled) || - (FormatterOptions.ColorBehavior == LoggerColorBehavior.Default && (!ConsoleUtils.EmitAnsiColorCodes || _isAndroidOrAppleMobile)); + (FormatterOptions.ColorBehavior == LoggerColorBehavior.Default && (!ConsoleUtils.EmitAnsiColorCodes || IsAndroidOrAppleMobile)); if (disableColors) { return new ConsoleColors(null, null); From 4c927373d91279096f82a19a0ff6e91c37e570a3 Mon Sep 17 00:00:00 2001 From: Radek Doulik Date: Wed, 31 Aug 2022 11:29:05 +0200 Subject: [PATCH 050/107] [wasm] shorten JSInterop bench detection phase (#74802) Some of the JSInterop measurements have long steps, so tune down the detection phase steps to avoid overly long detection, which resulted in 3x bench run times in some cases on arm64/linux SBC. --- src/mono/sample/wasm/browser-bench/JSInterop.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/mono/sample/wasm/browser-bench/JSInterop.cs b/src/mono/sample/wasm/browser-bench/JSInterop.cs index 4044410f6a44e7..bc47e44704cc5f 100644 --- a/src/mono/sample/wasm/browser-bench/JSInterop.cs +++ b/src/mono/sample/wasm/browser-bench/JSInterop.cs @@ -39,7 +39,7 @@ public JSInteropTask() public class LegacyExportIntMeasurement : BenchTask.Measurement { - public override int InitialSamples => 10; + public override int InitialSamples => 3; public override string Name => "LegacyExportInt"; public override void RunStep() { @@ -59,7 +59,7 @@ public override void RunStep() public class LegacyExportStringMeasurement : BenchTask.Measurement { - public override int InitialSamples => 10; + public override int InitialSamples => 3; public override string Name => "LegacyExportString"; public override void RunStep() { @@ -69,7 +69,7 @@ public override void RunStep() public class JSExportStringMeasurement : BenchTask.Measurement { - public override int InitialSamples => 10; + public override int InitialSamples => 3; public override string Name => "JSExportString"; public override void RunStep() { @@ -92,7 +92,7 @@ public override void RunStep() public class JSImportStringMeasurement : BenchTask.Measurement { - public override int InitialSamples => 10; + public override int InitialSamples => 3; public override string Name => "JSImportString"; public override void RunStep() { @@ -106,7 +106,7 @@ public override void RunStep() public class JSImportManyArgsMeasurement : BenchTask.Measurement { private DateTime start = DateTime.Now; - public override int InitialSamples => 10; + public override int InitialSamples => 3; public override string Name => "JSImportManyArgs"; public override void RunStep() { @@ -120,7 +120,7 @@ public override void RunStep() public class JSImportTaskMeasurement : BenchTask.Measurement { public override bool HasRunStepAsync => true; - public override int InitialSamples => 10; + public override int InitialSamples => 1; public override string Name => "JSImportTask"; public override async Task RunStepAsync() { @@ -137,7 +137,7 @@ public override async Task RunStepAsync() public class JSImportTaskFailMeasurement : BenchTask.Measurement { public override bool HasRunStepAsync => true; - public override int InitialSamples => 10; + public override int InitialSamples => 1; public override string Name => "JSImportTaskFail"; public override async Task RunStepAsync() { @@ -160,7 +160,7 @@ public override async Task RunStepAsync() public class JSImportFailMeasurement : BenchTask.Measurement { - public override int InitialSamples => 10; + public override int InitialSamples => 1; public override string Name => "JSImportFail"; public override void RunStep() { From 104fe14a7e0d9f027b37c23e5e3c58621c711353 Mon Sep 17 00:00:00 2001 From: Radek Doulik Date: Wed, 31 Aug 2022 12:21:55 +0200 Subject: [PATCH 051/107] Make System.Transactions.Local trimmable (#74828) On other target platforms than windows. This fixes https://github.com/dotnet/runtime/issues/74506 The reason to make it non-trimmable is that it uses COM interop on windows. So we can make it trimmable again on other target platforms. https://github.com/dotnet/runtime/issues/74506#issuecomment-1231917923 --- .../src/System.Transactions.Local.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libraries/System.Transactions.Local/src/System.Transactions.Local.csproj b/src/libraries/System.Transactions.Local/src/System.Transactions.Local.csproj index 86a68905ab6ed6..034f32afcf5070 100644 --- a/src/libraries/System.Transactions.Local/src/System.Transactions.Local.csproj +++ b/src/libraries/System.Transactions.Local/src/System.Transactions.Local.csproj @@ -5,7 +5,7 @@ $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent) CA1805;IDE0059;CS1591 $([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) - false + false From 9ac6c6d816eab9ca2dc84e1a9a6e65fc2dbde4cd Mon Sep 17 00:00:00 2001 From: Peter Sollich Date: Wed, 31 Aug 2022 16:10:44 +0200 Subject: [PATCH 052/107] Fix issue #74741 - assert failure during weak pointer scanning. (#74810) The problem here is that during GCScan::GcWeakPtrScan, we call GCHeap::IsPromoted so we can zero out object pointers to objects that weren't marked. At the same time, one thread may do the same for the sync block table. When the first kind of threads validate the object, they also validate the sync block entry that may have already been zeroed - this causes an assert failure. I don't think there is any bad effect apart from the assert failure though. The fix is to simply call Object::Validate with a bVerifySyncBlock of FALSE if the object hasn't been marked. --- src/coreclr/gc/gc.cpp | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/src/coreclr/gc/gc.cpp b/src/coreclr/gc/gc.cpp index 702f82ab386870..207a62355dc738 100644 --- a/src/coreclr/gc/gc.cpp +++ b/src/coreclr/gc/gc.cpp @@ -4473,8 +4473,12 @@ class CObjectHeader : public Object return ((ArrayBase *)this)->GetNumComponents(); } - void Validate(BOOL bDeep=TRUE) + void Validate(BOOL bDeep=TRUE, BOOL bVerifyNextHeader = FALSE, BOOL bVerifySyncBlock = FALSE) { + // declaration of extra parameters just so the call site would need no #ifdefs + UNREFERENCED_PARAMETER(bVerifyNextHeader); + UNREFERENCED_PARAMETER(bVerifySyncBlock); + MethodTable * pMT = GetMethodTable(); _ASSERTE(pMT->SanityCheck()); @@ -45145,15 +45149,10 @@ HRESULT GCHeap::Initialize() // GC callback functions bool GCHeap::IsPromoted(Object* object) { -#ifdef _DEBUG - if (object) - { - ((CObjectHeader*)object)->Validate(); - } -#endif //_DEBUG - uint8_t* o = (uint8_t*)object; + bool is_marked; + if (gc_heap::settings.condemned_generation == max_generation) { #ifdef MULTIPLE_HEAPS @@ -45165,27 +45164,35 @@ bool GCHeap::IsPromoted(Object* object) #ifdef BACKGROUND_GC if (gc_heap::settings.concurrent) { - bool is_marked = (!((o < hp->background_saved_highest_address) && (o >= hp->background_saved_lowest_address))|| + is_marked = (!((o < hp->background_saved_highest_address) && (o >= hp->background_saved_lowest_address))|| hp->background_marked (o)); - return is_marked; } else #endif //BACKGROUND_GC { - return (!((o < hp->highest_address) && (o >= hp->lowest_address)) - || hp->is_mark_set (o)); + is_marked = (!((o < hp->highest_address) && (o >= hp->lowest_address)) + || hp->is_mark_set (o)); } } else { #ifdef USE_REGIONS - return (gc_heap::is_in_gc_range (o) ? (gc_heap::is_in_condemned_gc (o) ? gc_heap::is_mark_set (o) : true) : true); + is_marked = (gc_heap::is_in_gc_range (o) ? (gc_heap::is_in_condemned_gc (o) ? gc_heap::is_mark_set (o) : true) : true); #else gc_heap* hp = gc_heap::heap_of (o); - return (!((o < hp->gc_high) && (o >= hp->gc_low)) - || hp->is_mark_set (o)); + is_marked = (!((o < hp->gc_high) && (o >= hp->gc_low)) + || hp->is_mark_set (o)); #endif //USE_REGIONS } + +#ifdef _DEBUG + if (o) + { + ((CObjectHeader*)o)->Validate(TRUE, TRUE, is_marked); + } +#endif //_DEBUG + + return is_marked; } size_t GCHeap::GetPromotedBytes(int heap_index) From 9e8d261ade2ee35cb679845af229d60c5c429304 Mon Sep 17 00:00:00 2001 From: Johan Lorensson Date: Wed, 31 Aug 2022 16:18:45 +0200 Subject: [PATCH 053/107] Fix OP_CHECK_THIS to read 1 byte instead of 4/8 on x86/x64/LLVM. (#74638) Current implementation of OP_CHECK_THIS on x86/x64 and LLVM does a memory read of at least 4 bytes. This creates an issue when the target is a managed pointer, since that could point to the interior of a type, meaning it can read pass the allocated memory causing a crash. Fix change the size of the read to one byte since the only reason doing the read is to validate that the reference, managed pointer is not NULL. Reading only one byte is also inline with how it is implemented on arm/arm64, and it will reduce potential unaligned reads on x86/x64. Full fix for, https://github.com/dotnet/runtime/issues/74179. --- src/mono/mono/arch/amd64/amd64-codegen.h | 1 + src/mono/mono/arch/x86/x86-codegen.h | 7 +++++++ src/mono/mono/mini/mini-amd64.c | 2 +- src/mono/mono/mini/mini-llvm.c | 2 +- src/mono/mono/mini/mini-x86.c | 7 ++----- 5 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/mono/mono/arch/amd64/amd64-codegen.h b/src/mono/mono/arch/amd64/amd64-codegen.h index ccd82d1ac172d8..9ac73b9853c466 100644 --- a/src/mono/mono/arch/amd64/amd64-codegen.h +++ b/src/mono/mono/arch/amd64/amd64-codegen.h @@ -1206,6 +1206,7 @@ typedef union { #define amd64_alu_membase8_imm_size(inst,opc,basereg,disp,imm,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),0,0,(basereg)); x86_alu_membase8_imm((inst),(opc),((basereg)&0x7),(disp),(imm)); amd64_codegen_post(inst); } while (0) #define amd64_alu_mem_reg_size(inst,opc,mem,reg,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),0,0,(reg)); x86_alu_mem_reg((inst),(opc),(mem),((reg)&0x7)); amd64_codegen_post(inst); } while (0) #define amd64_alu_membase_reg_size(inst,opc,basereg,disp,reg,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_alu_membase_reg((inst),(opc),((basereg)&0x7),(disp),((reg)&0x7)); amd64_codegen_post(inst); } while (0) +#define amd64_alu_membase8_reg_size(inst,opc,basereg,disp,reg,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),(reg),0,(basereg)); x86_alu_membase8_reg((inst),(opc),((basereg)&0x7),(disp),((reg)&0x7)); amd64_codegen_post(inst); } while (0) //#define amd64_alu_reg_reg_size(inst,opc,dreg,reg,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_alu_reg_reg((inst),(opc),((dreg)&0x7),((reg)&0x7)); amd64_codegen_post(inst); } while (0) #define amd64_alu_reg8_reg8_size(inst,opc,dreg,reg,is_dreg_h,is_reg_h,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),(dreg),0,(reg)); x86_alu_reg8_reg8((inst),(opc),((dreg)&0x7),((reg)&0x7),(is_dreg_h),(is_reg_h)); amd64_codegen_post(inst); } while (0) #define amd64_alu_reg_mem_size(inst,opc,reg,mem,size) do { amd64_codegen_pre(inst); amd64_emit_rex ((inst),(size),0,0,(reg)); x86_alu_reg_mem((inst),(opc),((reg)&0x7),(mem)); amd64_codegen_post(inst); } while (0) diff --git a/src/mono/mono/arch/x86/x86-codegen.h b/src/mono/mono/arch/x86/x86-codegen.h index 74f96f81af4077..aca2b659ca058b 100644 --- a/src/mono/mono/arch/x86/x86-codegen.h +++ b/src/mono/mono/arch/x86/x86-codegen.h @@ -682,6 +682,13 @@ mono_x86_patch_inline (guchar* code, gpointer target) x86_membase_emit ((inst), (reg), (basereg), (disp)); \ } while (0) +#define x86_alu_membase8_reg(inst,opc,basereg,disp,reg) \ + do { \ + x86_codegen_pre(&(inst), 1 + kMaxMembaseEmitPadding); \ + x86_byte (inst, (((unsigned char)(opc)) << 3)); \ + x86_membase_emit ((inst), (reg), (basereg), (disp)); \ + } while (0) + #define x86_alu_reg_reg(inst,opc,dreg,reg) \ do { \ x86_codegen_pre(&(inst), 2); \ diff --git a/src/mono/mono/mini/mini-amd64.c b/src/mono/mono/mini/mini-amd64.c index 3f52a94732440d..bc4eedd8f86c5e 100644 --- a/src/mono/mono/mini/mini-amd64.c +++ b/src/mono/mono/mini/mini-amd64.c @@ -5511,7 +5511,7 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb) } case OP_CHECK_THIS: /* ensure ins->sreg1 is not NULL */ - amd64_alu_membase_imm_size (code, X86_CMP, ins->sreg1, 0, 0, 4); + amd64_alu_membase8_reg_size (code, X86_CMP, ins->sreg1, 0, ins->sreg1, 1); break; case OP_ARGLIST: { amd64_lea_membase (code, AMD64_R11, cfg->frame_reg, cfg->sig_cookie); diff --git a/src/mono/mono/mini/mini-llvm.c b/src/mono/mono/mini/mini-llvm.c index b43892dcb1de47..171ef8c51a980a 100644 --- a/src/mono/mono/mini/mini-llvm.c +++ b/src/mono/mono/mini/mini-llvm.c @@ -6856,7 +6856,7 @@ MONO_RESTORE_WARNING } case OP_CHECK_THIS: - LLVMBuildLoad2 (builder, IntPtrType (), convert (ctx, lhs, pointer_type (IntPtrType ())), ""); + LLVMBuildLoad2 (builder, LLVMInt8Type (), convert (ctx, lhs, pointer_type (LLVMInt8Type ())), ""); break; case OP_OUTARG_VTRETADDR: break; diff --git a/src/mono/mono/mini/mini-x86.c b/src/mono/mono/mini/mini-x86.c index 6680b08f72d287..1006eabf989e54 100644 --- a/src/mono/mono/mini/mini-x86.c +++ b/src/mono/mono/mini/mini-x86.c @@ -3192,11 +3192,8 @@ mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb) break; } case OP_CHECK_THIS: - /* ensure ins->sreg1 is not NULL - * note that cmp DWORD PTR [eax], eax is one byte shorter than - * cmp DWORD PTR [eax], 0 - */ - x86_alu_membase_reg (code, X86_CMP, ins->sreg1, 0, ins->sreg1); + /* ensure ins->sreg1 is not NULL */ + x86_alu_membase8_reg (code, X86_CMP, ins->sreg1, 0, ins->sreg1); break; case OP_ARGLIST: { int hreg = ins->sreg1 == X86_EAX? X86_ECX: X86_EAX; From d6ce31b5cbc7e6c6bd1750721e37dac1c5cf80c0 Mon Sep 17 00:00:00 2001 From: David Pine Date: Wed, 31 Aug 2022 09:33:31 -0500 Subject: [PATCH 054/107] Update LifetimeTrackingHttpMessageHandler.cs (#74833) --- .../src/LifetimeTrackingHttpMessageHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libraries/Microsoft.Extensions.Http/src/LifetimeTrackingHttpMessageHandler.cs b/src/libraries/Microsoft.Extensions.Http/src/LifetimeTrackingHttpMessageHandler.cs index d7537ca82a607d..77be653ef4593c 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/LifetimeTrackingHttpMessageHandler.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/LifetimeTrackingHttpMessageHandler.cs @@ -5,7 +5,7 @@ namespace Microsoft.Extensions.Http { - // This a marker used to check if the underlying handler should be disposed. HttpClients + // This is a marker used to check if the underlying handler should be disposed. HttpClients // share a reference to an instance of this class, and when it goes out of scope the inner handler // is eligible to be disposed. internal sealed class LifetimeTrackingHttpMessageHandler : DelegatingHandler From d48dd6c90f8b59e9328279f512a2b4abda58b027 Mon Sep 17 00:00:00 2001 From: Pavel Savara Date: Wed, 31 Aug 2022 16:38:32 +0200 Subject: [PATCH 055/107] [wasm] trim System.Private.Uri.dll (#74826) change interop code so that ILLink would not protect Uri class --- .../JavaScript/Interop/LegacyExports.cs | 32 +++++++++++++++---- .../browser-advanced/ILLink.Descriptors.xml | 8 +++++ .../Wasm.Advanced.Sample.csproj | 3 ++ 3 files changed, 37 insertions(+), 6 deletions(-) create mode 100644 src/mono/sample/wasm/browser-advanced/ILLink.Descriptors.xml diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Interop/LegacyExports.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Interop/LegacyExports.cs index faf196db950d20..1b5b1f99366d7a 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Interop/LegacyExports.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Interop/LegacyExports.cs @@ -4,6 +4,7 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; +using System.Text; using System.Threading.Tasks; namespace System.Runtime.InteropServices.JavaScript @@ -210,15 +211,34 @@ public static void CreateDateTimeRef(double ticks, out object result) result = unixTime.DateTime; } + // we do this via reflection to allow linker to trim dependency on Uri class and it's assembly + // if the user code has methods with Uri signature, they probably also have the Uri constructor + // if they don't have it, they could configure ILLing to protect it after they enabled trimming + // We believe that this code path is probably not even used in the wild + // System.Private.Uri is ~80KB large assembly so it's worth trimming + private static Type? uriType; + [MethodImplAttribute(MethodImplOptions.NoInlining)] // https://github.com/dotnet/runtime/issues/71425 + [Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2077", Justification = "Done on purpose, see comment above.")] + [Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2057", Justification = "Done on purpose, see comment above.")] public static void CreateUriRef(string uri, out object? result) { - // we do this via reflection to allow linker to trim dependency on URI and it's assembly - // if the user code has methods with Uri signature, this should work too - // System.Private.Uri is large assembly so it's worth trimming - var uriType = Type.GetType("System.Uri, System.Private.Uri"); - if (uriType == null) throw new InvalidProgramException(); - result = Activator.CreateInstance(uriType, uri); + if (uriType == null) + { + // StringBuilder to confuse ILLink, which is too smart otherwise + StringBuilder sb = new StringBuilder("System.Uri, System.Private.Uri"); + uriType = Type.GetType(sb.ToString()); + } + // See: https://devblogs.microsoft.com/dotnet/customizing-trimming-in-net-core-5/ + if (uriType == null) throw new InvalidProgramException("The type System.Uri could not be found. Please consider to protect the class and it's constructor from trimming."); + try + { + result = Activator.CreateInstance(uriType, uri); + } + catch (MissingMethodException ex) + { + throw new MissingMethodException("Constructor on type 'System.Uri' not found. Please consider to protect it's constructor from trimming.", ex); + } } [MethodImplAttribute(MethodImplOptions.NoInlining)] // https://github.com/dotnet/runtime/issues/71425 diff --git a/src/mono/sample/wasm/browser-advanced/ILLink.Descriptors.xml b/src/mono/sample/wasm/browser-advanced/ILLink.Descriptors.xml new file mode 100644 index 00000000000000..665eae765f7332 --- /dev/null +++ b/src/mono/sample/wasm/browser-advanced/ILLink.Descriptors.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/mono/sample/wasm/browser-advanced/Wasm.Advanced.Sample.csproj b/src/mono/sample/wasm/browser-advanced/Wasm.Advanced.Sample.csproj index d8c4b204938efd..347294401f9a30 100644 --- a/src/mono/sample/wasm/browser-advanced/Wasm.Advanced.Sample.csproj +++ b/src/mono/sample/wasm/browser-advanced/Wasm.Advanced.Sample.csproj @@ -7,10 +7,13 @@ 1 true $(ExecXHarnessCmd) wasm test-browser --app=. --browser=Chrome $(XHarnessBrowserPathArg) --html-file=index.html --output-directory=$(XHarnessOutput) -- $(MSBuildProjectName).dll + true + true + <_SampleProject>Wasm.Advanced.Sample.csproj From b82f2545604e850deade7110a11a6204f5e09c89 Mon Sep 17 00:00:00 2001 From: Pavel Savara Date: Wed, 31 Aug 2022 17:08:03 +0200 Subject: [PATCH 056/107] appstart benchmark improvements (#74799) appstart benchmark improvements --- src/mono/sample/wasm/browser-advanced/index.html | 4 ++++ src/mono/sample/wasm/browser-advanced/main.js | 1 - src/mono/sample/wasm/browser-bench/AppStart.cs | 1 + src/mono/sample/wasm/browser-bench/appstart-frame.html | 8 ++++++-- src/mono/sample/wasm/browser-bench/frame-main.js | 4 ++-- src/mono/sample/wasm/browser-bench/index.html | 6 ++++++ src/mono/sample/wasm/browser/index.html | 4 ++++ src/mono/sample/wasm/simple-server/Program.cs | 2 ++ 8 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/mono/sample/wasm/browser-advanced/index.html b/src/mono/sample/wasm/browser-advanced/index.html index e107bead42a733..5fe0fc4f5cf9e3 100644 --- a/src/mono/sample/wasm/browser-advanced/index.html +++ b/src/mono/sample/wasm/browser-advanced/index.html @@ -9,6 +9,10 @@ + + + + diff --git a/src/mono/sample/wasm/browser-advanced/main.js b/src/mono/sample/wasm/browser-advanced/main.js index cc3a94bd786b33..b8e0778efcf07f 100644 --- a/src/mono/sample/wasm/browser-advanced/main.js +++ b/src/mono/sample/wasm/browser-advanced/main.js @@ -52,7 +52,6 @@ try { console.debug(`meaning: ${meaning}`); if (!exports.Sample.Test.IsPrime(meaning)) { document.getElementById("out").innerHTML = `${meaning} as computed on dotnet ver ${runtimeBuildInfo.productVersion}`; - console.debug(`ret: ${meaning}`); } let exit_code = await runMain(config.mainAssemblyName, []); diff --git a/src/mono/sample/wasm/browser-bench/AppStart.cs b/src/mono/sample/wasm/browser-bench/AppStart.cs index f2d263bd043b3f..1e047a8ba100af 100644 --- a/src/mono/sample/wasm/browser-bench/AppStart.cs +++ b/src/mono/sample/wasm/browser-bench/AppStart.cs @@ -11,6 +11,7 @@ namespace Sample { + // http://localhost:8000/?task=AppStart public partial class AppStartTask : BenchTask { public override string Name => "AppStart"; diff --git a/src/mono/sample/wasm/browser-bench/appstart-frame.html b/src/mono/sample/wasm/browser-bench/appstart-frame.html index 2c40ed1abd53bb..2760dc7ebe2cca 100644 --- a/src/mono/sample/wasm/browser-bench/appstart-frame.html +++ b/src/mono/sample/wasm/browser-bench/appstart-frame.html @@ -7,8 +7,12 @@ App task - - + + + + + + diff --git a/src/mono/sample/wasm/browser-bench/frame-main.js b/src/mono/sample/wasm/browser-bench/frame-main.js index 45fd825e15b1e4..667f5eec947d5e 100644 --- a/src/mono/sample/wasm/browser-bench/frame-main.js +++ b/src/mono/sample/wasm/browser-bench/frame-main.js @@ -31,9 +31,9 @@ try { } const runtime = await dotnet - .withElementOnExit() - .withExitCodeLogging() .withModuleConfig({ + printErr: () => undefined, + print: () => undefined, onConfigLoaded: (config) => { if (window.parent != window) { window.parent.resolveAppStartEvent("onConfigLoaded"); diff --git a/src/mono/sample/wasm/browser-bench/index.html b/src/mono/sample/wasm/browser-bench/index.html index d158954c830a38..4687b1ca80459c 100644 --- a/src/mono/sample/wasm/browser-bench/index.html +++ b/src/mono/sample/wasm/browser-bench/index.html @@ -8,6 +8,12 @@ + + + + + + diff --git a/src/mono/sample/wasm/browser/index.html b/src/mono/sample/wasm/browser/index.html index cee61db6f0b28a..ad5ca990d17169 100644 --- a/src/mono/sample/wasm/browser/index.html +++ b/src/mono/sample/wasm/browser/index.html @@ -9,6 +9,10 @@ + + + + diff --git a/src/mono/sample/wasm/simple-server/Program.cs b/src/mono/sample/wasm/simple-server/Program.cs index 70ef1e573093f1..972bad3016440d 100644 --- a/src/mono/sample/wasm/simple-server/Program.cs +++ b/src/mono/sample/wasm/simple-server/Program.cs @@ -156,6 +156,8 @@ private async void ServeAsync(HttpListenerContext context) string? contentType = null; if (path.EndsWith(".wasm")) contentType = "application/wasm"; + if (path.EndsWith(".json")) + contentType = "application/json"; if (path.EndsWith(".js") || path.EndsWith(".mjs") || path.EndsWith(".cjs")) contentType = "text/javascript"; From 51191575ccced7759ab2b82c7348a488f56d6f52 Mon Sep 17 00:00:00 2001 From: Neale Ferguson Date: Thu, 1 Sep 2022 03:01:31 +1000 Subject: [PATCH 057/107] [mono] Determine any memory/CPU limitations from sysfs cgroup (#74237) Add capability to interrogate cgroup limitations when determining CP and memory limits This code has been adapted from coreCLR. It has been modified from C++ but uses the same naming conventions in the event of a unified mechanism that can be shared between both runtimes being developed. The code has been tested on Ubuntu 20.04 and CentOS 7 with cgroupv1 and cgroupv2. This code is required in the event of running runtime in a container as the current limitations being discovered by the mono runtime are purely for the machine and not in a container which may have lower quotas. --- src/mono/CMakeLists.txt | 1 + src/mono/cmake/config.h.in | 3 + src/mono/mono/metadata/icall.c | 2 +- src/mono/mono/sgen/sgen-marksweep.c | 4 +- src/mono/mono/sgen/sgen-simple-nursery.c | 2 +- src/mono/mono/utils/CMakeLists.txt | 1 + src/mono/mono/utils/memfuncs.c | 60 +- src/mono/mono/utils/memfuncs.h | 5 + src/mono/mono/utils/mono-cgroup.c | 972 +++++++++++++++++++++++ src/mono/mono/utils/mono-proclib.c | 42 + src/mono/mono/utils/mono-proclib.h | 7 + 11 files changed, 1085 insertions(+), 14 deletions(-) create mode 100644 src/mono/mono/utils/mono-cgroup.c diff --git a/src/mono/CMakeLists.txt b/src/mono/CMakeLists.txt index 1629fe4dbcec93..6dbf542183bcdc 100644 --- a/src/mono/CMakeLists.txt +++ b/src/mono/CMakeLists.txt @@ -215,6 +215,7 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") set(HOST_LINUX 1) add_definitions(-D_GNU_SOURCE -D_REENTRANT) add_definitions(-D_THREAD_SAFE) + set(HAVE_CGROUP_SUPPORT 1) # Enable the "full RELRO" options (RELRO & BIND_NOW) at link time add_link_options(-Wl,-z,relro) add_link_options(-Wl,-z,now) diff --git a/src/mono/cmake/config.h.in b/src/mono/cmake/config.h.in index 81ff6697c2a272..4ac722c9d928c1 100644 --- a/src/mono/cmake/config.h.in +++ b/src/mono/cmake/config.h.in @@ -888,6 +888,9 @@ /* Define to 1 if you have /usr/include/malloc.h. */ #cmakedefine HAVE_USR_INCLUDE_MALLOC_H 1 +/* Define to 1 if you have linux cgroups */ +#cmakedefine HAVE_CGROUP_SUPPORT 1 + /* The architecture this is running on */ #define MONO_ARCHITECTURE @MONO_ARCHITECTURE@ diff --git a/src/mono/mono/metadata/icall.c b/src/mono/mono/metadata/icall.c index df14926eb572f1..c8b16f7f400a68 100644 --- a/src/mono/mono/metadata/icall.c +++ b/src/mono/mono/metadata/icall.c @@ -7189,7 +7189,7 @@ ves_icall_System_Threading_Thread_YieldInternal (void) gint32 ves_icall_System_Environment_get_ProcessorCount (void) { - return mono_cpu_count (); + return mono_cpu_limit (); } // Generate wrappers. diff --git a/src/mono/mono/sgen/sgen-marksweep.c b/src/mono/mono/sgen/sgen-marksweep.c index 49840611b5b54d..be5da41863dfc2 100644 --- a/src/mono/mono/sgen/sgen-marksweep.c +++ b/src/mono/mono/sgen/sgen-marksweep.c @@ -2861,7 +2861,7 @@ sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurr sgen_register_fixed_internal_mem_type (INTERNAL_MEM_MS_BLOCK_INFO, SIZEOF_MS_BLOCK_INFO); - if (mono_cpu_count () <= 1) + if (mono_cpu_limit () <= 1) is_parallel = FALSE; num_block_obj_sizes = ms_calculate_block_obj_sizes (MS_BLOCK_OBJ_SIZE_FACTOR, NULL); @@ -3027,7 +3027,7 @@ sgen_marksweep_init_internal (SgenMajorCollector *collector, gboolean is_concurr #ifndef DISABLE_SGEN_MAJOR_MARKSWEEP_CONC if (is_concurrent && is_parallel) - sgen_workers_create_context (GENERATION_OLD, mono_cpu_count ()); + sgen_workers_create_context (GENERATION_OLD, mono_cpu_limit ()); else if (is_concurrent) sgen_workers_create_context (GENERATION_OLD, 1); diff --git a/src/mono/mono/sgen/sgen-simple-nursery.c b/src/mono/mono/sgen/sgen-simple-nursery.c index 18a771d0abafce..8a63d8f66942e5 100644 --- a/src/mono/mono/sgen/sgen-simple-nursery.c +++ b/src/mono/mono/sgen/sgen-simple-nursery.c @@ -148,7 +148,7 @@ fill_parallel_with_concurrent_major_ops (SgenObjectOperations *ops) void sgen_simple_nursery_init (SgenMinorCollector *collector, gboolean parallel) { - if (mono_cpu_count () <= 1) + if (mono_cpu_limit () <= 1) parallel = FALSE; #ifdef DISABLE_SGEN_MAJOR_MARKSWEEP_CONC diff --git a/src/mono/mono/utils/CMakeLists.txt b/src/mono/mono/utils/CMakeLists.txt index 7ceb82e8eed230..4d552b6e033dd9 100644 --- a/src/mono/mono/utils/CMakeLists.txt +++ b/src/mono/mono/utils/CMakeLists.txt @@ -32,6 +32,7 @@ set(utils_common_sources mono-sha1.c mono-logger.c mono-logger-internals.h + mono-cgroup.c mono-codeman.c mono-counters.c mono-compiler.h diff --git a/src/mono/mono/utils/memfuncs.c b/src/mono/mono/utils/memfuncs.c index 4fc78079626abc..885c21ae3d8fb9 100644 --- a/src/mono/mono/utils/memfuncs.c +++ b/src/mono/mono/utils/memfuncs.c @@ -27,6 +27,7 @@ #include #include #include +#include #if defined (__APPLE__) #include @@ -69,6 +70,7 @@ __d [__i] = NULL; \ } while (0) +#define MINMEMSZ 209715200 /* Minimum restricted memory size */ /** * mono_gc_bzero_aligned: @@ -273,24 +275,59 @@ mono_determine_physical_ram_size (void) return (guint64)value; #elif defined (HAVE_SYSCONF) - gint64 page_size = -1, num_pages = -1; + guint64 page_size = 0, num_pages = 0, memsize; /* sysconf works on most *NIX operating systems, if your system doesn't have it or if it * reports invalid values, please add your OS specific code below. */ #ifdef _SC_PAGESIZE - page_size = (gint64)sysconf (_SC_PAGESIZE); + page_size = (guint64)sysconf (_SC_PAGESIZE); #endif #ifdef _SC_PHYS_PAGES - num_pages = (gint64)sysconf (_SC_PHYS_PAGES); + num_pages = (guint64)sysconf (_SC_PHYS_PAGES); #endif - if (page_size == -1 || num_pages == -1) { + if (!page_size || !num_pages) { g_warning ("Your operating system's sysconf (3) function doesn't correctly report physical memory size!"); return _DEFAULT_MEM_SIZE; } - return (guint64)page_size * (guint64)num_pages; +#if defined(_SC_AVPHYS_PAGES) + memsize = sysconf(_SC_AVPHYS_PAGES) * page_size; +#else + memsize = page_size * num_pages; /* Calculate physical memory size */ +#endif + +#if HAVE_CGROUP_SUPPORT + gint64 restricted_limit = mono_get_restricted_memory_limit(); /* Check for any cgroup limit */ + if (restricted_limit != 0) { + gchar *heapHardLimit = getenv("DOTNET_GCHeapHardLimit"); /* See if user has set a limit */ + if (heapHardLimit == NULL) + heapHardLimit = getenv("COMPlus_GCHeapHardLimit"); /* Check old envvar name */ + errno = 0; + if (heapHardLimit != NULL) { + guint64 gcLimit = strtoull(heapHardLimit, NULL, 16); + if ((errno == 0) && (gcLimit != 0)) + restricted_limit = (restricted_limit < gcLimit ? restricted_limit : (gint64) gcLimit); + } else { + gchar *heapHardLimitPct = getenv("DOTNET_GCHeapHardLimitPercent"); /* User % limit? */ + if (heapHardLimitPct == NULL) + heapHardLimitPct = getenv("COMPlus_GCHeapHardLimitPercent"); /* Check old envvar name */ + if (heapHardLimitPct != NULL) { + int gcLimit = strtoll(heapHardLimitPct, NULL, 16); + if ((gcLimit > 0) && (gcLimit <= 100)) + restricted_limit = (gcLimit * restricted_limit) / 100; + else + restricted_limit = (3 * restricted_limit) / 4; /* Use 75% limit of container */ + } else { + restricted_limit = (3 * restricted_limit) / 4; /* Use 75% limit of container */ + } + } + return (restricted_limit < MINMEMSZ ? MINMEMSZ : /* Use at least 20MB */ + (restricted_limit < memsize ? restricted_limit : memsize)); + } +#endif + return memsize; #else return _DEFAULT_MEM_SIZE; #endif @@ -343,25 +380,28 @@ mono_determine_physical_ram_available_size (void) host_page_size (host, &page_size); return (guint64) vmstat.free_count * page_size; +#elif HAVE_CGROUP_SUPPORT + return (mono_get_memory_avail()); + #elif defined (HAVE_SYSCONF) - gint64 page_size = -1, num_pages = -1; + guint64 page_size = 0, num_pages = 0; /* sysconf works on most *NIX operating systems, if your system doesn't have it or if it * reports invalid values, please add your OS specific code below. */ #ifdef _SC_PAGESIZE - page_size = (gint64)sysconf (_SC_PAGESIZE); + page_size = (guint64)sysconf (_SC_PAGESIZE); #endif #ifdef _SC_AVPHYS_PAGES - num_pages = (gint64)sysconf (_SC_AVPHYS_PAGES); + num_pages = (guint64)sysconf (_SC_AVPHYS_PAGES); #endif - if (page_size == -1 || num_pages == -1) { + if (!page_size || !num_pages) { g_warning ("Your operating system's sysconf (3) function doesn't correctly report physical memory size!"); return _DEFAULT_MEM_SIZE; } - return (guint64)page_size * (guint64)num_pages; + return page_size * num_pages; #else return _DEFAULT_MEM_SIZE; #endif diff --git a/src/mono/mono/utils/memfuncs.h b/src/mono/mono/utils/memfuncs.h index 904b28c96562c4..c8b934e3f7aacb 100644 --- a/src/mono/mono/utils/memfuncs.h +++ b/src/mono/mono/utils/memfuncs.h @@ -24,5 +24,10 @@ MONO_COMPONENT_API void mono_gc_memmove_atomic (void *dest, const void *src, siz void mono_gc_memmove_aligned (void *dest, const void *src, size_t size); guint64 mono_determine_physical_ram_size (void); guint64 mono_determine_physical_ram_available_size (void); +#if HAVE_CGROUP_SUPPORT +size_t mono_get_restricted_memory_limit(void); +gboolean mono_get_memory_used(size_t *); +size_t mono_get_memory_avail(void); +#endif #endif diff --git a/src/mono/mono/utils/mono-cgroup.c b/src/mono/mono/utils/mono-cgroup.c new file mode 100644 index 00000000000000..337abbe38b2350 --- /dev/null +++ b/src/mono/mono/utils/mono-cgroup.c @@ -0,0 +1,972 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +/*++ + +Module Name: + + mono-cgroup.c + +Abstract: + Read the memory limit for the current process + + Adapted from runtime src/coreclr/gc/unix/cgroup.cpp + - commit 28ec20194010c2a3d06f2217998cfcb8e8b8fb5e +--*/ +#ifdef __FreeBSD__ +#define _WITH_GETLINE +#endif + +#include +#include + +#if HAVE_CGROUP_SUPPORT + +#include +#include +#include +#include +#include +#include +#include +#if defined(__APPLE__) || defined(__FreeBSD__) +#include +#include +#else +#include +#endif +#include +#include + +#include + +#ifndef SIZE_T_MAX +# define SIZE_T_MAX (~(size_t)0) +#endif + +#define CGROUP2_SUPER_MAGIC 0x63677270 +#define TMPFS_MAGIC 0x01021994 + +#define PROC_MOUNTINFO_FILENAME "/proc/self/mountinfo" +#define PROC_CGROUP_FILENAME "/proc/self/cgroup" +#define PROC_STATM_FILENAME "/proc/self/statm" +#define CGROUP1_MEMORY_LIMIT_FILENAME "/memory.limit_in_bytes" +#define CGROUP2_MEMORY_LIMIT_FILENAME "/memory.max" +#define CGROUP_MEMORY_STAT_FILENAME "/memory.stat" +#define CGROUP1_MEMORY_USAGE_FILENAME "/memory.usage_in_bytes" +#define CGROUP2_MEMORY_USAGE_FILENAME "/memory.current" +#define CGROUP1_MEMORY_STAT_INACTIVE_FIELD "total_inactive_file " +#define CGROUP2_MEMORY_STAT_INACTIVE_FIELD "inactive_file " +#define CGROUP1_CFS_QUOTA_FILENAME "/cpu.cfs_quota_us" +#define CGROUP1_CFS_PERIOD_FILENAME "/cpu.cfs_period_us" +#define CGROUP2_CPU_MAX_FILENAME "/cpu.max" + +static void initialize(void); +static gboolean readMemoryValueFromFile(const char *, size_t *); +static gboolean getPhysicalMemoryLimit(size_t *); +static gboolean getPhysicalMemoryUsage(size_t *); +static int findCGroupVersion(void); +static gboolean isCGroup1MemorySubsystem(const char *); +static gboolean isCGroup1CpuSubsystem(const char *); +static char *findCGroupPath(gboolean (*is_subsystem)(const char *)); +static void findHierarchyMount(gboolean (*is_subsystem)(const char *), char **, char **); +static char *findCGroupPathForSubsystem(gboolean (*is_subsystem)(const char *)); +static gboolean getCGroupMemoryLimit(size_t *, const char *); +static gboolean getCGroupMemoryUsage(size_t *, const char *, const char *); +static size_t getPhysicalMemoryTotal(size_t); +static long long readCpuCGroupValue(const char *); +static void computeCpuLimit(long long, long long, guint32 *); + +size_t mono_get_restricted_memory_limit(void); +gboolean mono_get_memory_used(size_t *); +size_t mono_get_memory_avail(void); +gboolean mono_get_cpu_limit(guint *); +static gboolean readLongLongValueFromFile(const char *, long long *); + +// the cgroup version number or 0 to indicate cgroups are not found or not enabled +static int s_cgroup_version = -1; + +static char *s_memory_cgroup_path = NULL; +static char *s_cpu_cgroup_path = NULL; + +static long pageSize; + +/** + * @brief Initialize variables used by the calculation routines. + * + */ +static void +initialize() +{ + s_cgroup_version = findCGroupVersion (); + s_memory_cgroup_path = findCGroupPath (s_cgroup_version == 1 ? &isCGroup1MemorySubsystem : NULL); + s_cpu_cgroup_path = findCGroupPath (s_cgroup_version == 1 ? &isCGroup1CpuSubsystem : NULL); + + if (s_cgroup_version == 0) + return; + + pageSize = sysconf (_SC_PAGE_SIZE); +} + +/** + * + * @brief Read a value from a specified /sys/fs/cgroup/memory file + * + * @param[in] filename - name of file containing value + * @param[out] val - pointer to the result area + * @returns True or False depending if value was found + * + */ +static gboolean +readMemoryValueFromFile(const char* filename, size_t* val) +{ + gboolean result = FALSE; + char *line = NULL; + size_t lineLen = 0; + char *endptr = NULL; + FILE *file = NULL; + + if (val != NULL) { + file = fopen (filename, "r"); + if (file != NULL) { + if (getline (&line, &lineLen, file) != -1) { + errno = 0; + *val = strtoull (line, &endptr, 0); + result = TRUE; + } + } + } + + if (file) + fclose (file); + free (line); + return result; +} + +/** + * + * @brief Interrogate the cgroup memory values to determine if there's + * a limit on physical memory. + * + * @param[out] val - pointer to the result area + * @returns True or False depending if a limit was found + * + */ +static gboolean +getPhysicalMemoryLimit(size_t *val) +{ + if (s_cgroup_version == 0) + return FALSE; + else if (s_cgroup_version == 1) + return getCGroupMemoryLimit (val, CGROUP1_MEMORY_LIMIT_FILENAME); + else if (s_cgroup_version == 2) + return getCGroupMemoryLimit (val, CGROUP2_MEMORY_LIMIT_FILENAME); + else { + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG, + "Unknown cgroup version."); + return FALSE; + } +} + +/** + * + * @brief Interrogate the cgroup memory values to determine how much + * memory is in use. + * + * @param[out] val - pointer to the result area + * @returns True or False depending if a usage value was found + * + */ +static gboolean +getPhysicalMemoryUsage(size_t *val) +{ + if (s_cgroup_version == 0) + return FALSE; + else if (s_cgroup_version == 1) + return getCGroupMemoryUsage (val, CGROUP1_MEMORY_USAGE_FILENAME, CGROUP1_MEMORY_STAT_INACTIVE_FIELD); + else if (s_cgroup_version == 2) + return getCGroupMemoryUsage (val, CGROUP2_MEMORY_USAGE_FILENAME, CGROUP2_MEMORY_STAT_INACTIVE_FIELD); + else { + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG, + "Unknown cgroup version."); + return FALSE; + } +} + +/** + * + * @brief Inspect the /sys/fs/cgroup hierachy to determine what version of + * group we are using + * + * @returns cgroup version + * + */ +static int +findCGroupVersion() +{ + // It is possible to have both cgroup v1 and v2 enabled on a system. + // Most non-bleeding-edge Linux distributions fall in this group. We + // look at the file system type of /sys/fs/cgroup to determine which + // one is the default. For more details, see: + // https://systemd.io/CGROUP_DELEGATION/#three-different-tree-setups- + // We dont care about the difference between the "legacy" and "hybrid" + // modes because both of those involve cgroup v1 controllers managing + // resources. + + + struct statfs stats; + int result = statfs ("/sys/fs/cgroup", &stats); + if (result != 0) + return 0; + + switch (stats.f_type) { + case TMPFS_MAGIC: return 1; + case CGROUP2_SUPER_MAGIC: return 2; + default: return 0; + } +} + +/** + * + * @brief Check if we've found the memory component of /sys/fs/cgroup + * + * @param[in] strTok - Token for comparison + * @returns True if token matches "memory" + * + */ +static gboolean +isCGroup1MemorySubsystem(const char *strTok) +{ + return strcmp ("memory", strTok) == 0; +} + +/** + * + * @brief Check if we've found the CPU component of /sys/fs/cgroup + * + * @param[in] strTok - Token for comparison + * @returns True if token matches "cpu" + * + */ +static gboolean +isCGroup1CpuSubsystem(const char *strTok) +{ + return strcmp ("cpu", strTok) == 0; +} + +/** + * + * @brief Navigate the /sys/fs/cgroup to try and find the correct cgroup path + * + * @param[in] is_subsystem - Function used to compare tokens + * @returns Path to cgroup + * + */ +static char * +findCGroupPath(gboolean (*is_subsystem)(const char *)) +{ + char *cgroup_path = NULL; + char *hierarchy_mount = NULL; + char *hierarchy_root = NULL; + char *cgroup_path_relative_to_mount = NULL; + size_t common_path_prefix_len; + + findHierarchyMount (is_subsystem, &hierarchy_mount, &hierarchy_root); + if (hierarchy_mount != NULL && hierarchy_root != NULL) { + + cgroup_path_relative_to_mount = findCGroupPathForSubsystem (is_subsystem); + if (cgroup_path_relative_to_mount != NULL) { + + cgroup_path = (char*)malloc (strlen (hierarchy_mount) + strlen (cgroup_path_relative_to_mount) + 1); + if (cgroup_path != NULL) { + + strcpy (cgroup_path, hierarchy_mount); + // For a host cgroup, we need to append the relative path. + // The root and cgroup path can share a common prefix of the path that should not be appended. + // Example 1 (docker): + // hierarchy_mount: /sys/fs/cgroup/cpu + // hierarchy_root: /docker/87ee2de57e51bc75175a4d2e81b71d162811b179d549d6601ed70b58cad83578 + // cgroup_path_relative_to_mount: /docker/87ee2de57e51bc75175a4d2e81b71d162811b179d549d6601ed70b58cad83578/my_named_cgroup + // append do the cgroup_path: /my_named_cgroup + // final cgroup_path: /sys/fs/cgroup/cpu/my_named_cgroup + // + // Example 2 (out of docker) + // hierarchy_mount: /sys/fs/cgroup/cpu + // hierarchy_root: / + // cgroup_path_relative_to_mount: /my_named_cgroup + // append do the cgroup_path: /my_named_cgroup + // final cgroup_path: /sys/fs/cgroup/cpu/my_named_cgroup + common_path_prefix_len = strlen (hierarchy_root); + if ((common_path_prefix_len == 1) || + (strncmp (hierarchy_root, cgroup_path_relative_to_mount, common_path_prefix_len) != 0)) + common_path_prefix_len = 0; + + g_assert((cgroup_path_relative_to_mount[common_path_prefix_len] == '/') || + (cgroup_path_relative_to_mount[common_path_prefix_len] == '\0')); + + strcat (cgroup_path, cgroup_path_relative_to_mount + common_path_prefix_len); + } + } + } + + free (hierarchy_mount); + free (hierarchy_root); + free (cgroup_path_relative_to_mount); + return cgroup_path; +} + +/** + * + * @brief Check the /proc filesystem to determine the root and mount + * path of /sys/fs/cgroup data + * + * @param[in] is_subsystem - Comparison function + * @param[out] pmountpath - + * @param[out] pmountroot - + * + */ +static void +findHierarchyMount(gboolean (*is_subsystem)(const char *), char** pmountpath, char** pmountroot) +{ + char *line = NULL; + size_t lineLen = 0, maxLineLen = 0; + char *filesystemType = NULL; + char *options = NULL; + char *mountpath = NULL; + char *mountroot = NULL; + + FILE *mountinfofile = fopen (PROC_MOUNTINFO_FILENAME, "r"); + if (mountinfofile == NULL) + goto done; + + while (getline (&line, &lineLen, mountinfofile) != -1) { + if (filesystemType == NULL || lineLen > maxLineLen) { + free (filesystemType); + filesystemType = NULL; + free (options); + options = NULL; + filesystemType = (char*)malloc (lineLen+1); + if (filesystemType == NULL) + goto done; + options = (char*)malloc (lineLen+1); + if (options == NULL) + goto done; + maxLineLen = lineLen; + } + + char *separatorChar = strstr (line, " - "); + + // See man page of proc to get format for /proc/self/mountinfo file + int sscanfRet = sscanf (separatorChar, + " - %s %*s %s", + filesystemType, + options); + if (sscanfRet != 2) { + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG, "Failed to parse mount info file contents with sscanf."); + goto done; + } + + if (strncmp(filesystemType, "cgroup", 6) == 0) { + gboolean isSubsystemMatch = is_subsystem == NULL; + if (!isSubsystemMatch) { + char *context = NULL; + char *strTok = strtok_r (options, ",", &context); + while (!isSubsystemMatch && strTok != NULL) + { + isSubsystemMatch = is_subsystem (strTok); + strTok = strtok_r (NULL, ",", &context); + } + } + if (isSubsystemMatch) { + mountpath = (char*)malloc (lineLen+1); + if (mountpath == NULL) + goto done; + mountroot = (char*)malloc (lineLen+1); + if (mountroot == NULL) + goto done; + + sscanfRet = sscanf (line, + "%*s %*s %*s %s %s ", + mountroot, + mountpath); + if (sscanfRet != 2) + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG, + "Failed to parse mount info file contents with sscanf."); + + // assign the output arguments and clear the locals so we don't free them. + *pmountpath = mountpath; + *pmountroot = mountroot; + mountpath = mountroot = NULL; + } + } + } +done: + free (mountpath); + free (mountroot); + free (filesystemType); + free (options); + free (line); + if (mountinfofile) + fclose (mountinfofile); +} + +/** + * + * @brief + * Check the /proc filesystem to determine the root and mount path + * of /sys/fs/cgroup data + * + * @param[in] is_subsystem - Comparison function + * @returns cgroup path for the memory subsystem + * + */ +static char * +findCGroupPathForSubsystem(gboolean (*is_subsystem)(const char *)) +{ + char *line = NULL; + size_t lineLen = 0; + size_t maxLineLen = 0; + char *subsystem_list = NULL; + char *cgroup_path = NULL; + gboolean result = FALSE; + + FILE *cgroupfile = fopen (PROC_CGROUP_FILENAME, "r"); + if (cgroupfile == NULL) + goto done; + + while (!result && getline (&line, &lineLen, cgroupfile) != -1) { + if (subsystem_list == NULL || lineLen > maxLineLen) { + free (subsystem_list); + subsystem_list = NULL; + free (cgroup_path); + cgroup_path = NULL; + subsystem_list = (char*)malloc (lineLen+1); + if (subsystem_list == NULL) + goto done; + cgroup_path = (char*)malloc (lineLen+1); + if (cgroup_path == NULL) + goto done; + maxLineLen = lineLen; + } + + if (s_cgroup_version == 1) { + // See man page of proc to get format for /proc/self/cgroup file + int sscanfRet = sscanf (line, + "%*[^:]:%[^:]:%s", + subsystem_list, + cgroup_path); + if (sscanfRet != 2) { + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG, + "Failed to parse cgroup info file contents with sscanf."); + goto done; + } + + char* context = NULL; + char* strTok = strtok_r (subsystem_list, ",", &context); + while (strTok != NULL) { + if (is_subsystem (strTok)) { + result = TRUE; + break; + } + strTok = strtok_r (NULL, ",", &context); + } + } else if (s_cgroup_version == 2) { + // See https://www.kernel.org/doc/Documentation/cgroup-v2.txt + // Look for a "0::/some/path" + int sscanfRet = sscanf (line, + "0::%s", + cgroup_path); + if (sscanfRet == 1) + { + result = TRUE; + } + } else { + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG, + "Unknown cgroup version in mountinfo."); + goto done; + } + } +done: + free (subsystem_list); + if (!result) { + free (cgroup_path); + cgroup_path = NULL; + } + free (line); + if (cgroupfile) + fclose (cgroupfile); + return cgroup_path; +} + +/** + * + * @brief Extract memory limit from specified /sys/fs/cgroup/memory file + * + * @param[out] val - Memory limit + * @param[in] filename - name of file from which to extract limit + * @returns True if value found + * + */ +static gboolean +getCGroupMemoryLimit(size_t *val, const char *filename) +{ + if (s_memory_cgroup_path == NULL) + return FALSE; + + char* mem_limit_filename = NULL; + if (asprintf (&mem_limit_filename, "%s%s", s_memory_cgroup_path, filename) < 0) + return FALSE; + + gboolean result = readMemoryValueFromFile (mem_limit_filename, val); + free (mem_limit_filename); + return result; +} + +/** + * + * @brief Extract memory usage from /sys/fs/cgroup/memory.stat file + * + * @param[out] val - Memory limit + * @returns True if value found + * + */ +static gboolean +getCGroupMemoryUsage(size_t *val, const char *filename, const char *inactiveFileFieldName) +{ + /* + * Use the same way to calculate memory load as popular container tools (Docker, Kubernetes, Containerd etc.) + * For cgroup v1: value of 'memory.usage_in_bytes' minus 'total_inactive_file' value of 'memory.stat' + * For cgroup v2: value of 'memory.current' minus 'inactive_file' value of 'memory.stat' + */ + + char *mem_usage_filename = NULL; + if (asprintf (&mem_usage_filename, "%s%s", s_memory_cgroup_path, filename) < 0) + return FALSE; + + size_t temp = 0; + size_t usage = 0; + + gboolean result = readMemoryValueFromFile (mem_usage_filename, &temp); + if (result) { + if (temp > SIZE_T_MAX) + usage = SIZE_T_MAX; + else + usage = temp; + } + + free (mem_usage_filename); + + if (!result) + return result; + + if (s_memory_cgroup_path == NULL) + return FALSE; + + char *stat_filename = NULL; + if (asprintf (&stat_filename, "%s%s", s_memory_cgroup_path, CGROUP_MEMORY_STAT_FILENAME) < 0) + return FALSE; + + FILE *stat_file = fopen (stat_filename, "r"); + free (stat_filename); + if (stat_file == NULL) + return FALSE; + + char *line = NULL; + size_t lineLen = 0; + gboolean foundInactiveFileValue = FALSE; + char *endptr; + + size_t inactiveFileFieldNameLength = strlen (inactiveFileFieldName); + + while (getline (&line, &lineLen, stat_file) != -1) { + if (strncmp (line, inactiveFileFieldName, inactiveFileFieldNameLength) == 0) { + errno = 0; + const char *startptr = line + inactiveFileFieldNameLength; + size_t inactiveFileValue = strtoll (startptr, &endptr, 10); + if (endptr != startptr && errno == 0) { + foundInactiveFileValue = TRUE; + *val = usage - inactiveFileValue; + } + break; + } + } + + fclose (stat_file); + free (line); + + return foundInactiveFileValue; +} + +/** + * + * @brief Determine if there are any limits on memory and return the value + * + * @returns Physical memory limit + * + * Zero represents no limit. + */ +size_t +mono_get_restricted_memory_limit() +{ + size_t physical_memory_limit = 0; + + if (s_cgroup_version == -1) + initialize(); + + if (s_cgroup_version == 0) + return 0; + + if (!getPhysicalMemoryLimit (&physical_memory_limit)) + return 0; + + // If there's no memory limit specified on the container this + // actually returns 0x7FFFFFFFFFFFF000 (2^63-1 rounded down to + // 4k which is a common page size). So we know we are not + // running in a memory restricted environment. + if (physical_memory_limit > 0x7FFFFFFF00000000) + return 0; + + return (getPhysicalMemoryTotal (physical_memory_limit)); +} + +/** + * + * @brief Check the input limit against any system limits or actual memory on system + * + * @param[in] physical_memory_limit - The max memory on the system + * @returns Physical memory total + * + */ +static size_t +getPhysicalMemoryTotal(size_t physical_memory_limit) +{ + struct rlimit curr_rlimit; + size_t rlimit_soft_limit = (size_t)RLIM_INFINITY; + if (getrlimit (RLIMIT_AS, &curr_rlimit) == 0) + rlimit_soft_limit = curr_rlimit.rlim_cur; + physical_memory_limit = (physical_memory_limit < rlimit_soft_limit) ? + physical_memory_limit : rlimit_soft_limit; + + // Ensure that limit is not greater than real memory size + long pages = sysconf (_SC_PHYS_PAGES); + if (pages != -1) { + if (pageSize != -1) { + physical_memory_limit = (physical_memory_limit < (size_t)pages * pageSize) ? + physical_memory_limit : (size_t)pages * pageSize; + } + } + + if (physical_memory_limit > ULONG_MAX) { + // It is observed in practice when the memory is unrestricted, Linux control + // group returns a physical limit that is bigger than the address space + return ULONG_MAX; + } else + return physical_memory_limit; +} + +/** + * + * @brief Determine the amount of memory in use + * + * @param[out] val - pointer to the memory usage value + * @returns True if we are able to determine usage + * + */ +gboolean +mono_get_memory_used(size_t *val) +{ + gboolean result = FALSE; + size_t linelen; + char *line = NULL; + + if (val == NULL) + return FALSE; + + // Linux uses cgroup usage to trigger oom kills. + if (getPhysicalMemoryUsage (val)) + return TRUE; + + // process resident set size. + FILE* file = fopen (PROC_STATM_FILENAME, "r"); + if (file != NULL && getline (&line, &linelen, file) != -1) { + char* context = NULL; + char* strTok = strtok_r (line, " ", &context); + strTok = strtok_r (NULL, " ", &context); + + errno = 0; + *val = strtoull (strTok, NULL, 0); + if (errno == 0) { + if (pageSize != -1) { + *val = *val * pageSize; + result = TRUE; + } + } + } + + if (file) + fclose (file); + free (line); + return result; +} + +/** + * + * @brief Determine the amount of memory available by examininig any + * limits and checking what memory is in use. + * + * @returns Amount of memory available + * + */ +size_t +mono_get_memory_avail() +{ + size_t max, used, avail, sysAvail; +#ifdef _SC_AVPHYS_PAGES // If this isn't defined then we don't get called + + max = mono_get_restricted_memory_limit (); + + if (max == 0) + max = getPhysicalMemoryTotal (ULONG_MAX); + + if (mono_get_memory_used (&used)) + avail = max - used; + else + avail = max; + + sysAvail = sysconf (_SC_AVPHYS_PAGES) * pageSize; + return (avail < sysAvail ? avail : sysAvail); +#else + return (0); +#endif +} + +/** + * + * @brief Return any limits on CPU use + * + * @returns Number of CPU usable + * + */ +static gboolean +getCGroup1CpuLimit(guint32 *val) +{ + long long quota; + long long period; + + quota = readCpuCGroupValue (CGROUP1_CFS_QUOTA_FILENAME); + if (quota <= 0) + return FALSE; + + period = readCpuCGroupValue (CGROUP1_CFS_PERIOD_FILENAME); + if (period <= 0) + return FALSE; + + computeCpuLimit (period, quota, val); + + return TRUE; +} + +/** + * + * @brief Return any limits on CPU use + * + * @returns Number of CPU usable + * + */ +static gboolean +getCGroup2CpuLimit(guint32 *val) +{ + char *filename = NULL; + FILE *file = NULL; + char *endptr = NULL; + char *max_quota_string = NULL; + char *period_string = NULL; + char *context = NULL; + char *line = NULL; + size_t lineLen = 0; + + long long quota = 0; + long long period = 0; + + + gboolean result = FALSE; + + if (s_cpu_cgroup_path == NULL) + return FALSE; + + if (asprintf (&filename, "%s%s", s_cpu_cgroup_path, CGROUP2_CPU_MAX_FILENAME) < 0) + return FALSE; + + file = fopen (filename, "r"); + if (file == NULL) + goto done; + + if (getline (&line, &lineLen, file) == -1) + goto done; + + // The expected format is: + // $MAX $PERIOD + // Where "$MAX" may be the string literal "max" + + max_quota_string = strtok_r (line, " ", &context); + if (max_quota_string == NULL) + { + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG, + "Unable to parse " CGROUP2_CPU_MAX_FILENAME " file contents."); + goto done; + } + period_string = strtok_r (NULL, " ", &context); + if (period_string == NULL) + { + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG, + "Unable to parse " CGROUP2_CPU_MAX_FILENAME " file contents."); + goto done; + } + + // "max" means no cpu limit + if (strcmp ("max", max_quota_string) == 0) + goto done; + + errno = 0; + quota = strtoll (max_quota_string, &endptr, 10); + if (max_quota_string == endptr || errno != 0) + goto done; + + period = strtoll (period_string, &endptr, 10); + if (period_string == endptr || errno != 0) + goto done; + + computeCpuLimit (period, quota, val); + result = TRUE; + +done: + if (file) + fclose (file); + free (filename); + free (line); + + return result; +} + +/** + * + * @brief Compute the CPU limit based on the CGroup data + * + * @param[in] period + * @param[in] quota - Limit found in sysfs + * @param[out] Number of CPU usable + * + */ +static void +computeCpuLimit(long long period, long long quota, uint32_t *val) +{ + // Cannot have less than 1 CPU + if (quota <= period) { + *val = 1; + return; + } + + // Calculate cpu count based on quota and round it up + double cpu_count = (double) quota / period + 0.999999999; + *val = (cpu_count < UINT32_MAX) ? (uint32_t)cpu_count : UINT32_MAX; +} + +/** + * + * @brief Read the CGroup CPU data from sysfs + * + * @param[in] subsystemFileName - sysfs File containing data + * @returns CPU CGroup value + * + */ +static long long +readCpuCGroupValue(const char *subsystemFilename) +{ + char *filename = NULL; + gboolean result = FALSE; + long long val = -1; + + if (s_cpu_cgroup_path == NULL) + return -1; + + if (asprintf (&filename, "%s%s", s_cpu_cgroup_path, subsystemFilename) < 0) + return -1; + + result = readLongLongValueFromFile (filename, &val); + free (filename); + if (!result) + return -1; + + return val; +} + +/** + * + * @brief Read a long long value from a file + * + * @param[in] fileName - sysfs File containing data + * @param[out] val - Value read + * @returns Success indicator + * + */ +static gboolean +readLongLongValueFromFile(const char *filename, long long *val) +{ + gboolean result = FALSE; + char *line = NULL; + size_t lineLen = 0; + char *endptr = NULL; + + if (val == NULL) + return FALSE; + + FILE *file = fopen (filename, "r"); + if (file == NULL) + return FALSE; + + if (getline (&line, &lineLen, file) != -1) { + errno = 0; + *val = strtoll (line, &endptr, 10); + if (line != endptr && errno == 0) + result = TRUE; + } + + fclose (file); + free (line); + return result; +} + +/** + * + * @brief Interrogate the cgroup CPU values to determine if there's + * a limit on CPUs + * + * @param[out] val - pointer to the result area + * @returns True or False depending if a limit was found + * + * Interrogate the cgroup CPU values to determine if there's + * a limit on CPUs + */ +gboolean +mono_get_cpu_limit(guint *val) +{ + if (s_cgroup_version == -1) + initialize(); + + if (s_cgroup_version == 0) + return FALSE; + else if (s_cgroup_version == 1) + return getCGroup1CpuLimit ((guint32 *)val); + else if (s_cgroup_version == 2) + return getCGroup2CpuLimit ((guint32 *)val); + else { + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_CONFIG, + "Unknown cgroup version."); + return FALSE; + } +} +#else + +MONO_EMPTY_SOURCE_FILE (mono_cgroup); + +#endif diff --git a/src/mono/mono/utils/mono-proclib.c b/src/mono/mono/utils/mono-proclib.c index 40404b44f85e3b..a683e3d90295cc 100644 --- a/src/mono/mono/utils/mono-proclib.c +++ b/src/mono/mono/utils/mono-proclib.c @@ -12,6 +12,7 @@ #include #include #include +#include #ifdef HOST_WIN32 #include @@ -190,3 +191,44 @@ mono_cpu_count (void) return 1; #endif } + +/** + * mono_cpu_limit: + * \returns the number of processors available to this process + */ +int +mono_cpu_limit (void) +{ +#if defined(HOST_WIN32) + return mono_cpu_count (); +#else + static int limit = -1; /* Value will be cached for future calls */ + + /* + * If 1st time through then check if user has mandated a value and use it, + * otherwise we check for any cgroup limit and use the min of actual number + * and that limit + */ + if (limit == -1) { + char *dotnetProcCnt = getenv ("DOTNET_PROCESSOR_COUNT"); + if (dotnetProcCnt != NULL) { + errno = 0; + limit = (int) strtol (dotnetProcCnt, NULL, 0); + if ((errno == 0) && (limit > 0)) /* If it's in range and positive */ + return limit; + } + limit = mono_cpu_count (); +#if HAVE_CGROUP_SUPPORT + int count = 0; + if (mono_get_cpu_limit (&count)) + limit = (limit < count ? limit : count); +#endif + } + + /* + * Just return the cached value + */ + return limit; +#endif +} + diff --git a/src/mono/mono/utils/mono-proclib.h b/src/mono/mono/utils/mono-proclib.h index f14be3b9f3375b..9c72b47b239004 100644 --- a/src/mono/mono/utils/mono-proclib.h +++ b/src/mono/mono/utils/mono-proclib.h @@ -19,5 +19,12 @@ MONO_API int mono_cpu_count (void); +MONO_API +int +mono_cpu_limit (void); + +gboolean +mono_get_cpu_limit(int *limit); + #endif /* __MONO_PROC_LIB_H__ */ From e5058f6dab197944c4dcbf06ebfbe98d002b2f43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Rylek?= Date: Wed, 31 Aug 2022 20:09:54 +0200 Subject: [PATCH 058/107] Regression test for GitHub issue #74792 (Roslyn issue 63617) (#74804) While investigating the bug 74792 I have created this regression test based on the Roslyn issue 63617. So far I haven't managed to repro the failure locally so I'm sending it to the lab. Please let me know if I created the test incorrectly so that it needs adjustments to hit the issue. Thanks Tomas --- .../RegressionTests/GitHub_74792.cs | 49 +++++++++++++++++++ .../RegressionTests/GitHub_74792.csproj | 9 ++++ 2 files changed, 58 insertions(+) create mode 100644 src/tests/Loader/classloader/StaticVirtualMethods/RegressionTests/GitHub_74792.cs create mode 100644 src/tests/Loader/classloader/StaticVirtualMethods/RegressionTests/GitHub_74792.csproj diff --git a/src/tests/Loader/classloader/StaticVirtualMethods/RegressionTests/GitHub_74792.cs b/src/tests/Loader/classloader/StaticVirtualMethods/RegressionTests/GitHub_74792.cs new file mode 100644 index 00000000000000..769e449dee483c --- /dev/null +++ b/src/tests/Loader/classloader/StaticVirtualMethods/RegressionTests/GitHub_74792.cs @@ -0,0 +1,49 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; + +// This regression test tracks an externally reported issue where this +// code fails at runtime with a BadImageFormatException because the +// constraint resolver fails to confirm that L1 and L2 implement +// ILogic when constructing instances of the struct G, cf: +// +// https://github.com/dotnet/roslyn/issues/63617 +// https://github.com/dotnet/runtime/issues/74792 +// +// Apparently it was failing in an older version of the CoreCLR +// runtime, as of now (around .NET 7 RC1 timeframe) the test passes. + +class Program +{ + public static int Main() + { + new G().Test(); + new G().Test(); + return 100; + } +} + +public interface ILogic{ + abstract static void Run(); +} + +public class L1 : ILogic{ + public static void Run(){ + Console.WriteLine("L1"); + } +} + +public class L2 : ILogic{ + public static void Run(){ + Console.WriteLine("L2"); + } +} + +struct G where T : ILogic +{ + public void Test() + { + T.Run(); + } +} diff --git a/src/tests/Loader/classloader/StaticVirtualMethods/RegressionTests/GitHub_74792.csproj b/src/tests/Loader/classloader/StaticVirtualMethods/RegressionTests/GitHub_74792.csproj new file mode 100644 index 00000000000000..42c7a9e8ffc90f --- /dev/null +++ b/src/tests/Loader/classloader/StaticVirtualMethods/RegressionTests/GitHub_74792.csproj @@ -0,0 +1,9 @@ + + + true + Exe + + + + + From 02e144e374dddccfe9dad61be5a12df347a18f39 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Wed, 31 Aug 2022 11:27:31 -0700 Subject: [PATCH 059/107] Fix use of uninitialized memory for Vector3 constants (#74857) * Fix use of uninitialized memory for Vector3 constants Co-authored-by: Jakob Botsch Nielsen --- src/coreclr/jit/codegenarm64.cpp | 10 ++++++++-- src/coreclr/jit/codegenxarch.cpp | 10 ++++++++-- src/coreclr/jit/instr.cpp | 8 +++++++- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/coreclr/jit/codegenarm64.cpp b/src/coreclr/jit/codegenarm64.cpp index 6850014a1d710a..40d6e7cbbadbdf 100644 --- a/src/coreclr/jit/codegenarm64.cpp +++ b/src/coreclr/jit/codegenarm64.cpp @@ -2412,8 +2412,14 @@ void CodeGen::genSetRegToConst(regNumber targetReg, var_types targetType, GenTre // Get a temp integer register to compute long address. regNumber addrReg = tree->GetSingleTempReg(); - simd16_t constValue = vecCon->gtSimd16Val; - CORINFO_FIELD_HANDLE hnd = emit->emitSimd16Const(constValue); + simd16_t constValue = {}; + + if (vecCon->TypeIs(TYP_SIMD12)) + memcpy(&constValue, &vecCon->gtSimd12Val, sizeof(simd12_t)); + else + constValue = vecCon->gtSimd16Val; + + CORINFO_FIELD_HANDLE hnd = emit->emitSimd16Const(constValue); emit->emitIns_R_C(INS_ldr, attr, targetReg, addrReg, hnd, 0); } diff --git a/src/coreclr/jit/codegenxarch.cpp b/src/coreclr/jit/codegenxarch.cpp index d5bbe76dc1e528..6cfe068be76b68 100644 --- a/src/coreclr/jit/codegenxarch.cpp +++ b/src/coreclr/jit/codegenxarch.cpp @@ -561,8 +561,14 @@ void CodeGen::genSetRegToConst(regNumber targetReg, var_types targetType, GenTre case TYP_SIMD12: case TYP_SIMD16: { - simd16_t constValue = vecCon->gtSimd16Val; - CORINFO_FIELD_HANDLE hnd = emit->emitSimd16Const(constValue); + simd16_t constValue = {}; + + if (vecCon->TypeIs(TYP_SIMD12)) + memcpy(&constValue, &vecCon->gtSimd12Val, sizeof(simd12_t)); + else + constValue = vecCon->gtSimd16Val; + + CORINFO_FIELD_HANDLE hnd = emit->emitSimd16Const(constValue); emit->emitIns_R_C(ins_Load(targetType), attr, targetReg, hnd, 0); break; diff --git a/src/coreclr/jit/instr.cpp b/src/coreclr/jit/instr.cpp index 6d9494e59b541b..572a556c0858d6 100644 --- a/src/coreclr/jit/instr.cpp +++ b/src/coreclr/jit/instr.cpp @@ -765,7 +765,13 @@ CodeGen::OperandDesc CodeGen::genOperandDesc(GenTree* op) case TYP_SIMD12: case TYP_SIMD16: { - simd16_t constValue = op->AsVecCon()->gtSimd16Val; + simd16_t constValue = {}; + + if (op->TypeIs(TYP_SIMD12)) + memcpy(&constValue, &op->AsVecCon()->gtSimd12Val, sizeof(simd12_t)); + else + constValue = op->AsVecCon()->gtSimd16Val; + return OperandDesc(emit->emitSimd16Const(constValue)); } From c30cfbbbe2c515cc23c11e4a63dcb259269244ab Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Wed, 31 Aug 2022 15:39:32 -0400 Subject: [PATCH 060/107] [wasm] Split `runtime-wasm` pipeline into `runtime-wasm-libtests`, and `runtime-wasm-non-libtests` (#74859) Adds two new pipelines: - `runtime-wasm-libtests` - runs all the wasm library tests - `runtime-wasm-non-libtests` - runs all the wasm non-library tests like WBT, debugger etc. And `runtime-wasm` runs the combination of the two above. - For all 3 pipelines, jobs are run only if they weren't run on the default (`runtime`) pipeline ## Which pipeline should I run? * if `runtime` didn't run the tests that would be useful for testing the changes, then: - If the changes only relate to libraries, the runtime, then use `runtime-wasm-libtests` - If the changes only affect `Wasm.Build.Tests`, or debugger tests, or runtime tests, then use `runtime-wasm-non-libtests` - Use `runtime-wasm` when you want to run *all* the wasm tests # Updated CI matrix for wasm ## PR: * `only-pc` means `only on relevant path changes` ### Run by default * `runtime` runs jobs only when relevant paths change. And for `AOT`, only smoke tests are run. | . | runtime | | ----------------- | -------------------- | | libtests | linux+windows: all, only-pc | | libtests eat | linux+windows: smoke, only-pc | | libtests aot | linux+windows: smoke, only-pc | | high resource aot | none | | Wasm.Build.Tests | linux+windows: only-pc | | Debugger tests | linux+windows: only-pc | | Runtime tests | linux+windows: only-pc | ### Run manually with `/azp run ..` * `runtime-wasm*` pipelines are triggered manually, and they only run the jobs that would not run on any default pipelines based on path changes. * The `AOT` jobs run only smoke tests on `runtime`, and on `runtime-wasm*` pipelines all the `AOT` tests are run. | . | runtime-wasm | runtime-wasm-libtests | runtime-wasm-non-libtests | | ----------------- | -------------------------- | -------------------- | -------------------- | | libtests | linux+windows: all | linux+windows: all | none | | libtests eat | linux: all | linux: all | none | | libtests aot | linux+windows: all | linux+windows: all | none | | high resource aot | linux+windows: all | linux+windows: all | none | | Wasm.Build.Tests | linux+windows | none | linux+windows | | Debugger tests | linux+windows | none | linux+windows | | Runtime tests | linux | none | linux | | Perftrace | linux: all tests | linux: all tests | | | Multi-thread | linux: all tests | linux: all tests | | * `runtime-extra-platforms` does not run any wasm jobs on PRs * `high resource aot` runs a few specific library tests with AOT, that require more memory to AOT. ## Rolling build (twice a day): * `runtime` runs all the wasm jobs, but `AOT` still only runs smoke tests. * `runtime-extra-platforms` also runs by default. And it runs only the cases not covered by `runtime`. | . | runtime | runtime-extra-platforms (always run) | | ----------------- | ------------- | ------------------------------------ | | libtests | linux+windows: all | none | | libtests eat | linux: all | none | | libtests aot | linux+windows: smoke | linux+windows: all | | high resource aot | none | linux+windows: all | | | | | | Wasm.Build.Tests | linux+windows | none | | Debugger tests | linux+windows | none | | Runtime tests | linux | none | | Perftrace | linux: build only | none | | Multi-thread | linux: build only | none | * `high resource aot` runs a few specific library tests with AOT, that require more memory to AOT. --- .../common/templates/wasm-build-only.yml | 10 --- .../common/templates/wasm-build-tests.yml | 10 --- .../common/templates/wasm-debugger-tests.yml | 10 --- .../common/templates/wasm-library-tests.yml | 10 --- .../common/templates/wasm-runtime-tests.yml | 11 +-- eng/pipelines/common/variables.yml | 15 +++- eng/pipelines/common/xplat-setup.yml | 2 +- .../runtime-extra-platforms-wasm.yml | 5 +- eng/pipelines/runtime-wasm-libtests.yml | 19 +++++ eng/pipelines/runtime-wasm-non-libtests.yml | 19 +++++ src/mono/wasm/README.md | 78 ++++++++++++------- 11 files changed, 105 insertions(+), 84 deletions(-) create mode 100644 eng/pipelines/runtime-wasm-libtests.yml create mode 100644 eng/pipelines/runtime-wasm-non-libtests.yml diff --git a/eng/pipelines/common/templates/wasm-build-only.yml b/eng/pipelines/common/templates/wasm-build-only.yml index 761de04536d07c..32e17588a52928 100644 --- a/eng/pipelines/common/templates/wasm-build-only.yml +++ b/eng/pipelines/common/templates/wasm-build-only.yml @@ -27,16 +27,6 @@ jobs: value: ${{ parameters.alwaysRun }} - name: allWasmContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] - - name: isDefaultPipeline - # default pipeline, so not runtime-wasm, and not - # runtime-extra-platforms+rolling build - value: ${{ - and( - ne(parameters.isWasmOnlyBuild, true), - or( - ne(parameters.isExtraPlatformsBuild, true), - eq(variables['isRollingBuild'], true))) - }} - name: shouldRunOnDefaultPipelines value: $[ or( diff --git a/eng/pipelines/common/templates/wasm-build-tests.yml b/eng/pipelines/common/templates/wasm-build-tests.yml index 7ce2176f19a84d..07c253ed80bf1c 100644 --- a/eng/pipelines/common/templates/wasm-build-tests.yml +++ b/eng/pipelines/common/templates/wasm-build-tests.yml @@ -26,16 +26,6 @@ jobs: value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] - name: alwaysRunVar value: ${{ parameters.alwaysRun }} - - name: isDefaultPipeline - # default pipeline, so not runtime-wasm, and not - # runtime-extra-platforms+rolling build - value: ${{ - and( - ne(parameters.isWasmOnlyBuild, true), - or( - ne(parameters.isExtraPlatformsBuild, true), - eq(variables['isRollingBuild'], true))) - }} - name: shouldRunOnDefaultPipelines value: $[ or( diff --git a/eng/pipelines/common/templates/wasm-debugger-tests.yml b/eng/pipelines/common/templates/wasm-debugger-tests.yml index 2bd104a6592036..29e29e2a6aa27f 100644 --- a/eng/pipelines/common/templates/wasm-debugger-tests.yml +++ b/eng/pipelines/common/templates/wasm-debugger-tests.yml @@ -25,16 +25,6 @@ jobs: value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] - name: alwaysRunVar value: ${{ parameters.alwaysRun }} - - name: isDefaultPipeline - # default pipeline, so not runtime-wasm, and not - # runtime-extra-platforms+rolling build - value: ${{ - and( - ne(parameters.isWasmOnlyBuild, true), - or( - ne(parameters.isExtraPlatformsBuild, true), - eq(variables['isRollingBuild'], true))) - }} - name: shouldRunOnDefaultPipelines value: $[ or( diff --git a/eng/pipelines/common/templates/wasm-library-tests.yml b/eng/pipelines/common/templates/wasm-library-tests.yml index f96ca8aa1aabeb..9981d8727a85c5 100644 --- a/eng/pipelines/common/templates/wasm-library-tests.yml +++ b/eng/pipelines/common/templates/wasm-library-tests.yml @@ -34,16 +34,6 @@ jobs: value: ${{ parameters.alwaysRun }} - name: allWasmContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] - - name: isDefaultPipeline - # default pipeline, so not runtime-wasm, and not - # runtime-extra-platforms+rolling build - value: ${{ - and( - ne(parameters.isWasmOnlyBuild, true), - or( - ne(parameters.isExtraPlatformsBuild, true), - eq(variables['isRollingBuild'], true))) - }} - name: shouldRunOnDefaultPipelines value: $[ or( diff --git a/eng/pipelines/common/templates/wasm-runtime-tests.yml b/eng/pipelines/common/templates/wasm-runtime-tests.yml index b244949340241c..903235e75c1021 100644 --- a/eng/pipelines/common/templates/wasm-runtime-tests.yml +++ b/eng/pipelines/common/templates/wasm-runtime-tests.yml @@ -25,16 +25,6 @@ jobs: value: 10 - name: timeoutPerTestCollectionInMinutes value: 200 - - name: isDefaultPipeline - # default pipeline, so not runtime-wasm, and not - # runtime-extra-platforms+!rolling build - value: ${{ - and( - ne(parameters.isWasmOnlyBuild, true), - or( - ne(parameters.isExtraPlatformsBuild, true), - eq(variables['isRollingBuild'], true))) - }} - name: shouldRunOnDefaultPipelines value: $[ or( @@ -49,6 +39,7 @@ jobs: nameSuffix: AllSubsets_Mono_RuntimeTests runtimeVariant: monointerpreter buildArgs: -s mono+libs -c $(_BuildConfig) + timeoutInMinutes: 180 # if !alwaysRun, then: # if this is runtime-wasm (isWasmOnlyBuild): # - then run only if it would not have run on default pipelines (based diff --git a/eng/pipelines/common/variables.yml b/eng/pipelines/common/variables.yml index ea0836fc802440..0798b9fcd2e589 100644 --- a/eng/pipelines/common/variables.yml +++ b/eng/pipelines/common/variables.yml @@ -18,20 +18,27 @@ variables: - name: isNotExtraPlatformsBuild value: ${{ ne(variables['Build.DefinitionName'], 'runtime-extra-platforms') }} - name: isWasmOnlyBuild - value: ${{ eq(variables['Build.DefinitionName'], 'runtime-wasm') }} + value: ${{ in(variables['Build.DefinitionName'], 'runtime-wasm', 'runtime-wasm-libtests', 'runtime-wasm-non-libtests') }} - name: isRunSmokeTestsOnly - value: ${{ and(ne(variables['Build.DefinitionName'], 'runtime-extra-platforms'), ne(variables['Build.DefinitionName'], 'runtime-wasm')) }} + value: ${{ notin(variables['Build.DefinitionName'], 'runtime-extra-platforms', 'runtime-wasm', 'runtime-wasm-libtests', 'runtime-wasm-non-libtests') }} - name: isNotSpecificPlatformOnlyBuild - value: ${{ ne(variables['Build.DefinitionName'], 'runtime-wasm') }} + value: ${{ notin(variables['Build.DefinitionName'], 'runtime-wasm', 'runtime-wasm-libtests', 'runtime-wasm-non-libtests') }} # We only run evaluate paths on runtime, runtime-staging and runtime-community pipelines on PRs # keep in sync with /eng/pipelines/common/xplat-setup.yml - name: dependOnEvaluatePaths - value: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community', 'runtime-extra-platforms', 'runtime-wasm')) }} + value: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community', 'runtime-extra-platforms', 'runtime-wasm', 'runtime-wasm-libtests', 'runtime-wasm-non-libtests', 'dotnet-linker-tests', 'runtime-dev-innerloop')) }} - name: debugOnPrReleaseOnRolling ${{ if ne(variables['Build.Reason'], 'PullRequest') }}: value: Release ${{ if eq(variables['Build.Reason'], 'PullRequest') }}: value: Debug +- name: isDefaultPipeline + value: $[ and( + ne(variables['isWasmOnlyBuild'], true), + or( + ne(variables['isExtraPlatformsBuild'], true), + eq(variables['isRollingBuild'], true))) ] + - template: /eng/pipelines/common/perf-variables.yml diff --git a/eng/pipelines/common/xplat-setup.yml b/eng/pipelines/common/xplat-setup.yml index 9d91ccd891da39..53c43c02ce88da 100644 --- a/eng/pipelines/common/xplat-setup.yml +++ b/eng/pipelines/common/xplat-setup.yml @@ -18,7 +18,7 @@ jobs: shouldContinueOnError: ${{ or(eq(parameters.shouldContinueOnError, true), and(ne(parameters.shouldContinueOnError, 'forceFalse'), endsWith(variables['Build.DefinitionName'], 'staging'), eq(variables['Build.Reason'], 'PullRequest'))) }} # keep in sync with /eng/pipelines/common/variables.yml - dependOnEvaluatePaths: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community', 'runtime-extra-platforms', 'runtime-wasm')) }} + dependOnEvaluatePaths: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community', 'runtime-extra-platforms', 'runtime-wasm', 'runtime-wasm-libtests', 'runtime-wasm-non-libtests', 'dotnet-linker-tests', 'runtime-dev-innerloop')) }} variables: # Disable component governance in our CI builds. These builds are not shipping nor diff --git a/eng/pipelines/runtime-extra-platforms-wasm.yml b/eng/pipelines/runtime-extra-platforms-wasm.yml index 26152f51cf3a47..60d0105dedcc59 100644 --- a/eng/pipelines/runtime-extra-platforms-wasm.yml +++ b/eng/pipelines/runtime-extra-platforms-wasm.yml @@ -7,6 +7,8 @@ parameters: isExtraPlatformsBuild: false isWasmOnlyBuild: false isRollingBuild: false + excludeLibTests: false + excludeNonLibTests: false jobs: @@ -60,7 +62,7 @@ jobs: # - run everything, if relevant paths changed # - For runtime-wasm, force run all the jobs # -- ${{ if ne(parameters.isRollingBuild, true) }}: +- ${{ if and(ne(parameters.isRollingBuild, true), ne(parameters.excludeLibTests, true)) }}: # Library tests # these run on runtime also - template: /eng/pipelines/common/templates/wasm-library-tests.yml @@ -174,6 +176,7 @@ jobs: isWasmOnlyBuild: ${{ parameters.isWasmOnlyBuild }} alwaysRun: ${{ parameters.isWasmOnlyBuild }} +- ${{ if and(ne(parameters.isRollingBuild, true), ne(parameters.excludeNonLibTests, true)) }}: # Wasm.Build.Tests - template: /eng/pipelines/common/templates/wasm-build-tests.yml parameters: diff --git a/eng/pipelines/runtime-wasm-libtests.yml b/eng/pipelines/runtime-wasm-libtests.yml new file mode 100644 index 00000000000000..573dc4f3338587 --- /dev/null +++ b/eng/pipelines/runtime-wasm-libtests.yml @@ -0,0 +1,19 @@ +trigger: none + +variables: + - template: /eng/pipelines/common/variables.yml + +jobs: + +# +# Evaluate paths +# +- template: /eng/pipelines/common/evaluate-default-paths.yml + +- template: /eng/pipelines/runtime-extra-platforms-wasm.yml + parameters: + isExtraPlatformsBuild: ${{ variables.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ variables.isWasmOnlyBuild }} + isRollingBuild: ${{ variables.isRollingBuild }} + excludeNonLibTests: true + excludeLibTests: false diff --git a/eng/pipelines/runtime-wasm-non-libtests.yml b/eng/pipelines/runtime-wasm-non-libtests.yml new file mode 100644 index 00000000000000..c4f5e43c3b62a9 --- /dev/null +++ b/eng/pipelines/runtime-wasm-non-libtests.yml @@ -0,0 +1,19 @@ +trigger: none + +variables: + - template: /eng/pipelines/common/variables.yml + +jobs: + +# +# Evaluate paths +# +- template: /eng/pipelines/common/evaluate-default-paths.yml + +- template: /eng/pipelines/runtime-extra-platforms-wasm.yml + parameters: + isExtraPlatformsBuild: ${{ variables.isExtraPlatformsBuild }} + isWasmOnlyBuild: ${{ variables.isWasmOnlyBuild }} + isRollingBuild: ${{ variables.isRollingBuild }} + excludeNonLibTests: false + excludeLibTests: true diff --git a/src/mono/wasm/README.md b/src/mono/wasm/README.md index f8e2344fbf3295..221fce0e52b611 100644 --- a/src/mono/wasm/README.md +++ b/src/mono/wasm/README.md @@ -230,38 +230,60 @@ npm update ### How do I know which jobs run on CI, and when? ## PR: -* `runtime-extra-platforms`, and `runtime-wasm` run only when manually triggered with a comment - `/azp run ` -* `runtime`, and `runtime-staging`, run jobs only when relevant paths change. And for `EAT`, and `AOT`, only smoke tests are run. -* And when `runtime-wasm` is triggered manually, it runs *all* the wasm jobs completely - -| . | runtime | runtime-staging | runtime-extra-platforms(manual only) | runtime-wasm (manual only) | -| ----------------- | -------------------- | --------------- | ------------------------------------ | ------- | -| libtests | linux: all, only-pc | windows: all, only-pc | linux+windows: all, only-pc | linux+windows: all, always | -| libtests eat | linux: smoke, only-pc | - | linux: all, only-pc | linux: all, always | -| libtests aot | linux: smoke, only-pc | windows: smoke, only-pc | linux+windows: all, only-pc | linux+windows: all, always | -| high resource aot | none | none | linux+windows: all, only-pc | linux+windows: all, always | -| Wasm.Build.Tests | linux: only-pc | windows: only-pc | linux+windows: only-pc | linux+windows | -| Debugger tests | - | linux+windows: only-pc | linux+windows: only-pc | linux+windows | -| Runtime tests | linux: only-pc | - | linux: only-pc | linux | +* `only-pc` means `only on relevant path changes` + +### Run by default + +* `runtime` runs jobs only when relevant paths change. And for `AOT`, only smoke tests are run. + +| . | runtime | +| ----------------- | -------------------- | +| libtests | linux+windows: all, only-pc | +| libtests eat | linux+windows: smoke, only-pc | +| libtests aot | linux+windows: smoke, only-pc | +| high resource aot | none | +| Wasm.Build.Tests | linux+windows: only-pc | +| Debugger tests | linux+windows: only-pc | +| Runtime tests | linux+windows: only-pc | + + +### Run manually with `/azp run ..` + +* `runtime-wasm*` pipelines are triggered manually, and they only run the jobs that would not run on any default pipelines based on path changes. +* The `AOT` jobs run only smoke tests on `runtime`, and on `runtime-wasm*` pipelines all the `AOT` tests are run. + +| . | runtime-wasm | runtime-wasm-libtests | runtime-wasm-non-libtests | +| ----------------- | -------------------------- | -------------------- | -------------------- | +| libtests | linux+windows: all | linux+windows: all | none | +| libtests eat | linux: all | linux: all | none | +| libtests aot | linux+windows: all | linux+windows: all | none | +| high resource aot | linux+windows: all | linux+windows: all | none | +| Wasm.Build.Tests | linux+windows | none | linux+windows | +| Debugger tests | linux+windows | none | linux+windows | +| Runtime tests | linux | none | linux | +| Perftrace | linux: all tests | linux: all tests | none | +| Multi-thread | linux: all tests | linux: all tests | none | + +* `runtime-extra-platforms` does not run any wasm jobs on PRs * `high resource aot` runs a few specific library tests with AOT, that require more memory to AOT. ## Rolling build (twice a day): -* `runtime`, and `runtime-staging`, run all the wasm jobs unconditionally, but `EAT`, and `AOT` still run only smoke tests. -* `runtime-extra-platforms` also runs by default. And it runs only the cases not covered by the above two pipelines. - -* jobs w/o `only-pc` are always run - -| . | runtime | runtime-staging | runtime-extra-platforms (always run) | runtime-wasm (manual only) | -| ----------------- | ------------- | --------------- | ------------------------------------ | ------ | -| libtests | linux: all(v8/chr) | windows: all | none | N/A | -| libtests eat | linux: smoke | - | linux: all | | -| libtests aot | linux: smoke | windows: smoke | linux+windows: all | | -| high resource aot | none | none | linux+windows: all | | -| | | | | | -| Wasm.Build.Tests | linux: always | windows: always | none | | -| Debugger tests | - | linux+windows: always | none | | -| Runtime tests | linux: always | - | none | | +* `runtime` runs all the wasm jobs, but `AOT` still only runs smoke tests. +* `runtime-extra-platforms` also runs by default. And it runs only the cases not covered by `runtime`. + +| . | runtime | runtime-extra-platforms (always run) | +| ----------------- | ------------- | ------------------------------------ | +| libtests | linux+windows: all | none | +| libtests eat | linux: all | none | +| libtests aot | linux+windows: smoke | linux+windows: all | +| high resource aot | none | linux+windows: all | +| | | | +| Wasm.Build.Tests | linux+windows | none | +| Debugger tests | linux+windows | none | +| Runtime tests | linux | none | +| Perftrace | linux: build only | none | +| Multi-thread | linux: build only | none | * `high resource aot` runs a few specific library tests with AOT, that require more memory to AOT. From 7922d61f2e82cdcb5110c2a730a3547fe698c594 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Fi=C5=A1era?= Date: Wed, 31 Aug 2022 21:50:47 +0200 Subject: [PATCH 061/107] [wasm] Fix JSExport on structs, records and expression bodied methos (#74763) - Fix generating qualified name for JSExport on structs, record classes and record structs. - Fix using expression bodied methods for JSExport. - Add unit test using all these variants with and without namespace and nested types. - Rewrite concatenating method name. --- .../JSImportGenerator/JSExportGenerator.cs | 2 +- .../JSImportGenerator/JSImportStubContext.cs | 26 +- .../JavaScript/JSImportExportTest.cs | 57 +++- .../JavaScript/JavaScriptTestHelper.cs | 298 +++++++++++++++++- .../JavaScript/JavaScriptTestHelper.mjs | 53 ++++ 5 files changed, 425 insertions(+), 11 deletions(-) diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSExportGenerator.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSExportGenerator.cs index 82fb93b871026b..f6590136448336 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSExportGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSExportGenerator.cs @@ -319,7 +319,7 @@ private static bool ShouldVisitNode(SyntaxNode syntaxNode) // Verify the method has no generic types or defined implementation // and is marked static and partial. if (methodSyntax.TypeParameterList is not null - || methodSyntax.Body is null + || (methodSyntax.Body is null && methodSyntax.ExpressionBody is null) || !methodSyntax.Modifiers.Any(SyntaxKind.StaticKeyword) || methodSyntax.Modifiers.Any(SyntaxKind.PartialKeyword)) { diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportStubContext.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportStubContext.cs index 84d3cc2b692fdb..ad8d837df24000 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportStubContext.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportStubContext.cs @@ -4,7 +4,9 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics; using System.Linq; +using System.Text; using System.Threading; using Microsoft.CodeAnalysis; @@ -16,6 +18,11 @@ namespace Microsoft.Interop.JavaScript { internal sealed class JSSignatureContext : IEquatable { + private static SymbolDisplayFormat s_typeNameFormat { get; } = new SymbolDisplayFormat( + globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, + typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes + ); + internal static readonly string GeneratorName = typeof(JSImportGenerator).Assembly.GetName().Name; internal static readonly string GeneratorVersion = typeof(JSImportGenerator).Assembly.GetName().Version.ToString(); @@ -118,14 +125,8 @@ public static JSSignatureContext Create( }; int typesHash = Math.Abs((int)hash); - - var fullName = $"{method.ContainingType.ToDisplayString()}.{method.Name}"; - string qualifiedName; - var ns = string.Join(".", method.ContainingType.ToDisplayParts().Where(p => p.Kind == SymbolDisplayPartKind.NamespaceName).Select(x => x.ToString()).ToArray()); - var cn = string.Join("/", method.ContainingType.ToDisplayParts().Where(p => p.Kind == SymbolDisplayPartKind.ClassName).Select(x => x.ToString()).ToArray()); - var qclasses = method.ContainingType.ContainingNamespace == null ? ns : ns + "." + cn; - qualifiedName = $"[{env.Compilation.AssemblyName}]{qclasses}:{method.Name}"; + string qualifiedName = GetFullyQualifiedMethodName(env, method); return new JSSignatureContext() { @@ -143,6 +144,17 @@ public static JSSignatureContext Create( }; } + private static string GetFullyQualifiedMethodName(StubEnvironment env, IMethodSymbol method) + { + // Mono style nested class name format. + string typeName = method.ContainingType.ToDisplayString(s_typeNameFormat).Replace(".", "/"); + + if (!method.ContainingType.ContainingNamespace.IsGlobalNamespace) + typeName = $"{method.ContainingType.ContainingNamespace.ToDisplayString()}.{typeName}"; + + return $"[{env.Compilation.AssemblyName}]{typeName}:{method.Name}"; + } + private static (ImmutableArray, IMarshallingGeneratorFactory) GenerateTypeInformation(IMethodSymbol method, GeneratorDiagnostics diagnostics, StubEnvironment env) { ImmutableArray useSiteAttributeParsers = ImmutableArray.Create(new JSMarshalAsAttributeParser(env.Compilation)); diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JSImportExportTest.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JSImportExportTest.cs index 71a795545f3317..a8966dcaf521d0 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JSImportExportTest.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JSImportExportTest.cs @@ -1199,7 +1199,62 @@ public void JsExportString(string value) public void JsExportStringNoNs() { var actual = JavaScriptTestHelper.invoke2_String("test", nameof(JavaScriptTestHelperNoNamespace.EchoString)); - Assert.Equal("test!", actual); + Assert.Equal("test51", actual); + } + + [Fact] + public void JsExportStructClassRecords() + { + var actual = JavaScriptTestHelper.invokeStructClassRecords("test"); + Assert.Equal(48, actual.Length); + Assert.Equal("test11", actual[0]); + Assert.Equal("test12", actual[1]); + Assert.Equal("test13", actual[2]); + Assert.Equal("test14", actual[3]); + Assert.Equal("test15", actual[4]); + Assert.Equal("test16", actual[5]); + Assert.Equal("test17", actual[6]); + Assert.Equal("test18", actual[7]); + Assert.Equal("test19", actual[8]); + Assert.Equal("test21", actual[9]); + Assert.Equal("test22", actual[10]); + Assert.Equal("test23", actual[11]); + Assert.Equal("test24", actual[12]); + Assert.Equal("test25", actual[13]); + Assert.Equal("test31", actual[14]); + Assert.Equal("test32", actual[15]); + Assert.Equal("test33", actual[16]); + Assert.Equal("test34", actual[17]); + Assert.Equal("test35", actual[18]); + Assert.Equal("test41", actual[19]); + Assert.Equal("test42", actual[20]); + Assert.Equal("test43", actual[21]); + Assert.Equal("test44", actual[22]); + Assert.Equal("test45", actual[23]); + Assert.Equal("test51", actual[24]); + Assert.Equal("test52", actual[25]); + Assert.Equal("test53", actual[26]); + Assert.Equal("test54", actual[27]); + Assert.Equal("test55", actual[28]); + Assert.Equal("test56", actual[29]); + Assert.Equal("test57", actual[30]); + Assert.Equal("test58", actual[31]); + Assert.Equal("test59", actual[32]); + Assert.Equal("test61", actual[33]); + Assert.Equal("test62", actual[34]); + Assert.Equal("test63", actual[35]); + Assert.Equal("test64", actual[36]); + Assert.Equal("test65", actual[37]); + Assert.Equal("test71", actual[38]); + Assert.Equal("test72", actual[39]); + Assert.Equal("test73", actual[40]); + Assert.Equal("test74", actual[41]); + Assert.Equal("test75", actual[42]); + Assert.Equal("test81", actual[43]); + Assert.Equal("test82", actual[44]); + Assert.Equal("test83", actual[45]); + Assert.Equal("test84", actual[46]); + Assert.Equal("test85", actual[47]); } [Fact] diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.cs index aaa5d16c2b8cdb..b5a89b7f48fe98 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.cs @@ -250,6 +250,9 @@ public static int EchoInt32([JSMarshalAs] int arg1) [JSImport("invoke2", "JavaScriptTestHelper")] [return: JSMarshalAs] internal static partial string invoke2_String([JSMarshalAs] string value, [JSMarshalAs] string name); + [JSImport("invokeStructClassRecords", "JavaScriptTestHelper")] + [return: JSMarshalAs>] + internal static partial string[] invokeStructClassRecords([JSMarshalAs] string value); [JSExport] [return: JSMarshalAs] public static string EchoString([JSMarshalAs] string arg1) @@ -935,11 +938,302 @@ public static async Task InitializeAsync() } } +namespace JavaScriptTestHelperNamespace +{ + public partial class JavaScriptTestHelper + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) + { + return message + "11"; + } + + public partial class NestedClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "12"; + + public partial class DoubleNestedClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "13"; + } + } + + public partial record class NestedRecordClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "14"; + + public partial record class DoubleNestedRecordClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "15"; + } + } + + public partial struct NestedStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "16"; + + public partial struct DoubleNestedStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "17"; + } + } + + public partial record struct NestedRecordStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "18"; + + public partial record struct DoubleNestedRecordStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "19"; + } + } + } + + public partial class JavaScriptTestHelperStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "21"; + + public partial class NestedClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "22"; + } + + public partial record class NestedRecordClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "23"; + } + + public partial struct NestedStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) + { + return message + "24"; + } + } + + public partial record struct NestedRecordStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "25"; + } + } + + public partial record class JavaScriptTestHelperRecordClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "31"; + + public partial class NestedClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "32"; + } + + public partial record class NestedRecordClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "33"; + } + + public partial struct NestedStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "34"; + } + + public partial record struct NestedRecordStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "35"; + } + } + + public partial record struct JavaScriptTestHelperRecordStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "41"; + + public partial class NestedClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "42"; + } + + public partial record class NestedRecordClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "43"; + } + + public partial struct NestedStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "44"; + } + + public partial record struct NestedRecordStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) + { + return message + "45"; + } + } + } +} + public partial class JavaScriptTestHelperNoNamespace { [System.Runtime.InteropServices.JavaScript.JSExport] - public static string EchoString(string message) + public static string EchoString(string message) => message + "51"; + + public partial class NestedClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "52"; + + public partial class DoubleNestedClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "53"; + } + } + + public partial record class NestedRecordClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "54"; + + public partial record class DoubleNestedRecordClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "55"; + } + } + + public partial struct NestedStruct { - return message + "!"; + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "56"; + + public partial struct DoubleNestedStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "57"; + } + } + + public partial record struct NestedRecordStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "58"; + + public partial record struct DoubleNestedRecordStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "59"; + } } } + +public partial class JavaScriptTestHelperStructNoNamespace +{ + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "61"; + + public partial class NestedClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "62"; + } + + public partial record class NestedRecordClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "63"; + } + + public partial struct NestedStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "64"; + } + + public partial record struct NestedRecordStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "65"; + } +} + +public partial record class JavaScriptTestHelperRecordClassNoNamespace +{ + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "71"; + + public partial class NestedClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "72"; + } + + public partial record class NestedRecordClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "73"; + } + + public partial struct NestedStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "74"; + } + + public partial record struct NestedRecordStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "75"; + } +} + +public partial record struct JavaScriptTestHelperRecordStructNoNamespace +{ + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "81"; + + public partial class NestedClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "82"; + } + + public partial record class NestedRecordClass + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "83"; + } + + public partial struct NestedStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "84"; + } + + public partial record struct NestedRecordStruct + { + [System.Runtime.InteropServices.JavaScript.JSExport] + public static string EchoString(string message) => message + "85"; + } +} \ No newline at end of file diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.mjs b/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.mjs index c3cc24ed73979d..314e715e16b815 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.mjs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.mjs @@ -171,6 +171,59 @@ export function invoke2(arg1, name) { return res; } +export function invokeStructClassRecords(arg1) { + return [ + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelper.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelper.NestedClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelper.NestedClass.DoubleNestedClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelper.NestedRecordClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelper.NestedRecordClass.DoubleNestedRecordClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelper.NestedStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelper.NestedStruct.DoubleNestedStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelper.NestedRecordStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelper.NestedRecordStruct.DoubleNestedRecordStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperStruct.NestedClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperStruct.NestedRecordClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperStruct.NestedStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperStruct.NestedRecordStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperRecordClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperRecordClass.NestedClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperRecordClass.NestedRecordClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperRecordClass.NestedStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperRecordClass.NestedRecordStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperRecordStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperRecordStruct.NestedClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperRecordStruct.NestedRecordClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperRecordStruct.NestedStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNamespace.JavaScriptTestHelperRecordStruct.NestedRecordStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNoNamespace.EchoString(arg1), + dllExports.JavaScriptTestHelperNoNamespace.NestedClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNoNamespace.NestedClass.DoubleNestedClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNoNamespace.NestedRecordClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNoNamespace.NestedRecordClass.DoubleNestedRecordClass.EchoString(arg1), + dllExports.JavaScriptTestHelperNoNamespace.NestedStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNoNamespace.NestedStruct.DoubleNestedStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNoNamespace.NestedRecordStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperNoNamespace.NestedRecordStruct.DoubleNestedRecordStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperStructNoNamespace.EchoString(arg1), + dllExports.JavaScriptTestHelperStructNoNamespace.NestedClass.EchoString(arg1), + dllExports.JavaScriptTestHelperStructNoNamespace.NestedRecordClass.EchoString(arg1), + dllExports.JavaScriptTestHelperStructNoNamespace.NestedStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperStructNoNamespace.NestedRecordStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperRecordClassNoNamespace.EchoString(arg1), + dllExports.JavaScriptTestHelperRecordClassNoNamespace.NestedClass.EchoString(arg1), + dllExports.JavaScriptTestHelperRecordClassNoNamespace.NestedRecordClass.EchoString(arg1), + dllExports.JavaScriptTestHelperRecordClassNoNamespace.NestedStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperRecordClassNoNamespace.NestedRecordStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperRecordStructNoNamespace.EchoString(arg1), + dllExports.JavaScriptTestHelperRecordStructNoNamespace.NestedClass.EchoString(arg1), + dllExports.JavaScriptTestHelperRecordStructNoNamespace.NestedRecordClass.EchoString(arg1), + dllExports.JavaScriptTestHelperRecordStructNoNamespace.NestedStruct.EchoString(arg1), + dllExports.JavaScriptTestHelperRecordStructNoNamespace.NestedRecordStruct.EchoString(arg1), + ]; +} + export async function awaitvoid(arg1) { // console.log("awaitvoid:" + typeof arg1); await arg1; From fccff6eadb6ae97c8f53e570c3996c46a915b545 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Wed, 31 Aug 2022 17:26:41 -0700 Subject: [PATCH 062/107] Revert change in StringBuilder.Append(char) (#74885) The change has a bad interaction with inlining heuristics. Fixes #74158. Partial revert of #67448. --- .../System.Private.CoreLib/src/System/Text/StringBuilder.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs index ba233dc62aadee..1c0c6f493b033a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs @@ -1052,10 +1052,10 @@ public StringBuilder Append(char value) int nextCharIndex = m_ChunkLength; char[] chars = m_ChunkChars; - if ((uint)nextCharIndex < (uint)chars.Length) + if ((uint)chars.Length > (uint)nextCharIndex) { chars[nextCharIndex] = value; - m_ChunkLength = nextCharIndex + 1; + m_ChunkLength++; } else { From 70a5445273b7ae6fa562c57dfe6b5ed001016626 Mon Sep 17 00:00:00 2001 From: Vladimir Sadov Date: Wed, 31 Aug 2022 18:17:32 -0700 Subject: [PATCH 063/107] [NativeAOT] Fix conservative stack reporting (#74849) * Enable and fix conservative stack reporting * When reporting conservatively any managed point is a safe point * fix OSX build * re-disable conservative stack reporting --- src/coreclr/nativeaot/Runtime/PalRedhawk.h | 18 +++++++++ src/coreclr/nativeaot/Runtime/gcrhenv.cpp | 6 +++ src/coreclr/nativeaot/Runtime/gcrhinterface.h | 1 + src/coreclr/nativeaot/Runtime/thread.cpp | 18 ++++++++- .../nativeaot/Runtime/unix/UnixContext.h | 37 +++++++++++++++++++ 5 files changed, 78 insertions(+), 2 deletions(-) diff --git a/src/coreclr/nativeaot/Runtime/PalRedhawk.h b/src/coreclr/nativeaot/Runtime/PalRedhawk.h index 5e8751f694544e..6b0df3f294c0b1 100644 --- a/src/coreclr/nativeaot/Runtime/PalRedhawk.h +++ b/src/coreclr/nativeaot/Runtime/PalRedhawk.h @@ -221,6 +221,14 @@ typedef struct DECLSPEC_ALIGN(16) _CONTEXT { #endif // UNIX_AMD64_ABI uintptr_t GetIp() { return Rip; } uintptr_t GetSp() { return Rsp; } + + template + void ForEachPossibleObjectRef(F lambda) + { + for (uint64_t* pReg = &Rax; pReg < &Rip; pReg++) + lambda((size_t*)pReg); + } + } CONTEXT, *PCONTEXT; #elif defined(HOST_ARM) @@ -406,6 +414,16 @@ typedef struct DECLSPEC_ALIGN(16) _CONTEXT { uintptr_t GetIp() { return Pc; } uintptr_t GetLr() { return Lr; } uintptr_t GetSp() { return Sp; } + + template + void ForEachPossibleObjectRef(F lambda) + { + for (uint64_t* pReg = &X0; pReg <= &X28; pReg++) + lambda((size_t*)pReg); + + // Lr can be used as a scratch register + lambda((size_t*)&Lr); + } } CONTEXT, *PCONTEXT; #elif defined(HOST_WASM) diff --git a/src/coreclr/nativeaot/Runtime/gcrhenv.cpp b/src/coreclr/nativeaot/Runtime/gcrhenv.cpp index b81422dc0d0d95..68b7a96c36fa1e 100644 --- a/src/coreclr/nativeaot/Runtime/gcrhenv.cpp +++ b/src/coreclr/nativeaot/Runtime/gcrhenv.cpp @@ -405,6 +405,12 @@ void RedhawkGCInterface::EnumGcRef(PTR_RtuObjectRef pRef, GCRefKind kind, void * GcEnumObject((PTR_OBJECTREF)pRef, flags, (EnumGcRefCallbackFunc *)pfnEnumCallback, (EnumGcRefScanContext *)pvCallbackData); } +// static +void RedhawkGCInterface::EnumGcRefConservatively(PTR_RtuObjectRef pRef, void* pfnEnumCallback, void* pvCallbackData) +{ + GcEnumObject((PTR_OBJECTREF)pRef, GC_CALL_INTERIOR | GC_CALL_PINNED, (EnumGcRefCallbackFunc*)pfnEnumCallback, (EnumGcRefScanContext*)pvCallbackData); +} + #ifndef DACCESS_COMPILE // static diff --git a/src/coreclr/nativeaot/Runtime/gcrhinterface.h b/src/coreclr/nativeaot/Runtime/gcrhinterface.h index 1379a208e16e06..3a70dcb5327c88 100644 --- a/src/coreclr/nativeaot/Runtime/gcrhinterface.h +++ b/src/coreclr/nativeaot/Runtime/gcrhinterface.h @@ -112,6 +112,7 @@ class RedhawkGCInterface static void WaitForGCCompletion(); static void EnumGcRef(PTR_RtuObjectRef pRef, GCRefKind kind, void * pfnEnumCallback, void * pvCallbackData); + static void EnumGcRefConservatively(PTR_RtuObjectRef pRef, void* pfnEnumCallback, void* pvCallbackData); static void BulkEnumGcObjRef(PTR_RtuObjectRef pRefs, uint32_t cRefs, void * pfnEnumCallback, void * pvCallbackData); diff --git a/src/coreclr/nativeaot/Runtime/thread.cpp b/src/coreclr/nativeaot/Runtime/thread.cpp index e3d214a6850cef..0c50b4f3b49719 100644 --- a/src/coreclr/nativeaot/Runtime/thread.cpp +++ b/src/coreclr/nativeaot/Runtime/thread.cpp @@ -476,6 +476,18 @@ void Thread::GcScanRootsWorker(void * pfnEnumCallback, void * pvCallbackData, St // Transition frame may contain callee saved registers that need to be reported as well PInvokeTransitionFrame* pTransitionFrame = GetTransitionFrame(); ASSERT(pTransitionFrame != NULL); + + if (pTransitionFrame == INTERRUPTED_THREAD_MARKER) + { + GetInterruptedContext()->ForEachPossibleObjectRef + ( + [&](size_t* pRef) + { + RedhawkGCInterface::EnumGcRefConservatively((PTR_RtuObjectRef)pRef, pfnEnumCallback, pvCallbackData); + } + ); + } + if (pTransitionFrame < pLowerBound) pLowerBound = pTransitionFrame; @@ -649,11 +661,13 @@ void Thread::HijackCallback(NATIVE_CONTEXT* pThreadContext, void* pThreadToHijac // we may be able to do GC stack walk right where the threads is now, // as long as the location is a GC safe point. ICodeManager* codeManager = runtime->GetCodeManagerForAddress(pvAddress); - if (codeManager->IsSafePoint(pvAddress)) + if (runtime->IsConservativeStackReportingEnabled() || + codeManager->IsSafePoint(pvAddress)) { // we may not be able to unwind in some locations, such as epilogs. // such locations should not contain safe points. - ASSERT(codeManager->IsUnwindable(pvAddress)); + // when scanning conservatively we do not need to unwind + ASSERT(codeManager->IsUnwindable(pvAddress) || runtime->IsConservativeStackReportingEnabled()); // if we are not given a thread to hijack // perform in-line wait on the current thread diff --git a/src/coreclr/nativeaot/Runtime/unix/UnixContext.h b/src/coreclr/nativeaot/Runtime/unix/UnixContext.h index 112dfcf86ad9d5..6e63733bc35cce 100644 --- a/src/coreclr/nativeaot/Runtime/unix/UnixContext.h +++ b/src/coreclr/nativeaot/Runtime/unix/UnixContext.h @@ -67,6 +67,22 @@ struct UNIX_CONTEXT uintptr_t GetIp() { return (uintptr_t)Pc(); } uintptr_t GetSp() { return (uintptr_t)Sp(); } + template + void ForEachPossibleObjectRef(F lambda) + { + // it is doubtful anyone would implement X0-X28 not as a contiguous array + // just in case - here are some asserts. + ASSERT(&X0() + 1 == &X1()); + ASSERT(&X0() + 10 == &X10()); + ASSERT(&X0() + 20 == &X20()); + + for (uint64_t* pReg = &X0(); pReg <= &X28(); pReg++) + lambda((size_t*)pReg); + + // Lr can be used as a scratch register + lambda((size_t*)&Lr()); + } + #elif defined(TARGET_AMD64) uint64_t& Rax(); uint64_t& Rcx(); @@ -88,6 +104,27 @@ struct UNIX_CONTEXT uintptr_t GetIp() { return (uintptr_t)Rip(); } uintptr_t GetSp() { return (uintptr_t)Rsp(); } + + template + void ForEachPossibleObjectRef(F lambda) + { + lambda((size_t*)&Rax()); + lambda((size_t*)&Rcx()); + lambda((size_t*)&Rdx()); + lambda((size_t*)&Rbx()); + lambda((size_t*)&Rsp()); + lambda((size_t*)&Rbp()); + lambda((size_t*)&Rsi()); + lambda((size_t*)&Rdi()); + lambda((size_t*)&R8()); + lambda((size_t*)&R9()); + lambda((size_t*)&R10()); + lambda((size_t*)&R11()); + lambda((size_t*)&R12()); + lambda((size_t*)&R13()); + lambda((size_t*)&R14()); + lambda((size_t*)&R15()); + } #else PORTABILITY_ASSERT("UNIX_CONTEXT"); #endif // TARGET_ARM From 6702dc5c7814e624a42ab4615224920a5635beeb Mon Sep 17 00:00:00 2001 From: Elinor Fung Date: Wed, 31 Aug 2022 18:45:26 -0700 Subject: [PATCH 064/107] Add host trace message to indicate runtimeconfig was not found (#74829) --- .../HostActivation.Tests/StandaloneAppActivation.cs | 10 ++++++++++ src/native/corehost/runtime_config.cpp | 3 ++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/installer/tests/HostActivation.Tests/StandaloneAppActivation.cs b/src/installer/tests/HostActivation.Tests/StandaloneAppActivation.cs index 34e853327e0fe3..d76559cb06e456 100644 --- a/src/installer/tests/HostActivation.Tests/StandaloneAppActivation.cs +++ b/src/installer/tests/HostActivation.Tests/StandaloneAppActivation.cs @@ -68,6 +68,7 @@ public void Running_Publish_Output_Standalone_EXE_with_no_DepsJson_and_no_Runtim File.Delete(fixture.TestProject.RuntimeConfigJson); File.Delete(fixture.TestProject.DepsJson); + // Make sure normal run succeeds and doesn't print any errors Command.Create(appExe) .CaptureStdErr() .CaptureStdOut() @@ -76,6 +77,15 @@ public void Running_Publish_Output_Standalone_EXE_with_no_DepsJson_and_no_Runtim // Note that this is an exact match - we don't expect any output from the host itself .And.HaveStdOut($"Hello World!{Environment.NewLine}{Environment.NewLine}.NET {sharedTestState.RepoDirectories.MicrosoftNETCoreAppVersion}{Environment.NewLine}") .And.NotHaveStdErr(); + + // Make sure tracing indicates there is no runtime config and no deps json + Command.Create(appExe) + .EnableTracingAndCaptureOutputs() + .Execute() + .Should().Pass() + .And.HaveStdOut($"Hello World!{Environment.NewLine}{Environment.NewLine}.NET {sharedTestState.RepoDirectories.MicrosoftNETCoreAppVersion}{Environment.NewLine}") + .And.HaveStdErrContaining($"Runtime config does not exist at [{fixture.TestProject.RuntimeConfigJson}]") + .And.HaveStdErrContaining($"Could not locate the dependencies manifest file [{fixture.TestProject.DepsJson}]"); } [Fact] diff --git a/src/native/corehost/runtime_config.cpp b/src/native/corehost/runtime_config.cpp index bbfd8f89653ae8..08e75fd61e016d 100644 --- a/src/native/corehost/runtime_config.cpp +++ b/src/native/corehost/runtime_config.cpp @@ -396,15 +396,16 @@ bool runtime_config_t::read_framework_array(const json_parser_t::value_t& framew bool runtime_config_t::ensure_parsed() { - trace::verbose(_X("Attempting to read runtime config: %s"), m_path.c_str()); if (!ensure_dev_config_parsed()) { trace::verbose(_X("Did not successfully parse the runtimeconfig.dev.json")); } + trace::verbose(_X("Attempting to read runtime config: %s"), m_path.c_str()); if (!bundle::info_t::config_t::probe(m_path) && !pal::realpath(&m_path, true)) { // Not existing is not an error. + trace::verbose(_X("Runtime config does not exist at [%s]"), m_path.c_str()); return true; } From d684343d7fc6e050d5c7fa11298dc1b6a5ee7a0e Mon Sep 17 00:00:00 2001 From: Ankit Jain Date: Wed, 31 Aug 2022 21:51:24 -0400 Subject: [PATCH 065/107] CI: Reduce the unrelated jobs running on wasm only PRs (#74601) - For PRs with strictly wasm only changes, disables running non-wasm jobs like mobile, or coreclr - For Wasm.Build.Tests, and debugger only PRs, runs only those jobs - Run coreclr jobs only if the PR has non-mono/wasm changes --- .../common/evaluate-changed-paths.yml | 3 +- .../common/evaluate-default-paths.yml | 129 ++++++++++++------ eng/pipelines/common/evaluate-paths-job.yml | 1 - .../common/templates/wasm-build-only.yml | 10 +- .../common/templates/wasm-build-tests.yml | 6 +- .../common/templates/wasm-debugger-tests.yml | 5 - .../common/templates/wasm-library-tests.yml | 20 +-- .../common/templates/wasm-runtime-tests.yml | 8 +- eng/pipelines/global-build.yml | 38 ++++++ eng/pipelines/runtime-community.yml | 12 +- .../runtime-extra-platforms-other.yml | 44 +++--- eng/pipelines/runtime-linker-tests.yml | 20 +++ eng/pipelines/runtime-llvm.yml | 14 +- eng/pipelines/runtime-staging.yml | 2 +- eng/pipelines/runtime.yml | 74 ++++++---- 15 files changed, 246 insertions(+), 140 deletions(-) diff --git a/eng/pipelines/common/evaluate-changed-paths.yml b/eng/pipelines/common/evaluate-changed-paths.yml index 28f8490663b661..318063260d8b6d 100644 --- a/eng/pipelines/common/evaluate-changed-paths.yml +++ b/eng/pipelines/common/evaluate-changed-paths.yml @@ -12,7 +12,8 @@ parameters: steps: - ${{ if ne(parameters.arguments[0], '') }}: - - script: eng/pipelines/evaluate-changed-paths.sh + - script: >- + eng/pipelines/evaluate-changed-paths.sh --azurevariable containsChange ${{ join(' ', parameters.arguments) }} displayName: Evaluate paths for ${{ parameters.subsetName }} diff --git a/eng/pipelines/common/evaluate-default-paths.yml b/eng/pipelines/common/evaluate-default-paths.yml index 75361e1d2c58f8..1d51eed9542651 100644 --- a/eng/pipelines/common/evaluate-default-paths.yml +++ b/eng/pipelines/common/evaluate-default-paths.yml @@ -2,6 +2,23 @@ parameters: extraSubsets: '' + # _* parameters are being used as a const array, + # do not set them when using the template + _const_paths: + _wasm_specific_only: [ + eng/testing/ProvisioningVersions.props + eng/testing/scenarios/BuildWasmAppsJobsList.txt + eng/testing/tests.wasm.targets + src/libraries/sendtohelix-wasm.targets + src/mono/nuget/Microsoft.NET.Runtime.WebAssembly.Sdk/* + src/mono/nuget/Microsoft.NET.Runtime.wasm.Sample.Mono/* + src/mono/wasi/* + src/mono/wasm/* + src/tasks/WasmAppBuilder/* + src/tasks/WasmBuildTasks/* + src/tasks/WorkloadBuildTasks/* + ] + jobs: - template: /eng/pipelines/common/evaluate-paths-job.yml parameters: @@ -28,13 +45,16 @@ jobs: - eng/pipelines/mono/* - eng/pipelines/libraries/* - eng/pipelines/common/evaluate-default-paths.yml - - subset: mono + + - subset: mono_excluding_wasm include: - src/libraries/System.Private.CoreLib/* - src/native/libs/Common/* - src/native/libs/System.Globalization.Native/* - src/native/libs/System.IO.Compression.Native/* exclude: + - ${{ parameters._const_paths._wasm_specific_only }} + - eng/Version.Details.xml - '*.md' - LICENSE.TXT @@ -46,11 +66,11 @@ jobs: - src/libraries/* - src/native/libs/* - src/tests/* - - src/mono/wasm/* - eng/pipelines/installer/* - eng/pipelines/coreclr/* - eng/pipelines/libraries/* - eng/pipelines/common/evaluate-default-paths.yml + - subset: libraries exclude: - eng/Version.Details.xml @@ -68,14 +88,10 @@ jobs: - eng/pipelines/mono/* - eng/pipelines/installer/* - eng/pipelines/common/evaluate-default-paths.yml + - subset: runtimetests include: - src/tests/* - exclude: - # wasm runtime changes will trigger all wasm jobs anyway - - src/mono/wasm/* - - src/mono/wasm/* - - eng/pipelines/common/evaluate-default-paths.yml - subset: installer include: - docs/manpages/* @@ -95,6 +111,7 @@ jobs: - eng/pipelines/mono/* - eng/pipelines/libraries/* - eng/pipelines/common/evaluate-default-paths.yml + # We have limited Apple Silicon testing capacity # We want PR testing on a narrower set of changes # Specifically runtime directories which are higher risk of @@ -108,61 +125,83 @@ jobs: - src/coreclr/jit/* - src/coreclr/pal/* - src/coreclr/vm/* - exclude: - - '*' - subset: coreclr_jit include: - src/coreclr/jit/* + + # + # ** WASM ** + # Changes in *only* Wasm.Build.Tests, or debugger, are very self-contained, + # so we try to avoid triggering only those relevants tests + # - subset: wasmbuildtests include: - - src/tasks/* - - src/mono/wasm/Directory.Build* - - src/mono/wasm/Wasm.Build.Tests/* - - src/mono/wasm/build/* - - src/mono/wasm/host/* - - src/mono/wasm/runtime/* - - src/mono/wasm/templates/* - - src/mono/nuget/Microsoft.NET.Workload.Mono.Toolchain.Manifest/* + - eng/Version.Details.xml + - eng/Versions.props + - eng/testing/scenarios/BuildWasmAppsJobsList.txt + - eng/testing/workloads-testing.targets + - src/libraries/sendtohelix* + - src/mono/mono/* + - src/mono/nuget/Microsoft.NET.Runtime.MonoAOTCompiler.Task/* + - src/mono/nuget/Microsoft.NET.Runtime.MonoTargets.Sdk/* - src/mono/nuget/Microsoft.NET.Runtime.WebAssembly.Sdk/* - src/mono/nuget/Microsoft.NET.Runtime.wasm.Sample.Mono/* + - src/mono/nuget/Microsoft.NET.Workload.Mono.Toolchain.Manifest/* - src/mono/nuget/Microsoft.NETCore.BrowserDebugHost.Transport/* - - src/mono/nuget/Microsoft.NET.Runtime.MonoAOTCompiler.Task/* - - src/mono/nuget/Microsoft.NET.Runtime.MonoTargets.Sdk/* - - src/mono/mono/* - - eng/testing/scenarios/BuildWasmAppsJobsList.txt - - eng/testing/workloads-testing.targets - - eng/Version.Details.xml - - eng/Versions.props + - src/mono/wasm/build/* - src/mono/wasm/emscripten-version.txt - - src/libraries/sendtohelix* - exclude: - - eng/pipelines/common/evaluate-default-paths.yml + - src/mono/wasm/host/* + - src/mono/wasm/runtime/* + - src/mono/wasm/templates/* + - src/mono/wasm/Wasm.Build.Tests/* + - src/tasks/* + - subset: wasmdebuggertests include: - - src/mono/wasm/debugger/* - - src/mono/wasm/runtime/* - - src/mono/wasm/Directory.Build* - - src/mono/wasm/debugger/Wasm.Debugger.Tests/* - eng/testing/ProvisioningVersions.props - src/mono/mono/* + - src/mono/wasm/debugger/* + - src/mono/wasm/runtime/* + + - subset: any_other_than_wasm_wbt_dbg exclude: - - eng/pipelines/common/evaluate-default-paths.yml - - subset: allwasm + - src/mono/wasm/Wasm.Build.Tests/* + - src/mono/wasm/debugger/* + + - subset: wasm_wbt_or_dbg include: - - eng/Version.Details.xml - - src/mono/*.proj - - src/mono/Directory.Build* - - src/mono/CMakeLists.txt - - src/mono/System.Private.CoreLib/* - - src/mono/mono/* - - src/mono/wasm/emscripten-version.txt - - src/mono/wasm/build/* - - src/mono/wasm/data/aot-tests/* - - src/mono/wasm/runtime/* - - src/mono/wasm/test-main.js - - src/mono/wasm/wasm.proj + - src/mono/wasm/Wasm.Build.Tests/* + - src/mono/wasm/debugger/* + + - subset: wasm + include: + - ${{ parameters._const_paths._wasm_specific_only }} + # other paths that should also trigger wasm jobs + - src/mono/* + + # anything other than wasm-specific paths + - subset: non_wasm exclude: + - ${{ parameters._const_paths._wasm_specific_only }} + + # having this ensures that change in evaluate-default-paths.yml won't + # trigger non-onlywasm jobs - eng/pipelines/common/evaluate-default-paths.yml + # anything other than mono, or wasm specific paths + - subset: non_mono_and_wasm + exclude: + - ${{ parameters._const_paths._wasm_specific_only }} + + - eng/testing/tests.mobile.targets + - src/mono/* + - src/tasks/AndroidAppBuilder/* + - src/tasks/AotCompilerTask/* + - src/tasks/AppleAppBuilder/* + - src/tasks/MonoTargetsTasks/* + - src/tasks/WasmAppBuilder/* + - src/tasks/WasmBuildTasks/* + - src/tasks/WorkloadBuildTasks/* + - ${{ if ne(parameters.extraSubsets, '') }}: - ${{ parameters.extraSubsets }} diff --git a/eng/pipelines/common/evaluate-paths-job.yml b/eng/pipelines/common/evaluate-paths-job.yml index 71f35bd4f9f4c7..670fba6c0c6e0d 100644 --- a/eng/pipelines/common/evaluate-paths-job.yml +++ b/eng/pipelines/common/evaluate-paths-job.yml @@ -24,7 +24,6 @@ parameters: # This example will include ALL path changes under src/libraries/ except the ones under src/libraries/*!System.Private.CoreLib/* paths: [] - jobs: - job: evaluate_paths displayName: Evaluate Paths diff --git a/eng/pipelines/common/templates/wasm-build-only.yml b/eng/pipelines/common/templates/wasm-build-only.yml index 32e17588a52928..a84ce107d02f24 100644 --- a/eng/pipelines/common/templates/wasm-build-only.yml +++ b/eng/pipelines/common/templates/wasm-build-only.yml @@ -19,21 +19,15 @@ jobs: platforms: ${{ parameters.platforms }} variables: # map dependencies variables to local variables - - name: librariesContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] - name: alwaysRunVar value: ${{ parameters.alwaysRun }} - - name: allWasmContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] - name: shouldRunOnDefaultPipelines value: $[ or( eq(variables['wasmDarcDependenciesChanged'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true)) + eq(dependencies.evaluate_paths.outputs['SetPathVars_wasm.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true)) ] jobParameters: isExtraPlatforms: ${{ parameters.isExtraPlatformsBuild }} diff --git a/eng/pipelines/common/templates/wasm-build-tests.yml b/eng/pipelines/common/templates/wasm-build-tests.yml index 07c253ed80bf1c..3ade2d7ce08dbd 100644 --- a/eng/pipelines/common/templates/wasm-build-tests.yml +++ b/eng/pipelines/common/templates/wasm-build-tests.yml @@ -20,17 +20,12 @@ jobs: shouldContinueOnError: ${{ parameters.shouldContinueOnError }} variables: # map dependencies variables to local variables - - name: wasmbuildtestsContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_wasmbuildtests.containsChange'] ] - - name: allWasmContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] - name: alwaysRunVar value: ${{ parameters.alwaysRun }} - name: shouldRunOnDefaultPipelines value: $[ or( eq(variables['wasmDarcDependenciesChanged'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_wasmbuildtests.containsChange'], true)) ] jobParameters: @@ -56,3 +51,4 @@ jobs: extraHelixArguments: /p:BrowserHost=$(_hostedOs) scenarios: - buildwasmapps + diff --git a/eng/pipelines/common/templates/wasm-debugger-tests.yml b/eng/pipelines/common/templates/wasm-debugger-tests.yml index 29e29e2a6aa27f..94fd9e024e6955 100644 --- a/eng/pipelines/common/templates/wasm-debugger-tests.yml +++ b/eng/pipelines/common/templates/wasm-debugger-tests.yml @@ -19,17 +19,12 @@ jobs: shouldContinueOnError: ${{ parameters.shouldContinueOnError }} variables: # map dependencies variables to local variables - - name: wasmdebuggertestsContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_wasmdebuggertests.containsChange'] ] - - name: allWasmContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] - name: alwaysRunVar value: ${{ parameters.alwaysRun }} - name: shouldRunOnDefaultPipelines value: $[ or( eq(variables['wasmDarcDependenciesChanged'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_wasmdebuggertests.containsChange'], true)) ] jobParameters: diff --git a/eng/pipelines/common/templates/wasm-library-tests.yml b/eng/pipelines/common/templates/wasm-library-tests.yml index 9981d8727a85c5..782ee9c9590638 100644 --- a/eng/pipelines/common/templates/wasm-library-tests.yml +++ b/eng/pipelines/common/templates/wasm-library-tests.yml @@ -26,22 +26,24 @@ jobs: shouldContinueOnError: ${{ parameters.shouldContinueOnError }} variables: # map dependencies variables to local variables - - name: librariesContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] - name: alwaysRunVar value: ${{ parameters.alwaysRun }} - - name: allWasmContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] - name: shouldRunOnDefaultPipelines value: $[ or( eq(variables['wasmDarcDependenciesChanged'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true)) + and( + ne(variables['onlyWBTOrDbgTestHaveChanges'], true), + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_wasm.containsChange'], true)))) ] + - name: onlyWBTOrDbgTestHaveChanges + value: + and( + eq(dependencies.evaluate_paths.outputs.SetPathVars_wasm_wbt_or_dbg.containsChange, true), + ne(dependencies.evaluate_paths.outputs.SetPathVars_any_other_than_wasm_wbt_dbg.containsChange, true)) jobParameters: isExtraPlatforms: ${{ parameters.isExtraPlatformsBuild }} testGroup: innerloop diff --git a/eng/pipelines/common/templates/wasm-runtime-tests.yml b/eng/pipelines/common/templates/wasm-runtime-tests.yml index 903235e75c1021..8c091c165debfa 100644 --- a/eng/pipelines/common/templates/wasm-runtime-tests.yml +++ b/eng/pipelines/common/templates/wasm-runtime-tests.yml @@ -17,8 +17,6 @@ jobs: runtimeFlavor: mono platforms: ${{ parameters.platforms }} variables: - - name: allWasmContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'] ] - name: alwaysRunVar value: ${{ parameters.alwaysRun }} - name: timeoutPerTestInMinutes @@ -29,9 +27,8 @@ jobs: value: $[ or( eq(variables['wasmDarcDependenciesChanged'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_allwasm.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true)) + eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_wasm.containsChange'], true)) ] jobParameters: testGroup: innerloop @@ -40,6 +37,7 @@ jobs: runtimeVariant: monointerpreter buildArgs: -s mono+libs -c $(_BuildConfig) timeoutInMinutes: 180 + # FIXME: will get triggered by only wbt/dbg changes # if !alwaysRun, then: # if this is runtime-wasm (isWasmOnlyBuild): # - then run only if it would not have run on default pipelines (based diff --git a/eng/pipelines/global-build.yml b/eng/pipelines/global-build.yml index 83e8580068af58..1d483990e19306 100644 --- a/eng/pipelines/global-build.yml +++ b/eng/pipelines/global-build.yml @@ -25,7 +25,17 @@ pr: - PATENTS.TXT - THIRD-PARTY-NOTICES.TXT +variables: + - template: /eng/pipelines/common/variables.yml + jobs: + +# +# Evaluate paths +# +- ${{ if eq(variables.dependOnEvaluatePaths, true) }}: + - template: /eng/pipelines/common/evaluate-default-paths.yml + # # Build with Release config and Debug runtimeConfiguration # @@ -42,6 +52,10 @@ jobs: nameSuffix: Runtime_Debug buildArgs: -c release -runtimeConfiguration debug timeoutInMinutes: 90 + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) # # Build with Release config and runtimeConfiguration with MSBuild generator @@ -57,6 +71,10 @@ jobs: nameSuffix: MSBuild_CMake buildArgs: -c Release -msbuild timeoutInMinutes: 90 + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) # # Build with Debug config and Release runtimeConfiguration @@ -72,6 +90,10 @@ jobs: nameSuffix: Runtime_Release buildArgs: -c debug -runtimeConfiguration release timeoutInMinutes: 90 + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) # # Build with RuntimeFlavor only. This exercise code paths where only RuntimeFlavor is @@ -88,6 +110,10 @@ jobs: nameSuffix: RuntimeFlavor_Mono buildArgs: /p:RuntimeFlavor=Mono timeoutInMinutes: 90 + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) # # Build Mono + Libraries. This exercises the code path where we build libraries without @@ -104,6 +130,10 @@ jobs: nameSuffix: Mono_Libraries buildArgs: -subset mono+libs /p:RuntimeFlavor=Mono timeoutInMinutes: 90 + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) # # Build Libraries AllConfigurations. This exercises the code path where we build libraries for all @@ -119,6 +149,10 @@ jobs: nameSuffix: Libraries_AllConfigurations buildArgs: -subset libs -allconfigurations timeoutInMinutes: 90 + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) # # SourceBuild Build @@ -132,3 +166,7 @@ jobs: jobParameters: nameSuffix: SourceBuild timeoutInMinutes: 90 + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) diff --git a/eng/pipelines/runtime-community.yml b/eng/pipelines/runtime-community.yml index 3eace877e55222..7b2908c9f7d650 100644 --- a/eng/pipelines/runtime-community.yml +++ b/eng/pipelines/runtime-community.yml @@ -55,7 +55,7 @@ jobs: - name: librariesContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'] ] jobParameters: testGroup: innerloop nameSuffix: AllSubsets_Mono @@ -64,7 +64,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml @@ -93,7 +93,7 @@ jobs: - name: librariesContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'] ] jobParameters: testScope: innerloop nameSuffix: AllSubsets_Mono @@ -102,7 +102,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # @@ -121,7 +121,7 @@ jobs: - name: librariesContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'] ] jobParameters: testScope: innerloop nameSuffix: AllSubsets_Mono @@ -130,7 +130,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) ${{ if eq(variables['isRollingBuild'], true) }}: # extra steps, run tests diff --git a/eng/pipelines/runtime-extra-platforms-other.yml b/eng/pipelines/runtime-extra-platforms-other.yml index 983f239077762f..95fe8858ba2ba5 100644 --- a/eng/pipelines/runtime-extra-platforms-other.yml +++ b/eng/pipelines/runtime-extra-platforms-other.yml @@ -139,7 +139,7 @@ jobs: - name: librariesContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'] ] jobParameters: testScope: innerloop nameSuffix: AllSubsets_Mono @@ -148,7 +148,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests @@ -183,7 +183,7 @@ jobs: - name: librariesContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'] ] jobParameters: testGroup: innerloop nameSuffix: AllSubsets_Mono @@ -192,7 +192,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests @@ -225,7 +225,7 @@ jobs: - name: librariesContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'] ] jobParameters: testGroup: innerloop nameSuffix: AllSubsets_Mono @@ -235,7 +235,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml @@ -267,7 +267,7 @@ jobs: - name: librariesContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'] ] jobParameters: testGroup: innerloop nameSuffix: AllSubsets_Mono @@ -276,7 +276,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests @@ -308,7 +308,7 @@ jobs: - name: librariesContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'] ] jobParameters: testGroup: innerloop nameSuffix: AllSubsets_Mono_AppSandbox @@ -317,7 +317,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml @@ -349,7 +349,7 @@ jobs: - name: librariesContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'] ] jobParameters: testGroup: innerloop nameSuffix: AllSubsets_Mono @@ -358,7 +358,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests @@ -390,7 +390,7 @@ jobs: - name: librariesContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'] ] jobParameters: testGroup: innerloop nameSuffix: AllSubsets_Mono @@ -399,7 +399,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml @@ -444,7 +444,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests @@ -470,7 +470,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # @@ -487,7 +487,7 @@ jobs: testGroup: innerloop condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -520,7 +520,7 @@ jobs: timeoutInMinutes: 240 condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests @@ -560,7 +560,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/common/templates/runtimes/android-runtime-and-send-to-helix.yml @@ -598,7 +598,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # don't run tests on PRs until we can get significantly more devices # Turn off the testing for now, until https://github.com/dotnet/runtime/issues/60128 gets resolved @@ -628,7 +628,7 @@ jobs: runtimeVariant: minijit condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -651,6 +651,6 @@ jobs: runtimeVariant: monointerpreter condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(variables['isRollingBuild'], true)) diff --git a/eng/pipelines/runtime-linker-tests.yml b/eng/pipelines/runtime-linker-tests.yml index 770f6cec01e1cb..bf72b50bfe18e7 100644 --- a/eng/pipelines/runtime-linker-tests.yml +++ b/eng/pipelines/runtime-linker-tests.yml @@ -45,7 +45,17 @@ pr: - PATENTS.TXT - THIRD-PARTY-NOTICES.TXT +variables: + - template: /eng/pipelines/common/variables.yml + jobs: + +# +# Evaluate paths +# +- ${{ if eq(variables.dependOnEvaluatePaths, true) }}: + - template: /eng/pipelines/common/evaluate-default-paths.yml + # # Build Release config vertical for Windows, Linux, Linux musl and OSX # @@ -61,6 +71,10 @@ jobs: testGroup: innerloop timeoutInMinutes: 120 nameSuffix: Runtime_Release + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) buildArgs: -s clr+libs -c $(_BuildConfig) extraStepsTemplate: /eng/pipelines/libraries/execute-trimming-tests-steps.yml @@ -78,6 +92,12 @@ jobs: timeoutInMinutes: 120 nameSuffix: Runtime_Release buildArgs: -s mono+libs -c $(_BuildConfig) -p:WasmBuildNative=false + condition: + or( + eq(variables['isRollingBuild'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['DarcDependenciesChanged.Microsoft_NET_ILLink_Tasks'], true)) extraStepsTemplate: /eng/pipelines/libraries/execute-trimming-tests-steps.yml extraStepsParameters: extraTestArgs: '/p:WasmBuildNative=false' diff --git a/eng/pipelines/runtime-llvm.yml b/eng/pipelines/runtime-llvm.yml index 0a68de11407d84..9f58d2bab8f605 100644 --- a/eng/pipelines/runtime-llvm.yml +++ b/eng/pipelines/runtime-llvm.yml @@ -77,7 +77,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -97,7 +97,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -120,7 +120,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -139,7 +139,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -160,7 +160,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # @@ -185,7 +185,7 @@ jobs: runtimeVariant: llvmaot condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -210,6 +210,6 @@ jobs: runtimeVariant: llvmfullaot condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(variables['isRollingBuild'], true)) diff --git a/eng/pipelines/runtime-staging.yml b/eng/pipelines/runtime-staging.yml index e4cf2237a70707..9aa56c919a7cdb 100644 --- a/eng/pipelines/runtime-staging.yml +++ b/eng/pipelines/runtime-staging.yml @@ -88,7 +88,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) ${{ if eq(variables['isRollingBuild'], true) }}: # extra steps, run tests diff --git a/eng/pipelines/runtime.yml b/eng/pipelines/runtime.yml index 9dc55e45cc6b8b..64ce210d6fbb75 100644 --- a/eng/pipelines/runtime.yml +++ b/eng/pipelines/runtime.yml @@ -106,7 +106,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), @@ -155,6 +155,11 @@ jobs: - FreeBSD_x64 jobParameters: testGroup: innerloop + # Don't run these when we have only wasm changes on PRs + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) # # Build CoreCLR Formatting Job @@ -307,7 +312,8 @@ jobs: isOfficialBuild: ${{ variables.isOfficialBuild }} condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -330,7 +336,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -349,7 +355,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -460,7 +466,7 @@ jobs: - name: librariesContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'] ] jobParameters: testGroup: innerloop nameSuffix: AllSubsets_Mono @@ -469,7 +475,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests @@ -503,7 +509,7 @@ jobs: - name: librariesContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'] ] jobParameters: testGroup: innerloop nameSuffix: AllSubsets_Mono @@ -512,7 +518,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) # extra steps, run tests @@ -544,7 +550,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -564,7 +570,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -587,7 +593,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -606,7 +612,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -633,7 +639,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # @@ -663,7 +669,8 @@ jobs: - Browser condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -690,7 +697,7 @@ jobs: - MacCatalyst condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -714,7 +721,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # @@ -734,7 +741,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # @@ -754,7 +761,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # @@ -774,6 +781,11 @@ jobs: - windows_arm - windows_arm64 - windows_x86 + jobParameters: + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -789,6 +801,10 @@ jobs: - FreeBSD_x64 jobParameters: testScope: innerloop + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) # # Libraries debug build that only runs when coreclr is changed @@ -871,6 +887,10 @@ jobs: jobParameters: liveRuntimeBuildConfig: release liveLibrariesBuildConfig: Release + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) - template: /eng/pipelines/installer/installer-matrix.yml parameters: @@ -886,6 +906,10 @@ jobs: jobParameters: liveRuntimeBuildConfig: release liveLibrariesBuildConfig: ${{ variables.debugOnPrReleaseOnRolling }} + condition: + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_non_mono_and_wasm.containsChange'], true), + eq(variables['isRollingBuild'], true)) # # CoreCLR Test builds using live libraries release build @@ -978,7 +1002,7 @@ jobs: testGroup: innerloop condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -1002,7 +1026,7 @@ jobs: runtimeVariant: minijit condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -1025,7 +1049,7 @@ jobs: runtimeVariant: monointerpreter condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(variables['isRollingBuild'], true)) # @@ -1050,7 +1074,7 @@ jobs: runtimeVariant: llvmaot condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -1075,7 +1099,7 @@ jobs: runtimeVariant: llvmfullaot condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(variables['isRollingBuild'], true)) @@ -1102,7 +1126,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # @@ -1128,7 +1152,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono_excluding_wasm.containsChange'], true), eq(variables['isRollingBuild'], true)) # From a919d611e832bfee46fc34762f5ded2006c9f16d Mon Sep 17 00:00:00 2001 From: Pavel Savara Date: Thu, 1 Sep 2022 07:19:07 +0200 Subject: [PATCH 066/107] [wasm] JS interop without JS code gen - CSP friendly (#74441) - interpret signature data instead of generating the JS code - tests --- .../src/Interop/Browser/Interop.Runtime.cs | 2 + .../JavaScript/JSFunctionBinding.cs | 20 +- .../JavaScript/JSImportExportTest.cs | 14 ++ .../JavaScript/JavaScriptTestHelper.cs | 42 ++++ .../JavaScript/JavaScriptTestHelper.mjs | 25 ++ src/mono/sample/wasm/Directory.Build.targets | 7 +- src/mono/wasm/runtime/corebindings.c | 2 + src/mono/wasm/runtime/es6/dotnet.es6.lib.js | 1 + src/mono/wasm/runtime/exports-linker.ts | 3 +- src/mono/wasm/runtime/invoke-cs.ts | 200 ++++++++++++---- src/mono/wasm/runtime/invoke-js.ts | 223 +++++++++++++----- src/mono/wasm/runtime/marshal-to-cs.ts | 119 +++------- src/mono/wasm/runtime/marshal-to-js.ts | 123 +++------- src/mono/wasm/runtime/marshal.ts | 1 + .../wasm/runtime/net6-legacy/corebindings.ts | 6 +- src/mono/wasm/runtime/types.ts | 9 +- 16 files changed, 501 insertions(+), 296 deletions(-) diff --git a/src/libraries/Common/src/Interop/Browser/Interop.Runtime.cs b/src/libraries/Common/src/Interop/Browser/Interop.Runtime.cs index 693a88b8e9ff95..27762b7ac5d102 100644 --- a/src/libraries/Common/src/Interop/Browser/Interop.Runtime.cs +++ b/src/libraries/Common/src/Interop/Browser/Interop.Runtime.cs @@ -15,6 +15,8 @@ internal static unsafe partial class Runtime [MethodImpl(MethodImplOptions.InternalCall)] public static extern void InvokeJSFunction(IntPtr bound_function_js_handle, void* data); [MethodImpl(MethodImplOptions.InternalCall)] + public static extern void InvokeImport(IntPtr fn_handle, void* data); + [MethodImpl(MethodImplOptions.InternalCall)] public static extern unsafe void BindCSFunction(in string fully_qualified_name, int signature_hash, void* signature, out int is_exception, out object result); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void MarshalPromise(void* data); diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSFunctionBinding.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSFunctionBinding.cs index 8ec27641bcaf03..a7c099a5aa8f81 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSFunctionBinding.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSFunctionBinding.cs @@ -20,7 +20,7 @@ public sealed partial class JSFunctionBinding #region intentionally opaque internal structure internal unsafe JSBindingHeader* Header; internal unsafe JSBindingType* Sigs;// points to first arg, not exception, not result - internal JSObject? JSFunction; + internal IntPtr FnHandle; [StructLayout(LayoutKind.Sequential, Pack = 4)] internal struct JSBindingHeader @@ -121,7 +121,7 @@ internal unsafe JSBindingType this[int position] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void InvokeJS(JSFunctionBinding signature, Span arguments) { - InvokeJSImpl(signature.JSFunction!, arguments); + InvokeImportImpl(signature.FnHandle, arguments); } /// @@ -167,6 +167,20 @@ internal static unsafe void InvokeJSImpl(JSObject jsFunction, Span arguments) + { + fixed (JSMarshalerArgument* ptr = arguments) + { + Interop.Runtime.InvokeImport(fnHandle, ptr); + ref JSMarshalerArgument exceptionArg = ref arguments[0]; + if (exceptionArg.slot.Type != MarshalerType.None) + { + JSHostImplementation.ThrowException(ref exceptionArg); + } + } + } + [MethodImpl(MethodImplOptions.NoInlining)] internal static unsafe JSFunctionBinding BindJSFunctionImpl(string functionName, string moduleName, ReadOnlySpan signatures) { @@ -176,7 +190,7 @@ internal static unsafe JSFunctionBinding BindJSFunctionImpl(string functionName, if (isException != 0) throw new JSException((string)exceptionMessage); - signature.JSFunction = JSHostImplementation.CreateCSOwnedProxy(jsFunctionHandle); + signature.FnHandle = jsFunctionHandle; return signature; } diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JSImportExportTest.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JSImportExportTest.cs index a8966dcaf521d0..dded93a4059ab7 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JSImportExportTest.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JSImportExportTest.cs @@ -79,6 +79,20 @@ public unsafe void OutOfRange() Assert.Contains("Overflow: value 9007199254740991 is out of -2147483648 2147483647 range", ex.Message); } + [Fact] + public unsafe void OptimizedPaths() + { + JavaScriptTestHelper.optimizedReached = 0; + JavaScriptTestHelper.invoke0V(); + Assert.Equal(1, JavaScriptTestHelper.optimizedReached); + JavaScriptTestHelper.invoke1V(42); + Assert.Equal(43, JavaScriptTestHelper.optimizedReached); + Assert.Equal(124, JavaScriptTestHelper.invoke1R(123)); + Assert.Equal(43 + 123, JavaScriptTestHelper.optimizedReached); + Assert.Equal(32, JavaScriptTestHelper.invoke2R(15, 16)); + Assert.Equal(43 + 123 + 31, JavaScriptTestHelper.optimizedReached); + } + #region Get/Set Property diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.cs index b5a89b7f48fe98..cca24202da298d 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.cs @@ -45,6 +45,48 @@ public static DateTime Now() return DateTime.Now; } + // the methods in the region have signature for which we have optimized path in the call marshaler + // it's the combination of number of arguments and void vs result + // see mono_wasm_bind_js_function and mono_wasm_bind_cs_function + #region Optimized + + public static int optimizedReached = 0; + [JSExport] + public static void Optimized0V() + { + optimizedReached++; + } + [JSImport("invoke0V", "JavaScriptTestHelper")] + public static partial void invoke0V(); + + [JSExport] + public static void Optimized1V(int a1) + { + optimizedReached+= a1; + } + [JSImport("invoke1V", "JavaScriptTestHelper")] + public static partial void invoke1V(int a1); + + [JSExport] + public static int Optimized1R(int a1) + { + optimizedReached += a1; + return a1 + 1; + } + [JSImport("invoke1R", "JavaScriptTestHelper")] + public static partial int invoke1R(int a1); + + [JSExport] + public static int Optimized2R(int a1, int a2) + { + optimizedReached += a1+ a2; + return a1 + a2 +1; + } + [JSImport("invoke2R", "JavaScriptTestHelper")] + public static partial int invoke2R(int a1, int a2); + + #endregion + [JSImport("create_function", "JavaScriptTestHelper")] [return: JSMarshalAs>] public static partial Func createMath([JSMarshalAs] string a, [JSMarshalAs] string b, [JSMarshalAs] string code); diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.mjs b/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.mjs index 314e715e16b815..db9d18c5adbc35 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.mjs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/tests/System.Runtime.InteropServices.JavaScript.UnitTests/System/Runtime/InteropServices/JavaScript/JavaScriptTestHelper.mjs @@ -147,6 +147,31 @@ export function getClass1() { return cname; } let dllExports; + +export function invoke0V() { + const JavaScriptTestHelper = dllExports.System.Runtime.InteropServices.JavaScript.Tests.JavaScriptTestHelper; + const fn = JavaScriptTestHelper['Optimized0V']; + fn(); +} + +export function invoke1V(arg1) { + const JavaScriptTestHelper = dllExports.System.Runtime.InteropServices.JavaScript.Tests.JavaScriptTestHelper; + const fn = JavaScriptTestHelper['Optimized1V']; + fn(arg1); +} + +export function invoke1R(arg1) { + const JavaScriptTestHelper = dllExports.System.Runtime.InteropServices.JavaScript.Tests.JavaScriptTestHelper; + const fn = JavaScriptTestHelper['Optimized1R']; + return fn(arg1); +} + +export function invoke2R(arg1, arg2) { + const JavaScriptTestHelper = dllExports.System.Runtime.InteropServices.JavaScript.Tests.JavaScriptTestHelper; + const fn = JavaScriptTestHelper['Optimized2R']; + return fn(arg1, arg2); +} + export function invoke1(arg1, name) { if (globalThis.gc) { // console.log('globalThis.gc'); diff --git a/src/mono/sample/wasm/Directory.Build.targets b/src/mono/sample/wasm/Directory.Build.targets index cf7244f6ecb464..c01bfada90c654 100644 --- a/src/mono/sample/wasm/Directory.Build.targets +++ b/src/mono/sample/wasm/Directory.Build.targets @@ -41,7 +41,12 @@ - + + diff --git a/src/mono/wasm/runtime/corebindings.c b/src/mono/wasm/runtime/corebindings.c index 1d4267a6fb8db7..c9ebdc01abd23b 100644 --- a/src/mono/wasm/runtime/corebindings.c +++ b/src/mono/wasm/runtime/corebindings.c @@ -30,6 +30,7 @@ extern void mono_wasm_typed_array_from_ref (int ptr, int begin, int end, int byt extern void mono_wasm_bind_js_function(MonoString **function_name, MonoString **module_name, void *signature, int* function_js_handle, int *is_exception, MonoObject **result); extern void mono_wasm_invoke_bound_function(int function_js_handle, void *data); +extern void mono_wasm_invoke_import(int fn_handle, void *data); extern void mono_wasm_bind_cs_function(MonoString **fully_qualified_name, int signature_hash, void* signatures, int *is_exception, MonoObject **result); extern void mono_wasm_marshal_promise(void *data); @@ -49,6 +50,7 @@ void core_initialize_internals () mono_add_internal_call ("Interop/Runtime::BindJSFunction", mono_wasm_bind_js_function); mono_add_internal_call ("Interop/Runtime::InvokeJSFunction", mono_wasm_invoke_bound_function); + mono_add_internal_call ("Interop/Runtime::InvokeImport", mono_wasm_invoke_import); mono_add_internal_call ("Interop/Runtime::BindCSFunction", mono_wasm_bind_cs_function); mono_add_internal_call ("Interop/Runtime::MarshalPromise", mono_wasm_marshal_promise); mono_add_internal_call ("Interop/Runtime::RegisterGCRoot", mono_wasm_register_root); diff --git a/src/mono/wasm/runtime/es6/dotnet.es6.lib.js b/src/mono/wasm/runtime/es6/dotnet.es6.lib.js index bde650aea36eca..9cf4b57ebb724b 100644 --- a/src/mono/wasm/runtime/es6/dotnet.es6.lib.js +++ b/src/mono/wasm/runtime/es6/dotnet.es6.lib.js @@ -88,6 +88,7 @@ const linked_functions = [ "mono_wasm_compile_function_ref", "mono_wasm_bind_js_function", "mono_wasm_invoke_bound_function", + "mono_wasm_invoke_import", "mono_wasm_bind_cs_function", "mono_wasm_marshal_promise", diff --git a/src/mono/wasm/runtime/exports-linker.ts b/src/mono/wasm/runtime/exports-linker.ts index 22f8a66cdee89f..3c030f2f4f9307 100644 --- a/src/mono/wasm/runtime/exports-linker.ts +++ b/src/mono/wasm/runtime/exports-linker.ts @@ -6,7 +6,7 @@ import { mono_wasm_fire_debugger_agent_message, mono_wasm_debugger_log, mono_was import { mono_wasm_release_cs_owned_object } from "./gc-handles"; import { mono_wasm_load_icu_data, mono_wasm_get_icudt_name } from "./icu"; import { mono_wasm_bind_cs_function } from "./invoke-cs"; -import { mono_wasm_bind_js_function, mono_wasm_invoke_bound_function } from "./invoke-js"; +import { mono_wasm_bind_js_function, mono_wasm_invoke_bound_function, mono_wasm_invoke_import } from "./invoke-js"; import { mono_wasm_typed_array_from_ref } from "./net6-legacy/buffers"; import { mono_wasm_invoke_js_blazor, mono_wasm_invoke_js_with_args_ref, mono_wasm_get_object_property_ref, mono_wasm_set_object_property_ref, @@ -70,6 +70,7 @@ export function export_linker(): any { mono_wasm_typed_array_from_ref, mono_wasm_bind_js_function, mono_wasm_invoke_bound_function, + mono_wasm_invoke_import, mono_wasm_bind_cs_function, mono_wasm_marshal_promise, diff --git a/src/mono/wasm/runtime/invoke-cs.ts b/src/mono/wasm/runtime/invoke-cs.ts index 569f0aa83c34c6..581573c6b63c76 100644 --- a/src/mono/wasm/runtime/invoke-cs.ts +++ b/src/mono/wasm/runtime/invoke-cs.ts @@ -2,27 +2,22 @@ // The .NET Foundation licenses this file to you under the MIT license. import { Module, runtimeHelpers } from "./imports"; -import { generate_arg_marshal_to_cs } from "./marshal-to-cs"; -import { marshal_exception_to_js, generate_arg_marshal_to_js } from "./marshal-to-js"; +import { bind_arg_marshal_to_cs } from "./marshal-to-cs"; +import { marshal_exception_to_js, bind_arg_marshal_to_js } from "./marshal-to-js"; import { - JavaScriptMarshalerArgSize, - JSMarshalerTypeSize, JSMarshalerSignatureHeaderSize, - get_arg, get_sig, - get_signature_argument_count, is_args_exception, bound_cs_function_symbol, get_signature_version, MarshalerType, alloc_stack_frame, + get_arg, get_sig, get_signature_argument_count, is_args_exception, + bound_cs_function_symbol, get_signature_version, alloc_stack_frame, get_signature_type, } from "./marshal"; import { mono_wasm_new_external_root } from "./roots"; import { conv_string, conv_string_root } from "./strings"; -import { mono_assert, MonoObjectRef, MonoStringRef, MonoString, MonoObject, MonoMethod, JSMarshalerArguments, JSFunctionSignature } from "./types"; +import { mono_assert, MonoObjectRef, MonoStringRef, MonoString, MonoObject, MonoMethod, JSMarshalerArguments, JSFunctionSignature, BoundMarshalerToCs, BoundMarshalerToJs } from "./types"; import { Int32Ptr } from "./types/emscripten"; import cwraps from "./cwraps"; import { assembly_load } from "./class-loader"; import { wrap_error_root } from "./invoke-js"; -const exportedMethods = new Map(); - export function mono_wasm_bind_cs_function(fully_qualified_name: MonoStringRef, signature_hash: number, signature: JSFunctionSignature, is_exception: Int32Ptr, result_address: MonoObjectRef): void { const fqn_root = mono_wasm_new_external_root(fully_qualified_name), resultRoot = mono_wasm_new_external_root(result_address); - const anyModule = Module as any; try { const version = get_signature_version(signature); mono_assert(version === 1, () => `Signature version ${version} mismatch.`); @@ -50,54 +45,44 @@ export function mono_wasm_bind_cs_function(fully_qualified_name: MonoStringRef, if (!method) throw new Error(`Could not find method: ${wrapper_name} in ${klass} [${assembly}]`); - const closure: any = { - method, signature, - stackSave: anyModule.stackSave, stackRestore: anyModule.stackRestore, - alloc_stack_frame, - invoke_method_and_handle_exception - }; - const bound_js_function_name = "_bound_cs_" + `${namespace}_${classname}_${methodname}`.replace(/\./g, "_").replace(/\//g, "_"); - let body = `//# sourceURL=https://dotnet.generated.invalid/${bound_js_function_name} \n`; - let bodyToCs = ""; - let converter_names = ""; - + const arg_marshalers: (BoundMarshalerToCs)[] = new Array(args_count); for (let index = 0; index < args_count; index++) { - const arg_offset = (index + 2) * JavaScriptMarshalerArgSize; - const sig_offset = (index + 2) * JSMarshalerTypeSize + JSMarshalerSignatureHeaderSize; const sig = get_sig(signature, index + 2); - const { converters, call_body } = generate_arg_marshal_to_cs(sig, index + 2, arg_offset, sig_offset, `arguments[${index}]`, closure); - converter_names += converters; - bodyToCs += call_body; + const marshaler_type = get_signature_type(sig); + const arg_marshaler = bind_arg_marshal_to_cs(sig, marshaler_type, index + 2); + mono_assert(arg_marshaler, "ERR43: argument marshaler must be resolved"); + arg_marshalers[index] = arg_marshaler; } - const { converters: res_converters, call_body: res_call_body, marshaler_type: res_marshaler_type } = generate_arg_marshal_to_js(get_sig(signature, 1), 1, JavaScriptMarshalerArgSize, JSMarshalerTypeSize + JSMarshalerSignatureHeaderSize, "js_result", closure); - converter_names += res_converters; - body += `const { method, signature, stackSave, stackRestore, alloc_stack_frame, invoke_method_and_handle_exception ${converter_names} } = closure;\n`; - // TODO named arguments instead of arguments keyword - body += `return function ${bound_js_function_name} () {\n`; - body += "const sp = stackSave();\n"; - body += "try {\n"; - body += ` const args = alloc_stack_frame(${(args_count + 2)});\n`; + const res_sig = get_sig(signature, 1); + const res_marshaler_type = get_signature_type(res_sig); + const res_converter = bind_arg_marshal_to_js(res_sig, res_marshaler_type, 1); - body += bodyToCs; - - body += " invoke_method_and_handle_exception(method, args);\n"; - if (res_marshaler_type !== MarshalerType.Void && res_marshaler_type !== MarshalerType.Discard) { - body += res_call_body; + const closure: BindingClosure = { + method, + args_count, + arg_marshalers, + res_converter, + }; + let bound_fn: Function; + if (args_count == 0 && !res_converter) { + bound_fn = bind_fn_0V(closure); } - - if (res_marshaler_type !== MarshalerType.Void && res_marshaler_type !== MarshalerType.Discard) { - body += " return js_result;\n"; + else if (args_count == 1 && !res_converter) { + bound_fn = bind_fn_1V(closure); + } + else if (args_count == 1 && res_converter) { + bound_fn = bind_fn_1R(closure); + } + else if (args_count == 2 && res_converter) { + bound_fn = bind_fn_2R(closure); + } + else { + bound_fn = bind_fn(closure); } - body += "} finally {\n"; - body += " stackRestore(sp);\n"; - body += "}}"; - const factory = new Function("closure", body); - const bound_fn = factory(closure); - bound_fn[bound_cs_function_symbol] = true; + (bound_fn)[bound_cs_function_symbol] = true; - exportedMethods.set(js_fqn, bound_fn); _walk_exports_to_set_function(assembly, namespace, classname, methodname, signature_hash, bound_fn); } catch (ex: any) { @@ -109,6 +94,123 @@ export function mono_wasm_bind_cs_function(fully_qualified_name: MonoStringRef, } } +function bind_fn_0V(closure: BindingClosure) { + const method = closure.method; + (closure) = null; + return function bound_fn_0V() { + const sp = Module.stackSave(); + try { + const args = alloc_stack_frame(2); + // call C# side + invoke_method_and_handle_exception(method, args); + } finally { + Module.stackRestore(sp); + } + }; +} + +function bind_fn_1V(closure: BindingClosure) { + const method = closure.method; + const marshaler1 = closure.arg_marshalers[0]!; + (closure) = null; + return function bound_fn_1V(arg1: any) { + const sp = Module.stackSave(); + try { + const args = alloc_stack_frame(3); + marshaler1(args, arg1); + + // call C# side + invoke_method_and_handle_exception(method, args); + } finally { + Module.stackRestore(sp); + } + }; +} + +function bind_fn_1R(closure: BindingClosure) { + const method = closure.method; + const marshaler1 = closure.arg_marshalers[0]!; + const res_converter = closure.res_converter!; + (closure) = null; + return function bound_fn_1R(arg1: any) { + const sp = Module.stackSave(); + try { + const args = alloc_stack_frame(3); + marshaler1(args, arg1); + + // call C# side + invoke_method_and_handle_exception(method, args); + + const js_result = res_converter(args); + return js_result; + } finally { + Module.stackRestore(sp); + } + }; +} + +function bind_fn_2R(closure: BindingClosure) { + const method = closure.method; + const marshaler1 = closure.arg_marshalers[0]!; + const marshaler2 = closure.arg_marshalers[1]!; + const res_converter = closure.res_converter!; + (closure) = null; + return function bound_fn_2R(arg1: any, arg2: any) { + const sp = Module.stackSave(); + try { + const args = alloc_stack_frame(4); + marshaler1(args, arg1); + marshaler2(args, arg2); + + // call C# side + invoke_method_and_handle_exception(method, args); + + const js_result = res_converter(args); + return js_result; + } finally { + Module.stackRestore(sp); + } + }; +} + +function bind_fn(closure: BindingClosure) { + const args_count = closure.args_count; + const arg_marshalers = closure.arg_marshalers; + const res_converter = closure.res_converter; + const method = closure.method; + (closure) = null; + return function bound_fn(...js_args: any[]) { + const sp = Module.stackSave(); + try { + const args = alloc_stack_frame(2 + args_count); + for (let index = 0; index < args_count; index++) { + const marshaler = arg_marshalers[index]; + if (marshaler) { + const js_arg = js_args[index]; + marshaler(args, js_arg); + } + } + + // call C# side + invoke_method_and_handle_exception(method, args); + + if (res_converter) { + const js_result = res_converter(args); + return js_result; + } + } finally { + Module.stackRestore(sp); + } + }; +} + +type BindingClosure = { + args_count: number, + method: MonoMethod, + arg_marshalers: (BoundMarshalerToCs)[], + res_converter: BoundMarshalerToJs | undefined, +} + export function invoke_method_and_handle_exception(method: MonoMethod, args: JSMarshalerArguments): void { const fail = cwraps.mono_wasm_invoke_method_bound(method, args); if (fail) throw new Error("ERR24: Unexpected error: " + conv_string(fail)); diff --git a/src/mono/wasm/runtime/invoke-js.ts b/src/mono/wasm/runtime/invoke-js.ts index 7e31a296fdb987..b4ef450843e742 100644 --- a/src/mono/wasm/runtime/invoke-js.ts +++ b/src/mono/wasm/runtime/invoke-js.ts @@ -1,17 +1,19 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { mono_wasm_get_jsobj_from_js_handle, mono_wasm_get_js_handle } from "./gc-handles"; -import { marshal_exception_to_cs, generate_arg_marshal_to_cs } from "./marshal-to-cs"; -import { get_signature_argument_count, JavaScriptMarshalerArgSize, bound_js_function_symbol, JSMarshalerTypeSize, get_sig, JSMarshalerSignatureHeaderSize, get_signature_version, MarshalerType, get_signature_type } from "./marshal"; +import { marshal_exception_to_cs, bind_arg_marshal_to_cs } from "./marshal-to-cs"; +import { get_signature_argument_count, bound_js_function_symbol, get_sig, get_signature_version, MarshalerType, get_signature_type, imported_js_function_symbol } from "./marshal"; import { setI32 } from "./memory"; import { conv_string_root, js_string_to_mono_string_root } from "./strings"; -import { mono_assert, JSHandle, MonoObject, MonoObjectRef, MonoString, MonoStringRef, JSFunctionSignature, JSMarshalerArguments, WasmRoot } from "./types"; +import { mono_assert, MonoObject, MonoObjectRef, MonoString, MonoStringRef, JSFunctionSignature, JSMarshalerArguments, WasmRoot, BoundMarshalerToJs, JSFnHandle, BoundMarshalerToCs, JSHandle } from "./types"; import { Int32Ptr } from "./types/emscripten"; import { IMPORTS, INTERNAL, Module, runtimeHelpers } from "./imports"; -import { generate_arg_marshal_to_js } from "./marshal-to-js"; +import { bind_arg_marshal_to_js } from "./marshal-to-js"; import { mono_wasm_new_external_root } from "./roots"; import { mono_wasm_symbolicate_string } from "./logging"; +import { mono_wasm_get_jsobj_from_js_handle } from "./gc-handles"; + +const fn_wrapper_by_fn_handle: Function[] = [null];// 0th slot is dummy, we never free bound functions export function mono_wasm_bind_js_function(function_name: MonoStringRef, module_name: MonoStringRef, signature: JSFunctionSignature, function_js_handle: Int32Ptr, is_exception: Int32Ptr, result_address: MonoObjectRef): void { const function_name_root = mono_wasm_new_external_root(function_name), @@ -29,67 +31,59 @@ export function mono_wasm_bind_js_function(function_name: MonoStringRef, module_ const fn = mono_wasm_lookup_function(js_function_name, js_module_name); const args_count = get_signature_argument_count(signature); - const closure: any = { fn, marshal_exception_to_cs, signature }; - const bound_js_function_name = "_bound_js_" + js_function_name.replace(/\./g, "_"); - let body = `//# sourceURL=https://dotnet.generated.invalid/${bound_js_function_name} \n`; - let converter_names = ""; - - - let bodyToJs = ""; - let pass_args = ""; + const arg_marshalers: (BoundMarshalerToJs)[] = new Array(args_count); + const arg_cleanup: (Function | undefined)[] = new Array(args_count); + let has_cleanup = false; for (let index = 0; index < args_count; index++) { - const arg_offset = (index + 2) * JavaScriptMarshalerArgSize; - const sig_offset = (index + 2) * JSMarshalerTypeSize + JSMarshalerSignatureHeaderSize; - const arg_name = `arg${index}`; const sig = get_sig(signature, index + 2); - const { converters, call_body } = generate_arg_marshal_to_js(sig, index + 2, arg_offset, sig_offset, arg_name, closure); - converter_names += converters; - bodyToJs += call_body; - if (pass_args === "") { - pass_args += arg_name; - } else { - pass_args += `, ${arg_name}`; + const marshaler_type = get_signature_type(sig); + const arg_marshaler = bind_arg_marshal_to_js(sig, marshaler_type, index + 2); + mono_assert(arg_marshaler, "ERR42: argument marshaler must be resolved"); + arg_marshalers[index] = arg_marshaler; + if (marshaler_type === MarshalerType.Span) { + arg_cleanup[index] = (js_arg: any) => { + if (js_arg) { + js_arg.dispose(); + } + }; + has_cleanup = true; } } - const { converters: res_converters, call_body: res_call_body, marshaler_type: res_marshaler_type } = generate_arg_marshal_to_cs(get_sig(signature, 1), 1, JavaScriptMarshalerArgSize, JSMarshalerTypeSize + JSMarshalerSignatureHeaderSize, "js_result", closure); - converter_names += res_converters; - - body += `const { signature, fn, marshal_exception_to_cs ${converter_names} } = closure;\n`; - body += `return function ${bound_js_function_name} (args) { try {\n`; - // body += `console.log("${bound_js_function_name}")\n`; - body += bodyToJs; + const res_sig = get_sig(signature, 1); + const res_marshaler_type = get_signature_type(res_sig); + const res_converter = bind_arg_marshal_to_cs(res_sig, res_marshaler_type, 1); - - if (res_marshaler_type === MarshalerType.Void) { - body += ` const js_result = fn(${pass_args});\n`; - body += ` if (js_result !== undefined) throw new Error('Function ${js_function_name} returned unexpected value, C# signature is void');\n`; + const closure: BindingClosure = { + fn, + args_count, + arg_marshalers, + res_converter, + has_cleanup, + arg_cleanup + }; + let bound_fn: Function; + if (args_count == 0 && !res_converter) { + bound_fn = bind_fn_0V(closure); } - else if (res_marshaler_type === MarshalerType.Discard) { - body += ` fn(${pass_args});\n`; + else if (args_count == 1 && !has_cleanup && !res_converter) { + bound_fn = bind_fn_1V(closure); } - else { - body += ` const js_result = fn(${pass_args});\n`; - body += res_call_body; + else if (args_count == 1 && !has_cleanup && res_converter) { + bound_fn = bind_fn_1R(closure); } - - for (let index = 0; index < args_count; index++) { - const sig = get_sig(signature, index + 2); - const marshaler_type = get_signature_type(sig); - if (marshaler_type == MarshalerType.Span) { - const arg_name = `arg${index}`; - body += ` ${arg_name}.dispose();\n`; - } + else if (args_count == 2 && !has_cleanup && res_converter) { + bound_fn = bind_fn_2R(closure); + } + else { + bound_fn = bind_fn(closure); } - body += "} catch (ex) {\n"; - body += " marshal_exception_to_cs(args, ex);\n"; - body += "}}"; - const factory = new Function("closure", body); - const bound_fn = factory(closure); - bound_fn[bound_js_function_symbol] = true; - const bound_function_handle = mono_wasm_get_js_handle(bound_fn)!; - setI32(function_js_handle, bound_function_handle); - } catch (ex) { + (bound_fn)[imported_js_function_symbol] = true; + const fn_handle = fn_wrapper_by_fn_handle.length; + fn_wrapper_by_fn_handle.push(bound_fn); + setI32(function_js_handle, fn_handle); + } catch (ex: any) { + Module.printErr(ex.toString()); wrap_error_root(is_exception, ex, resultRoot); } finally { resultRoot.release(); @@ -97,12 +91,129 @@ export function mono_wasm_bind_js_function(function_name: MonoStringRef, module_ } } +function bind_fn_0V(closure: BindingClosure) { + const fn = closure.fn; + (closure) = null; + return function bound_fn_0V(args: JSMarshalerArguments) { + try { + // call user function + fn(); + } catch (ex) { + marshal_exception_to_cs(args, ex); + } + }; +} + +function bind_fn_1V(closure: BindingClosure) { + const fn = closure.fn; + const marshaler1 = closure.arg_marshalers[0]!; + (closure) = null; + return function bound_fn_1V(args: JSMarshalerArguments) { + try { + const arg1 = marshaler1(args); + // call user function + fn(arg1); + } catch (ex) { + marshal_exception_to_cs(args, ex); + } + }; +} + +function bind_fn_1R(closure: BindingClosure) { + const fn = closure.fn; + const marshaler1 = closure.arg_marshalers[0]!; + const res_converter = closure.res_converter!; + (closure) = null; + return function bound_fn_1R(args: JSMarshalerArguments) { + try { + const arg1 = marshaler1(args); + // call user function + const js_result = fn(arg1); + res_converter(args, js_result); + } catch (ex) { + marshal_exception_to_cs(args, ex); + } + }; +} + +function bind_fn_2R(closure: BindingClosure) { + const fn = closure.fn; + const marshaler1 = closure.arg_marshalers[0]!; + const marshaler2 = closure.arg_marshalers[1]!; + const res_converter = closure.res_converter!; + (closure) = null; + return function bound_fn_2R(args: JSMarshalerArguments) { + try { + const arg1 = marshaler1(args); + const arg2 = marshaler2(args); + // call user function + const js_result = fn(arg1, arg2); + res_converter(args, js_result); + } catch (ex) { + marshal_exception_to_cs(args, ex); + } + }; +} + +function bind_fn(closure: BindingClosure) { + const args_count = closure.args_count; + const arg_marshalers = closure.arg_marshalers; + const res_converter = closure.res_converter; + const arg_cleanup = closure.arg_cleanup; + const has_cleanup = closure.has_cleanup; + const fn = closure.fn; + (closure) = null; + return function bound_fn(args: JSMarshalerArguments) { + try { + const js_args = new Array(args_count); + for (let index = 0; index < args_count; index++) { + const marshaler = arg_marshalers[index]!; + const js_arg = marshaler(args); + js_args[index] = js_arg; + } + + // call user function + const js_result = fn(...js_args); + + if (res_converter) { + res_converter(args, js_result); + } + + if (has_cleanup) { + for (let index = 0; index < args_count; index++) { + const cleanup = arg_cleanup[index]; + if (cleanup) { + cleanup(js_args[index]); + } + } + } + } catch (ex) { + marshal_exception_to_cs(args, ex); + } + }; +} + +type BindingClosure = { + fn: Function, + args_count: number, + arg_marshalers: (BoundMarshalerToJs)[], + res_converter: BoundMarshalerToCs | undefined, + has_cleanup: boolean, + arg_cleanup: (Function | undefined)[] +} + export function mono_wasm_invoke_bound_function(bound_function_js_handle: JSHandle, args: JSMarshalerArguments): void { const bound_fn = mono_wasm_get_jsobj_from_js_handle(bound_function_js_handle); mono_assert(bound_fn && typeof (bound_fn) === "function" && bound_fn[bound_js_function_symbol], () => `Bound function handle expected ${bound_function_js_handle}`); bound_fn(args); } +export function mono_wasm_invoke_import(fn_handle: JSFnHandle, args: JSMarshalerArguments): void { + const bound_fn = fn_wrapper_by_fn_handle[fn_handle]; + mono_assert(bound_fn, () => `Imported function handle expected ${fn_handle}`); + bound_fn(args); +} + export function mono_wasm_set_module_imports(module_name: string, moduleImports: any) { importedModules.set(module_name, moduleImports); if (runtimeHelpers.diagnosticTracing) diff --git a/src/mono/wasm/runtime/marshal-to-cs.ts b/src/mono/wasm/runtime/marshal-to-cs.ts index e7cd7cf7e02342..9b3b05d8b558de 100644 --- a/src/mono/wasm/runtime/marshal-to-cs.ts +++ b/src/mono/wasm/runtime/marshal-to-cs.ts @@ -8,14 +8,15 @@ import { Module, runtimeHelpers } from "./imports"; import { ManagedError, set_gc_handle, set_js_handle, set_arg_type, set_arg_i32, set_arg_f64, set_arg_i52, set_arg_f32, set_arg_i16, set_arg_u8, set_arg_b8, set_arg_date, - set_arg_length, get_arg, get_signature_type, get_signature_arg1_type, get_signature_arg2_type, cs_to_js_marshalers, js_to_cs_marshalers, + set_arg_length, get_arg, get_signature_arg1_type, get_signature_arg2_type, js_to_cs_marshalers, get_signature_res_type, bound_js_function_symbol, set_arg_u16, array_element_size, get_string_root, Span, ArraySegment, MemoryViewType, get_signature_arg3_type, MarshalerType, set_arg_i64_big, set_arg_intptr, IDisposable, - set_arg_element_type, ManagedObject + set_arg_element_type, ManagedObject, JavaScriptMarshalerArgSize } from "./marshal"; +import { get_marshaler_to_js_by_type } from "./marshal-to-js"; import { _zero_region } from "./memory"; import { js_string_to_mono_string_root } from "./strings"; -import { mono_assert, GCHandle, GCHandleNull, JSMarshalerArgument, JSMarshalerArguments, JSMarshalerType, MarshalerToCs, MarshalerToJs } from "./types"; +import { mono_assert, GCHandle, GCHandleNull, JSMarshalerArgument, JSMarshalerArguments, JSMarshalerType, MarshalerToCs, MarshalerToJs, BoundMarshalerToCs } from "./types"; import { TypedArray } from "./types/emscripten"; export function initialize_marshalers_to_cs(): void { @@ -49,103 +50,39 @@ export function initialize_marshalers_to_cs(): void { } } -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -export function generate_arg_marshal_to_cs(sig: JSMarshalerType, index: number, arg_offset: number, sig_offset: number, jsname: string, closure: any): { - converters: string, - call_body: string, - marshaler_type: MarshalerType -} { - let converters = ""; - let converter_types = ""; - let call_body = ""; - const converter_name = "converter" + index; - let converter_name_arg1 = "null"; - let converter_name_arg2 = "null"; - let converter_name_arg3 = "null"; - let converter_name_res = "null"; - - let marshaler_type = get_signature_type(sig); +export function bind_arg_marshal_to_cs(sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToCs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void) { - return { - converters, - call_body, - marshaler_type - }; + return undefined; } + let res_marshaler: MarshalerToCs | undefined = undefined; + let arg1_marshaler: MarshalerToJs | undefined = undefined; + let arg2_marshaler: MarshalerToJs | undefined = undefined; + let arg3_marshaler: MarshalerToJs | undefined = undefined; + arg1_marshaler = get_marshaler_to_js_by_type(get_signature_arg1_type(sig)); + arg2_marshaler = get_marshaler_to_js_by_type(get_signature_arg2_type(sig)); + arg3_marshaler = get_marshaler_to_js_by_type(get_signature_arg3_type(sig)); const marshaler_type_res = get_signature_res_type(sig); - if (marshaler_type_res !== MarshalerType.None) { - const converter = js_to_cs_marshalers.get(marshaler_type_res); - mono_assert(converter && typeof converter === "function", () => `Unknow converter for type ${marshaler_type_res} at ${index}`); - - - if (marshaler_type != MarshalerType.Nullable) { - converter_name_res = "converter" + index + "_res"; - converters += ", " + converter_name_res; - converter_types += " " + MarshalerType[marshaler_type_res]; - closure[converter_name_res] = converter; - } - else { - marshaler_type = marshaler_type_res; - } - } - - const marshaler_type_arg1 = get_signature_arg1_type(sig); - if (marshaler_type_arg1 !== MarshalerType.None) { - const converter = cs_to_js_marshalers.get(marshaler_type_arg1); - mono_assert(converter && typeof converter === "function", () => `Unknow converter for type ${marshaler_type_arg1} at ${index}`); - - converter_name_arg1 = "converter" + index + "_arg1"; - converters += ", " + converter_name_arg1; - converter_types += " " + MarshalerType[marshaler_type_arg1]; - closure[converter_name_arg1] = converter; - } - - const marshaler_type_arg2 = get_signature_arg2_type(sig); - if (marshaler_type_arg2 !== MarshalerType.None) { - const converter = cs_to_js_marshalers.get(marshaler_type_arg2); - mono_assert(converter && typeof converter === "function", () => `Unknow converter for type ${marshaler_type_arg2} at ${index}`); - - converter_name_arg2 = "converter" + index + "_arg2"; - converters += ", " + converter_name_arg2; - converter_types += " " + MarshalerType[marshaler_type_arg2]; - closure[converter_name_arg2] = converter; + res_marshaler = get_marshaler_to_cs_by_type(marshaler_type_res); + if (marshaler_type === MarshalerType.Nullable) { + // nullable has nested type information, it's stored in res slot of the signature. The marshaler is the same as for non-nullable primitive type. + marshaler_type = marshaler_type_res; } + const converter = get_marshaler_to_cs_by_type(marshaler_type)!; - const marshaler_type_arg3 = get_signature_arg3_type(sig); - if (marshaler_type_arg3 !== MarshalerType.None) { - const converter = cs_to_js_marshalers.get(marshaler_type_arg3); - mono_assert(converter && typeof converter === "function", () => `Unknow converter for type ${marshaler_type_arg3} at ${index}`); + const arg_offset = index * JavaScriptMarshalerArgSize; + return (args: JSMarshalerArguments, value: any) => { + converter(args + arg_offset, value, sig, res_marshaler, arg1_marshaler, arg2_marshaler, arg3_marshaler); + }; +} - converter_name_arg3 = "converter" + index + "_arg3"; - converters += ", " + converter_name_arg3; - converter_types += " " + MarshalerType[marshaler_type_arg3]; - closure[converter_name_arg3] = converter; +export function get_marshaler_to_cs_by_type(marshaler_type: MarshalerType): MarshalerToCs | undefined { + if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void) { + return undefined; } - const converter = js_to_cs_marshalers.get(marshaler_type); - - const arg_type_name = MarshalerType[marshaler_type]; - mono_assert(converter && typeof converter === "function", () => `Unknow converter for type ${arg_type_name} (${marshaler_type}) at ${index} `); - - converters += ", " + converter_name; - converter_types += " " + arg_type_name; - closure[converter_name] = converter; - - - if (marshaler_type == MarshalerType.Task) { - call_body = ` ${converter_name}(args + ${arg_offset}, ${jsname}, signature + ${sig_offset}, ${converter_name_res}); // ${converter_types} \n`; - } else if (marshaler_type == MarshalerType.Action || marshaler_type == MarshalerType.Function) { - call_body = ` ${converter_name}(args + ${arg_offset}, ${jsname}, signature + ${sig_offset}, ${converter_name_res}, ${converter_name_arg1}, ${converter_name_arg2}, ${converter_name_arg2}); // ${converter_types} \n`; - } else { - call_body = ` ${converter_name}(args + ${arg_offset}, ${jsname}, signature + ${sig_offset}); // ${converter_types} \n`; - } - - return { - converters, - call_body, - marshaler_type - }; + mono_assert(converter && typeof converter === "function", () => `ERR30: Unknown converter for type ${marshaler_type}`); + return converter; } function _marshal_bool_to_cs(arg: JSMarshalerArgument, value: any): void { diff --git a/src/mono/wasm/runtime/marshal-to-js.ts b/src/mono/wasm/runtime/marshal-to-js.ts index 318d10580ffec0..b3f469fc05f5ce 100644 --- a/src/mono/wasm/runtime/marshal-to-js.ts +++ b/src/mono/wasm/runtime/marshal-to-js.ts @@ -9,13 +9,14 @@ import { ManagedObject, ManagedError, get_arg_gc_handle, get_arg_js_handle, get_arg_type, get_arg_i32, get_arg_f64, get_arg_i52, get_arg_i16, get_arg_u8, get_arg_f32, get_arg_b8, get_arg_date, get_arg_length, set_js_handle, get_arg, set_arg_type, - get_signature_arg2_type, get_signature_arg1_type, get_signature_type, cs_to_js_marshalers, js_to_cs_marshalers, + get_signature_arg2_type, get_signature_arg1_type, cs_to_js_marshalers, get_signature_res_type, get_arg_u16, array_element_size, get_string_root, - ArraySegment, Span, MemoryViewType, get_signature_arg3_type, MarshalerType, get_arg_i64_big, get_arg_intptr, get_arg_element_type + ArraySegment, Span, MemoryViewType, get_signature_arg3_type, MarshalerType, get_arg_i64_big, get_arg_intptr, get_arg_element_type, JavaScriptMarshalerArgSize } from "./marshal"; import { conv_string_root } from "./strings"; -import { mono_assert, JSHandleNull, GCHandleNull, JSMarshalerArgument, JSMarshalerArguments, JSMarshalerType, MarshalerToCs, MarshalerToJs } from "./types"; +import { mono_assert, JSHandleNull, GCHandleNull, JSMarshalerArgument, JSMarshalerArguments, JSMarshalerType, MarshalerToCs, MarshalerToJs, BoundMarshalerToJs } from "./types"; import { TypedArray } from "./types/emscripten"; +import { get_marshaler_to_cs_by_type } from "./marshal-to-cs"; export function initialize_marshalers_to_js(): void { if (cs_to_js_marshalers.size == 0) { @@ -48,98 +49,40 @@ export function initialize_marshalers_to_js(): void { } } -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -export function generate_arg_marshal_to_js(sig: JSMarshalerType, index: number, arg_offset: number, sig_offset: number, jsname: string, closure: any): { - converters: string, - call_body: string, - marshaler_type: MarshalerType -} { - let converters = ""; - let converter_types = ""; - let call_body = ""; - const converter_name = "converter" + index; - let converter_name_arg1 = "null"; - let converter_name_arg2 = "null"; - let converter_name_arg3 = "null"; - let converter_name_res = "null"; - - let marshaler_type = get_signature_type(sig); +export function bind_arg_marshal_to_js(sig: JSMarshalerType, marshaler_type: MarshalerType, index: number): BoundMarshalerToJs | undefined { if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void) { - return { - converters, - call_body, - marshaler_type - }; - } - - const marshaler_type_res = get_signature_res_type(sig); - if (marshaler_type_res !== MarshalerType.None) { - const converter = cs_to_js_marshalers.get(marshaler_type_res); - mono_assert(converter && typeof converter === "function", () => `Unknow converter for type ${marshaler_type_res} at ${index}`); - - if (marshaler_type != MarshalerType.Nullable) { - converter_name_res = "converter" + index + "_res"; - converters += ", " + converter_name_res; - converter_types += " " + MarshalerType[marshaler_type_res]; - closure[converter_name_res] = converter; - } else { - marshaler_type = marshaler_type_res; - } + return undefined; } - const marshaler_type_arg1 = get_signature_arg1_type(sig); - if (marshaler_type_arg1 !== MarshalerType.None) { - const converter = js_to_cs_marshalers.get(marshaler_type_arg1); - mono_assert(converter && typeof converter === "function", () => `Unknow converter for type ${marshaler_type_arg1} at ${index}`); + let res_marshaler: MarshalerToJs | undefined = undefined; + let arg1_marshaler: MarshalerToCs | undefined = undefined; + let arg2_marshaler: MarshalerToCs | undefined = undefined; + let arg3_marshaler: MarshalerToCs | undefined = undefined; - converter_name_arg1 = "converter" + index + "_arg1"; - converters += ", " + converter_name_arg1; - converter_types += " " + MarshalerType[marshaler_type_arg1]; - closure[converter_name_arg1] = converter; - } - - const marshaler_type_arg2 = get_signature_arg2_type(sig); - if (marshaler_type_arg2 !== MarshalerType.None) { - const converter = js_to_cs_marshalers.get(marshaler_type_arg2); - mono_assert(converter && typeof converter === "function", () => `Unknow converter for type ${marshaler_type_arg2} at ${index}`); - - converter_name_arg2 = "converter" + index + "_arg2"; - converters += ", " + converter_name_arg2; - converter_types += " " + MarshalerType[marshaler_type_arg2]; - closure[converter_name_arg2] = converter; + arg1_marshaler = get_marshaler_to_cs_by_type(get_signature_arg1_type(sig)); + arg2_marshaler = get_marshaler_to_cs_by_type(get_signature_arg2_type(sig)); + arg3_marshaler = get_marshaler_to_cs_by_type(get_signature_arg3_type(sig)); + const marshaler_type_res = get_signature_res_type(sig); + res_marshaler = get_marshaler_to_js_by_type(marshaler_type_res); + if (marshaler_type === MarshalerType.Nullable) { + // nullable has nested type information, it's stored in res slot of the signature. The marshaler is the same as for non-nullable primitive type. + marshaler_type = marshaler_type_res; } + const converter = get_marshaler_to_js_by_type(marshaler_type)!; - const marshaler_type_arg3 = get_signature_arg3_type(sig); - if (marshaler_type_arg3 !== MarshalerType.None) { - const converter = js_to_cs_marshalers.get(marshaler_type_arg3); - mono_assert(converter && typeof converter === "function", () => `Unknow converter for type ${marshaler_type_arg3} at ${index}`); + const arg_offset = index * JavaScriptMarshalerArgSize; + return (args: JSMarshalerArguments) => { + return converter(args + arg_offset, sig, res_marshaler, arg1_marshaler, arg2_marshaler, arg3_marshaler); + }; +} - converter_name_arg3 = "converter" + index + "_arg3"; - converters += ", " + converter_name_arg3; - converter_types += " " + MarshalerType[marshaler_type_arg3]; - closure[converter_name_arg3] = converter; +export function get_marshaler_to_js_by_type(marshaler_type: MarshalerType): MarshalerToJs | undefined { + if (marshaler_type === MarshalerType.None || marshaler_type === MarshalerType.Void) { + return undefined; } - const converter = cs_to_js_marshalers.get(marshaler_type); - mono_assert(converter && typeof converter === "function", () => `Unknow converter for type ${marshaler_type} at ${index} `); - - converters += ", " + converter_name; - converter_types += " " + MarshalerType[marshaler_type]; - closure[converter_name] = converter; - - if (marshaler_type == MarshalerType.Task) { - call_body = ` const ${jsname} = ${converter_name}(args + ${arg_offset}, signature + ${sig_offset}, ${converter_name_res}); // ${converter_types} \n`; - } else if (marshaler_type == MarshalerType.Action || marshaler_type == MarshalerType.Function) { - call_body = ` const ${jsname} = ${converter_name}(args + ${arg_offset}, signature + ${sig_offset}, ${converter_name_res}, ${converter_name_arg1}, ${converter_name_arg2}, ${converter_name_arg3}); // ${converter_types} \n`; - } else { - call_body = ` const ${jsname} = ${converter_name}(args + ${arg_offset}, signature + ${sig_offset}); // ${converter_types} \n`; - } - - return { - converters, - call_body, - marshaler_type - }; + mono_assert(converter && typeof converter === "function", () => `ERR41: Unknown converter for type ${marshaler_type}`); + return converter; } function _marshal_bool_to_js(arg: JSMarshalerArgument): boolean | null { @@ -266,7 +209,7 @@ export function marshal_task_to_js(arg: JSMarshalerArgument, _?: JSMarshalerType // when we arrived here from _marshal_cs_object_to_js res_converter = cs_to_js_marshalers.get(type); } - mono_assert(res_converter, () => `Unknow sub_converter for type ${MarshalerType[type]} `); + mono_assert(res_converter, () => `Unknown sub_converter for type ${MarshalerType[type]} `); // this is already resolved const val = res_converter(arg); @@ -297,7 +240,7 @@ export function marshal_task_to_js(arg: JSMarshalerArgument, _?: JSMarshalerType // when we arrived here from _marshal_cs_object_to_js res_converter = cs_to_js_marshalers.get(type); } - mono_assert(res_converter, () => `Unknow sub_converter for type ${MarshalerType[type]}`); + mono_assert(res_converter, () => `Unknown sub_converter for type ${MarshalerType[type]}`); const js_value = res_converter!(argInner); orig_resolve(js_value); @@ -329,7 +272,7 @@ export function mono_wasm_marshal_promise(args: JSMarshalerArguments): void { else if (value_type !== MarshalerType.Task) { // this is already resolved task const sub_converter = cs_to_js_marshalers.get(value_type); - mono_assert(sub_converter, () => `Unknow sub_converter for type ${MarshalerType[value_type]} `); + mono_assert(sub_converter, () => `Unknown sub_converter for type ${MarshalerType[value_type]} `); const data = sub_converter(arg_value); promise_control.resolve(data); } @@ -438,7 +381,7 @@ function _marshal_cs_object_to_js(arg: JSMarshalerArgument): any { // other types const converter = cs_to_js_marshalers.get(marshaler_type); - mono_assert(converter, () => `Unknow converter for type ${MarshalerType[marshaler_type]}`); + mono_assert(converter, () => `Unknown converter for type ${MarshalerType[marshaler_type]}`); return converter(arg); } diff --git a/src/mono/wasm/runtime/marshal.ts b/src/mono/wasm/runtime/marshal.ts index 77bec6b6aa762f..591f3976292164 100644 --- a/src/mono/wasm/runtime/marshal.ts +++ b/src/mono/wasm/runtime/marshal.ts @@ -12,6 +12,7 @@ export const cs_to_js_marshalers = new Map(); export const js_to_cs_marshalers = new Map(); export const bound_cs_function_symbol = Symbol.for("wasm bound_cs_function"); export const bound_js_function_symbol = Symbol.for("wasm bound_js_function"); +export const imported_js_function_symbol = Symbol.for("wasm imported_js_function"); /** * JSFunctionSignature is pointer to [ diff --git a/src/mono/wasm/runtime/net6-legacy/corebindings.ts b/src/mono/wasm/runtime/net6-legacy/corebindings.ts index 759f84e1a307cd..1850aeaa611a5d 100644 --- a/src/mono/wasm/runtime/net6-legacy/corebindings.ts +++ b/src/mono/wasm/runtime/net6-legacy/corebindings.ts @@ -14,9 +14,9 @@ const fn_signatures: SigLine[] = [ [true, "_get_cs_owned_object_by_js_handle_ref", "GetCSOwnedObjectByJSHandleRef", "iim"], [true, "_get_cs_owned_object_js_handle_ref", "GetCSOwnedObjectJSHandleRef", "mi"], [true, "_try_get_cs_owned_object_js_handle_ref", "TryGetCSOwnedObjectJSHandleRef", "mi"], - [false, "_create_cs_owned_proxy_ref", "CreateCSOwnedProxyRef", "iiim"], + [true, "_create_cs_owned_proxy_ref", "CreateCSOwnedProxyRef", "iiim"], - [false, "_get_js_owned_object_by_gc_handle_ref", "GetJSOwnedObjectByGCHandleRef", "im"], + [true, "_get_js_owned_object_by_gc_handle_ref", "GetJSOwnedObjectByGCHandleRef", "im"], [true, "_get_js_owned_object_gc_handle_ref", "GetJSOwnedObjectGCHandleRef", "m"], [true, "_create_tcs", "CreateTaskSource", ""], @@ -30,7 +30,7 @@ const fn_signatures: SigLine[] = [ [true, "_create_date_time_ref", "CreateDateTimeRef", "dm"], [true, "_create_uri_ref", "CreateUriRef", "sm"], [true, "_is_simple_array_ref", "IsSimpleArrayRef", "m"], - [false, "_get_call_sig_ref", "GetCallSignatureRef", "im"], + [true, "_get_call_sig_ref", "GetCallSignatureRef", "im"], ]; export interface LegacyExports { diff --git a/src/mono/wasm/runtime/types.ts b/src/mono/wasm/runtime/types.ts index ea01f16a9e5c85..3aa07dd6550ab0 100644 --- a/src/mono/wasm/runtime/types.ts +++ b/src/mono/wasm/runtime/types.ts @@ -10,6 +10,9 @@ export type GCHandle = { export type JSHandle = { __brand: "JSHandle" } +export type JSFnHandle = { + __brand: "JSFnHandle" +} export interface MonoObject extends ManagedPointer { __brandMonoObject: "MonoObject" } @@ -413,8 +416,10 @@ export interface JavaScriptExports { install_synchronization_context(): void; } -export type MarshalerToJs = (arg: JSMarshalerArgument, sig?: JSMarshalerType, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs) => any; -export type MarshalerToCs = (arg: JSMarshalerArgument, value: any, sig?: JSMarshalerType, res_converter?: MarshalerToCs, arg1_converter?: MarshalerToJs, arg2_converter?: MarshalerToJs) => void; +export type MarshalerToJs = (arg: JSMarshalerArgument, sig?: JSMarshalerType, res_converter?: MarshalerToJs, arg1_converter?: MarshalerToCs, arg2_converter?: MarshalerToCs, arg3_converter?: MarshalerToCs) => any; +export type MarshalerToCs = (arg: JSMarshalerArgument, value: any, sig?: JSMarshalerType, res_converter?: MarshalerToCs, arg1_converter?: MarshalerToJs, arg2_converter?: MarshalerToJs, arg3_converter?: MarshalerToJs) => void; +export type BoundMarshalerToJs = (args: JSMarshalerArguments) => any; +export type BoundMarshalerToCs = (args: JSMarshalerArguments, value: any) => void; export interface JSMarshalerArguments extends NativePointer { __brand: "JSMarshalerArguments" From 6414a0b729bcb96b7f8f69c9511a2b028ce1fd68 Mon Sep 17 00:00:00 2001 From: Eric StJohn Date: Thu, 1 Sep 2022 02:35:26 -0700 Subject: [PATCH 067/107] Disable copying ProjectReferences in generator projects (#74897) --- eng/references.targets | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/eng/references.targets b/eng/references.targets index 29cff247f0d0d1..9ce2c0ed3e60c2 100644 --- a/eng/references.targets +++ b/eng/references.targets @@ -7,8 +7,8 @@ <_FindDependencies>false - - + + false From c8009fe6655f91766a9062554f2f32a6a3585efa Mon Sep 17 00:00:00 2001 From: Radek Zikmund <32671551+rzikm@users.noreply.github.com> Date: Thu, 1 Sep 2022 06:45:20 -0700 Subject: [PATCH 068/107] Remove outdated comment (#74871) --- .../System.Net.Http/src/System/Net/Http/HttpMethod.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpMethod.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpMethod.cs index 5743ff3ec8bef0..a3368fff3a5a6e 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpMethod.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpMethod.cs @@ -64,9 +64,6 @@ public static HttpMethod Patch get { return s_patchMethod; } } - // Don't expose CONNECT as static property, since it's used by the transport to connect to a proxy. - // CONNECT is not used by users directly. - public static HttpMethod Connect { get { return s_connectMethod; } From 2cfc0cdeec0fc722eea5b95996add3856b910dec Mon Sep 17 00:00:00 2001 From: Radek Doulik Date: Thu, 1 Sep 2022 15:51:13 +0200 Subject: [PATCH 069/107] [wasm] Speedup Vector128.Shuffle with SIMD (#74872) Example speedup result in Span.Reverse Firefox/amd64 | measurement | before | after | delta | |-:|-:|-:|-:| | Span, Reverse bytes | 0.0857ms | 0.0022ms | 39x faster | | Span, Reverse chars | 0.0987ms | 0.0042ms | 23.5x faster| Chrome/amd64 | measurement | before | after | delta | |-:|-:|-:|-:| | Span, Reverse bytes | 0.0768ms | 0.0028ms | 27.4x faster | | Span, Reverse chars | 0.0975ms | 0.0061ms | 16x faster | --- src/mono/mono/mini/simd-intrinsics.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/mono/mono/mini/simd-intrinsics.c b/src/mono/mono/mini/simd-intrinsics.c index ccc1f0d4e81c89..3c045fae1b7bc4 100644 --- a/src/mono/mono/mini/simd-intrinsics.c +++ b/src/mono/mono/mini/simd-intrinsics.c @@ -937,6 +937,7 @@ static guint16 sri_vector_methods [] = { SN_Narrow, SN_Negate, SN_OnesComplement, + SN_Shuffle, SN_Sqrt, SN_Subtract, SN_Sum, @@ -1370,6 +1371,15 @@ emit_sri_vector (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsi return NULL; return emit_simd_ins_for_unary_op (cfg, klass, fsig, args, arg0_type, id); } + case SN_Shuffle: { + if (!is_element_type_primitive (fsig->params [0])) + return NULL; +#ifdef TARGET_WASM + return emit_simd_ins_for_sig (cfg, klass, OP_WASM_SIMD_SWIZZLE, -1, -1, fsig, args); +#else + return NULL; +#endif + } case SN_Sum: { #ifdef TARGET_ARM64 if (!is_element_type_primitive (fsig->params [0])) From 82b85b36a7d1231a8b2aa8dd389b32114a167af8 Mon Sep 17 00:00:00 2001 From: Alex Perovich Date: Thu, 1 Sep 2022 07:09:20 -0700 Subject: [PATCH 070/107] Update public pool names (#74904) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Alexander Köplinger --- eng/common/templates/job/source-build.yml | 2 +- eng/common/templates/job/source-index-stage1.yml | 2 +- eng/pipelines/common/xplat-setup.yml | 6 +++--- eng/pipelines/coreclr/perf-non-wasm-jobs.yml | 4 ++-- eng/pipelines/libraries/enterprise/linux.yml | 2 +- eng/pipelines/libraries/stress/http.yml | 4 ++-- eng/pipelines/libraries/stress/ssl.yml | 4 ++-- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/eng/common/templates/job/source-build.yml b/eng/common/templates/job/source-build.yml index 5cd5325d7b4e6b..88f6f75a622dc6 100644 --- a/eng/common/templates/job/source-build.yml +++ b/eng/common/templates/job/source-build.yml @@ -46,7 +46,7 @@ jobs: # source-build builds run in Docker, including the default managed platform. pool: ${{ if eq(variables['System.TeamProject'], 'public') }}: - name: NetCore1ESPool-Public + name: NetCore-Public demands: ImageOverride -equals Build.Ubuntu.1804.Amd64.Open ${{ if eq(variables['System.TeamProject'], 'internal') }}: name: NetCore1ESPool-Internal diff --git a/eng/common/templates/job/source-index-stage1.yml b/eng/common/templates/job/source-index-stage1.yml index c85044a6849054..21fd12276b6580 100644 --- a/eng/common/templates/job/source-index-stage1.yml +++ b/eng/common/templates/job/source-index-stage1.yml @@ -28,7 +28,7 @@ jobs: ${{ if eq(parameters.pool, '') }}: pool: ${{ if eq(variables['System.TeamProject'], 'public') }}: - name: NetCore1ESPool-Public + name: NetCore-Public demands: ImageOverride -equals windows.vs2019.amd64.open ${{ if eq(variables['System.TeamProject'], 'internal') }}: name: NetCore1ESPool-Internal diff --git a/eng/pipelines/common/xplat-setup.yml b/eng/pipelines/common/xplat-setup.yml index 53c43c02ce88da..f50d8ede93dba9 100644 --- a/eng/pipelines/common/xplat-setup.yml +++ b/eng/pipelines/common/xplat-setup.yml @@ -135,7 +135,7 @@ jobs: pool: # Public Linux Build Pool ${{ if and(or(in(parameters.osGroup, 'Linux', 'FreeBSD', 'Android', 'Tizen'), eq(parameters.jobParameters.hostedOs, 'Linux')), eq(variables['System.TeamProject'], 'public')) }}: - name: NetCore1ESPool-Public + name: NetCore-Public demands: ImageOverride -equals Build.Ubuntu.1804.Amd64.Open # Official Build Linux Pool @@ -145,7 +145,7 @@ jobs: # OSX Build Pool (we don't have on-prem OSX BuildPool ${{ if in(parameters.osGroup, 'OSX', 'MacCatalyst', 'iOS', 'iOSSimulator', 'tvOS', 'tvOSSimulator') }}: - vmImage: 'macos-11-v3beta' + vmImage: 'macos-11' # Official Build Windows Pool ${{ if and(eq(parameters.osGroup, 'windows'), ne(variables['System.TeamProject'], 'public')) }}: @@ -154,7 +154,7 @@ jobs: # Public Windows Build Pool ${{ if and(or(eq(parameters.osGroup, 'windows'), eq(parameters.jobParameters.hostedOs, 'windows')), eq(variables['System.TeamProject'], 'public')) }}: - name: NetCore1ESPool-Public + name: NetCore-Public demands: ImageOverride -equals windows.vs2022.amd64.open diff --git a/eng/pipelines/coreclr/perf-non-wasm-jobs.yml b/eng/pipelines/coreclr/perf-non-wasm-jobs.yml index c400c870c6b6f5..9cc0e60fd01222 100644 --- a/eng/pipelines/coreclr/perf-non-wasm-jobs.yml +++ b/eng/pipelines/coreclr/perf-non-wasm-jobs.yml @@ -416,7 +416,7 @@ jobs: nameSuffix: MACiOSAndroidMauiNet7 isOfficialBuild: false pool: - vmImage: 'macos-11-v3beta' + vmImage: 'macos-11' extraStepsTemplate: /eng/pipelines/coreclr/templates/build-perf-maui-apps-net7.yml extraStepsParameters: rootFolder: '$(Build.SourcesDirectory)/artifacts/' @@ -440,7 +440,7 @@ jobs: nameSuffix: MACiOSAndroidMauiNet6 isOfficialBuild: false pool: - vmImage: 'macos-11-v3beta' + vmImage: 'macos-11' extraStepsTemplate: /eng/pipelines/coreclr/templates/build-perf-maui-apps-net6.yml extraStepsParameters: rootFolder: '$(Build.SourcesDirectory)/artifacts/' diff --git a/eng/pipelines/libraries/enterprise/linux.yml b/eng/pipelines/libraries/enterprise/linux.yml index ca2ec8777146d6..bf800fc3505e75 100644 --- a/eng/pipelines/libraries/enterprise/linux.yml +++ b/eng/pipelines/libraries/enterprise/linux.yml @@ -33,7 +33,7 @@ jobs: - job: EnterpriseLinuxTests timeoutInMinutes: 120 pool: - name: NetCore1ESPool-Public + name: NetCore-Public demands: ImageOverride -equals Build.Ubuntu.1804.Amd64.Open steps: - bash: | diff --git a/eng/pipelines/libraries/stress/http.yml b/eng/pipelines/libraries/stress/http.yml index 32b9549fa5483f..4e9e7e02d4c1a6 100644 --- a/eng/pipelines/libraries/stress/http.yml +++ b/eng/pipelines/libraries/stress/http.yml @@ -31,7 +31,7 @@ jobs: variables: DUMPS_SHARE_MOUNT_ROOT: "/dumps-share" pool: - name: NetCore1ESPool-Public + name: NetCore-Public demands: ImageOverride -equals 1es-ubuntu-1804-open steps: @@ -97,7 +97,7 @@ jobs: variables: DUMPS_SHARE_MOUNT_ROOT: "C:/dumps-share" pool: - name: NetCore1ESPool-Public + name: NetCore-Public demands: ImageOverride -equals 1es-windows-2022-open steps: diff --git a/eng/pipelines/libraries/stress/ssl.yml b/eng/pipelines/libraries/stress/ssl.yml index 97a81347a9feee..99edbbf1ab0acb 100644 --- a/eng/pipelines/libraries/stress/ssl.yml +++ b/eng/pipelines/libraries/stress/ssl.yml @@ -30,7 +30,7 @@ jobs: displayName: Docker Linux timeoutInMinutes: 120 pool: - name: NetCore1ESPool-Public + name: NetCore-Public demands: ImageOverride -equals Build.Ubuntu.1804.Amd64.Open steps: @@ -55,7 +55,7 @@ jobs: displayName: Docker NanoServer timeoutInMinutes: 120 pool: - name: NetCore1ESPool-Public + name: NetCore-Public demands: ImageOverride -equals 1es-windows-2022-open steps: From 7a45201181d37329b7ab0bee541ed7c42b5d94b6 Mon Sep 17 00:00:00 2001 From: Radek Zikmund <32671551+rzikm@users.noreply.github.com> Date: Thu, 1 Sep 2022 07:44:19 -0700 Subject: [PATCH 071/107] Unload MsQuic after checking for QUIC support to free resources. (#74749) * Unload MsQuic after checking for QUIC support to free resources. * Unload MsQuic unconditionally * Code review feedback --- .../src/System/Net/Quic/Internal/MsQuicApi.cs | 83 +++++++++++++------ 1 file changed, 59 insertions(+), 24 deletions(-) diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Internal/MsQuicApi.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Internal/MsQuicApi.cs index e2866454356dd2..eb06b9dce8e645 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Internal/MsQuicApi.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Internal/MsQuicApi.cs @@ -1,6 +1,7 @@ // 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.Runtime.InteropServices; using Microsoft.Quic; @@ -47,7 +48,8 @@ private MsQuicApi(QUIC_API_TABLE* apiTable) } } - internal static MsQuicApi Api { get; } = null!; + private static readonly Lazy _api = new Lazy(AllocateMsQuicApi); + internal static MsQuicApi Api => _api.Value; internal static bool IsQuicSupported { get; } @@ -58,29 +60,21 @@ private MsQuicApi(QUIC_API_TABLE* apiTable) static MsQuicApi() { - IntPtr msQuicHandle; - if (!NativeLibrary.TryLoad($"{Interop.Libraries.MsQuic}.{MsQuicVersion.Major}", typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out msQuicHandle) && - !NativeLibrary.TryLoad(Interop.Libraries.MsQuic, typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out msQuicHandle)) + if (!TryLoadMsQuic(out IntPtr msQuicHandle)) { return; } try { - if (!NativeLibrary.TryGetExport(msQuicHandle, "MsQuicOpenVersion", out IntPtr msQuicOpenVersionAddress)) - { - return; - } - - QUIC_API_TABLE* apiTable = null; - delegate* unmanaged[Cdecl] msQuicOpenVersion = (delegate* unmanaged[Cdecl])msQuicOpenVersionAddress; - if (StatusFailed(msQuicOpenVersion((uint)MsQuicVersion.Major, &apiTable))) + if (!TryOpenMsQuic(msQuicHandle, out QUIC_API_TABLE* apiTable)) { return; } try { + // Check version int arraySize = 4; uint* libVersion = stackalloc uint[arraySize]; uint size = (uint)arraySize * sizeof(uint); @@ -99,7 +93,7 @@ static MsQuicApi() return; } - // Assume SChannel is being used on windows and query for the actual provider from the library + // Assume SChannel is being used on windows and query for the actual provider from the library if querying is supported QUIC_TLS_PROVIDER provider = OperatingSystem.IsWindows() ? QUIC_TLS_PROVIDER.SCHANNEL : QUIC_TLS_PROVIDER.OPENSSL; size = sizeof(QUIC_TLS_PROVIDER); apiTable->GetParam(null, QUIC_PARAM_GLOBAL_TLS_PROVIDER, &size, &provider); @@ -122,26 +116,67 @@ static MsQuicApi() Tls13ClientMayBeDisabled = IsTls13Disabled(isServer: false); } - Api = new MsQuicApi(apiTable); IsQuicSupported = true; } finally { - if (!IsQuicSupported && NativeLibrary.TryGetExport(msQuicHandle, "MsQuicClose", out IntPtr msQuicClose)) - { - // Gracefully close the API table - ((delegate* unmanaged[Cdecl])msQuicClose)(apiTable); - } + // Gracefully close the API table to free resources. The API table will be allocated lazily again if needed + bool closed = TryCloseMsQuic(msQuicHandle, apiTable); + Debug.Assert(closed, "Failed to close MsQuic"); } - } finally { - if (!IsQuicSupported) - { - NativeLibrary.Free(msQuicHandle); - } + // Unload the library, we will load it again when we actually use QUIC + NativeLibrary.Free(msQuicHandle); + } + } + + private static MsQuicApi AllocateMsQuicApi() + { + Debug.Assert(IsQuicSupported); + + if (TryLoadMsQuic(out IntPtr msQuicHandle) && + TryOpenMsQuic(msQuicHandle, out QUIC_API_TABLE* apiTable)) + { + return new MsQuicApi(apiTable); + } + + throw new Exception("Failed to create MsQuicApi instance"); + } + + private static bool TryLoadMsQuic(out IntPtr msQuicHandle) => + NativeLibrary.TryLoad($"{Interop.Libraries.MsQuic}.{MsQuicVersion.Major}", typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out msQuicHandle) || + NativeLibrary.TryLoad(Interop.Libraries.MsQuic, typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out msQuicHandle); + + private static bool TryOpenMsQuic(IntPtr msQuicHandle, out QUIC_API_TABLE* apiTable) + { + apiTable = null; + if (!NativeLibrary.TryGetExport(msQuicHandle, "MsQuicOpenVersion", out IntPtr msQuicOpenVersionAddress)) + { + return false; + } + + QUIC_API_TABLE* table = null; + delegate* unmanaged[Cdecl] msQuicOpenVersion = (delegate* unmanaged[Cdecl])msQuicOpenVersionAddress; + if (StatusFailed(msQuicOpenVersion((uint)MsQuicVersion.Major, &table))) + { + return false; } + + apiTable = table; + return true; + } + + private static bool TryCloseMsQuic(IntPtr msQuicHandle, QUIC_API_TABLE* apiTable) + { + if (NativeLibrary.TryGetExport(msQuicHandle, "MsQuicClose", out IntPtr msQuicClose)) + { + ((delegate* unmanaged[Cdecl])msQuicClose)(apiTable); + return true; + } + + return false; } private static bool IsWindowsVersionSupported() => OperatingSystem.IsWindowsVersionAtLeast(MinWindowsVersion.Major, From ab2d195f169a08bf8eb978b472b2d3aca61b0a46 Mon Sep 17 00:00:00 2001 From: Tlakaelel Axayakatl Ceja Date: Thu, 1 Sep 2022 13:02:43 -0700 Subject: [PATCH 072/107] Run code quality analyzers in the coreclr/tools directory (#74825) Run codeanalysis analyzers in the coreclr/tools directory --- .../Common/CommandLine/ArgumentParser.cs | 2 +- .../Common/CommandLine/ArgumentSyntax.cs | 33 +- .../CommandLine/ArgumentSyntax_Definers.cs | 2 +- .../tools/Common/CommandLine/ArgumentToken.cs | 4 +- .../CommandLine/CommandLineException.cs | 2 +- .../Common/CommandLine/CommandLineHelpers.cs | 6 +- .../Common/CommandLine/HelpTextGenerator.cs | 8 +- .../Compiler/CodeGenerationFailedException.cs | 2 +- .../CompilerTypeSystemContext.Validation.cs | 4 +- .../Compiler/CompilerTypeSystemContext.cs | 28 +- .../DependencyAnalysis/CompilerComparer.cs | 1 - .../EmbeddedDataContainerNode.cs | 4 +- .../INodeWithRuntimeDeterminedDependencies.cs | 3 +- .../DependencyAnalysis/ISymbolNode.cs | 5 +- .../MethodReadOnlyDataNode.cs | 2 - .../ObjectAndOffsetSymbolNode.cs | 2 +- .../DependencyAnalysis/ObjectDataBuilder.cs | 10 +- .../Compiler/DependencyAnalysis/ObjectNode.cs | 4 +- .../DependencyAnalysis/ObjectNodeSection.cs | 4 +- .../ShadowConcreteMethodNode.cs | 2 +- .../SortableDependencyNode.cs | 3 +- .../Target_ARM/ARMEmitter.cs | 3 +- .../DependencyAnalysis/Target_ARM/Register.cs | 8 +- .../Target_ARM/TargetRegisterMap.cs | 2 - .../Target_ARM64/ARM64Emitter.cs | 4 +- .../Target_ARM64/AddrMode.cs | 2 - .../Target_ARM64/Register.cs | 10 +- .../Target_ARM64/TargetRegisterMap.cs | 2 - .../Target_LoongArch64/AddrMode.cs | 2 - .../Target_LoongArch64/Register.cs | 6 - .../Target_LoongArch64/TargetRegisterMap.cs | 2 - .../DependencyAnalysis/Target_X64/AddrMode.cs | 2 - .../DependencyAnalysis/Target_X64/Register.cs | 6 - .../Target_X64/X64Emitter.cs | 9 +- .../DependencyAnalysis/Target_X86/AddrMode.cs | 2 - .../DependencyAnalysis/Target_X86/Register.cs | 8 +- .../Target_X86/TargetRegisterMap.cs | 2 +- .../Target_X86/X86Emitter.cs | 9 +- .../Compiler/DevirtualizationManager.cs | 3 +- .../Common/Compiler/DisplayNameHelpers.cs | 8 +- .../Compiler/HardwareIntrinsicHelpers.cs | 5 - .../Common/Compiler/InstructionSetSupport.cs | 5 +- .../tools/Common/Compiler/MethodExtensions.cs | 3 - .../Common/Compiler/NativeAotNameMangler.cs | 47 +- .../tools/Common/Compiler/TypeExtensions.cs | 10 +- .../Compiler/VectorFieldLayoutAlgorithm.cs | 6 +- .../LowLevelLinq/LowLevelEnumerable.ToList.cs | 2 - .../Generator/MdBinaryWriterGen.cs | 4 - .../NativeFormat/Generator/ReaderGen.cs | 5 +- .../NativeFormat/Generator/SchemaDef.cs | 14 +- .../NativeFormat/Generator/WriterGen.cs | 15 +- .../Metadata/NativeFormat/MdBinaryReader.cs | 7 - .../NativeFormat/MdBinaryReaderGen.cs | 4 - .../NativeFormat/NativeFormatReaderGen.cs | 2 +- .../NativeFormat/NativeMetadataReader.cs | 4 +- .../NativeFormatReader.Primitives.cs | 2 - .../NativeFormat/NativeFormatReader.String.cs | 1 - .../NativeFormat/NativeFormatReader.cs | 3 +- .../NativeFormat/NativeFormatWriter.cs | 135 +-- .../Common/Internal/Runtime/CorConstants.cs | 2 - .../Internal/Runtime/EETypeBuilderHelpers.cs | 3 +- .../Runtime/EETypeOptionalFieldsBuilder.cs | 16 +- .../Common/Internal/Runtime/GCDescEncoder.cs | 2 +- .../InterfaceDispatchCellCachePointerFlags.cs | 2 - .../Common/Internal/Runtime/ModuleHeaders.cs | 3 +- .../Internal/Runtime/ReadyToRunConstants.cs | 2 +- .../UniversalGenericParameterLayout.cs | 15 +- .../tools/Common/Internal/Text/Utf8String.cs | 3 +- .../Common/Internal/Text/Utf8StringBuilder.cs | 4 +- .../tools/Common/JitInterface/CorInfoBase.cs | 356 +++--- .../Common/JitInterface/CorInfoHelpFunc.cs | 18 +- .../tools/Common/JitInterface/CorInfoImpl.cs | 158 ++- .../JitInterface/CorInfoInstructionSet.cs | 10 +- .../JitInterface/CorInfoTypes.VarInfo.cs | 1 - .../tools/Common/JitInterface/CorInfoTypes.cs | 11 +- .../Common/JitInterface/JitConfigProvider.cs | 7 +- .../LoongArch64PassStructInRegister.cs | 9 +- .../tools/Common/JitInterface/MemoryHelper.cs | 2 - .../SystemVStructClassificator.cs | 14 +- .../ThunkGenerator/InstructionSetGenerator.cs | 10 +- .../JitInterface/ThunkGenerator/Program.cs | 6 +- .../tools/Common/JitInterface/TypeString.cs | 6 +- .../Common/JitInterface/UnboxingMethodDesc.cs | 3 +- .../JitInterface/UnboxingMethodDescFactory.cs | 4 +- src/coreclr/tools/Common/Pgo/PgoFormat.cs | 30 +- .../Common/Pgo/TypeSystemEntityOrUnknown.cs | 4 +- .../Sorting/ISortableDataStructureAccessor.cs | 4 - .../tools/Common/Sorting/ListAccessor.cs | 1 - src/coreclr/tools/Common/Sorting/MergeSort.cs | 2 +- .../tools/Common/Sorting/MergeSortCore.cs | 5 +- .../TypeSystem/Canon/ArrayType.Canon.cs | 4 +- .../TypeSystem/Canon/ByRefType.Canon.cs | 2 +- .../TypeSystem/Canon/CanonTypes.Diagnostic.cs | 7 - .../TypeSystem/Canon/CanonTypes.Interop.cs | 2 +- .../TypeSystem/Canon/CanonTypes.Sorting.cs | 6 +- .../Common/TypeSystem/Canon/DefType.Canon.cs | 2 +- .../Canon/FunctionPointerType.Canon.cs | 4 +- .../Canon/InstantiatedMethod.Canon.cs | 10 +- .../Canon/InstantiatedType.Canon.cs | 2 +- .../TypeSystem/Canon/MetadataType.Canon.cs | 2 +- .../TypeSystem/Canon/MethodDelegator.Canon.cs | 2 +- .../TypeSystem/Canon/MethodDesc.Canon.cs | 2 +- .../Canon/MethodForInstantiatedType.Canon.cs | 2 +- .../Canon/ParameterizedType.Canon.cs | 2 +- .../TypeSystem/Canon/PointerType.Canon.cs | 2 +- .../Canon/SignatureVariable.Canon.cs | 4 +- .../Common/TypeSystem/Canon/TypeDesc.Canon.cs | 11 +- .../TypeSystem/CodeGen/FieldDesc.CodeGen.cs | 4 +- .../CodeGen/MethodDelegator.CodeGen.cs | 2 +- .../CodeGen/NativeStructType.CodeGen.cs | 2 +- .../CodeGen/TargetDetails.CodeGen.cs | 2 +- .../TypeSystem/CodeGen/TypeDesc.CodeGen.cs | 4 +- .../ArrayOfTRuntimeInterfacesAlgorithm.cs | 1 - .../Common/TypeSystem/Common/ArrayType.cs | 1 - .../BaseTypeRuntimeInterfacesAlgorithm.cs | 3 - .../Common/TypeSystem/Common/CastingHelper.cs | 4 +- .../Common/ConstructedTypeRewritingHelpers.cs | 1 - .../TypeSystem/Common/DefType.Diagnostic.cs | 4 +- .../TypeSystem/Common/DefType.FieldLayout.cs | 18 +- .../Common/FieldDesc.FieldLayout.cs | 1 - .../TypeSystem/Common/FieldDesc.ToString.cs | 2 +- .../Common/TypeSystem/Common/FieldDesc.cs | 5 +- .../Common/FieldForInstantiatedType.cs | 4 +- .../TypeSystem/Common/FunctionPointerType.cs | 2 - .../Common/GenericParameterDesc.Diagnostic.cs | 1 - .../TypeSystem/Common/GenericParameterDesc.cs | 2 +- .../TypeSystem/Common/InstantiatedMethod.cs | 4 +- .../Common/InstantiatedType.Interfaces.cs | 5 +- .../Common/InstantiatedType.MethodImpls.cs | 4 +- .../TypeSystem/Common/InstantiatedType.cs | 4 +- .../Common/TypeSystem/Common/LayoutInt.cs | 2 +- .../Common/TypeSystem/Common/LinqPoison.cs | 2 +- .../Common/MetadataFieldLayoutAlgorithm.cs | 19 +- .../MetadataRuntimeInterfacesAlgorithm.cs | 9 +- .../Common/MetadataType.Interfaces.cs | 3 - .../Common/MetadataType.MethodImpls.cs | 2 - .../Common/MetadataTypeSystemContext.cs | 1 - .../Common/MetadataVirtualMethodAlgorithm.cs | 16 +- .../Common/MethodDelegator.Diagnostic.cs | 2 +- .../Common/MethodDesc.Diagnostic.cs | 4 +- .../TypeSystem/Common/MethodDesc.ToString.cs | 4 +- .../Common/TypeSystem/Common/MethodDesc.cs | 6 +- .../Common/MethodForInstantiatedType.cs | 4 +- .../Common/TypeSystem/Common/ModuleDesc.cs | 1 - .../TypeSystem/Common/ParameterizedType.cs | 2 - .../TypeSystem/Common/SignatureVariable.cs | 4 - .../TypeSystem/Common/TargetArchitecture.cs | 3 - .../Common/TargetDetails.ToString.cs | 5 +- .../TypeSystem/Common/ThrowHelper.Common.cs | 1 - .../TypeSystem/Common/TypeDesc.Interfaces.cs | 1 - .../TypeSystem/Common/TypeDesc.ToString.cs | 2 +- .../Common/TypeSystem/Common/TypeDesc.cs | 12 +- .../Common/TypeHashingAlgorithms.cs | 1 - .../Common/TypeSystemConstraintsHelpers.cs | 2 +- .../TypeSystem/Common/TypeSystemContext.cs | 12 +- .../Common/TypeSystemException.Resources.cs | 3 +- .../TypeSystem/Common/TypeSystemException.cs | 6 +- .../TypeSystem/Common/TypeSystemHelpers.cs | 2 +- .../Common/UniversalCanonLayoutAlgorithm.cs | 4 - .../CustomAttributeTypeNameFormatter.cs | 2 +- .../CustomAttributeTypeNameParser.cs | 31 +- .../Common/Utilities/DebugNameFormatter.cs | 2 - .../ExceptionTypeNameFormatter.Metadata.cs | 6 +- .../Utilities/GCPointerMap.Algorithm.cs | 2 +- .../Common/Utilities/GCPointerMap.cs | 2 +- .../Utilities/LockFreeReaderHashtable.cs | 5 +- .../Common/Utilities/TypeNameFormatter.cs | 1 - .../Common/TypeSystem/Common/WellKnownType.cs | 2 - .../Ecma/CachingMetadataStringDecoder.cs | 4 +- .../TypeSystem/Ecma/EcmaAssembly.Symbols.cs | 2 +- .../TypeSystem/Ecma/EcmaField.CodeGen.cs | 2 +- .../Ecma/EcmaField.Serialization.cs | 2 +- .../TypeSystem/Ecma/EcmaField.Sorting.cs | 2 +- .../Ecma/EcmaGenericParameter.Sorting.cs | 2 +- .../TypeSystem/Ecma/EcmaGenericParameter.cs | 6 +- .../TypeSystem/Ecma/EcmaMethod.Sorting.cs | 2 +- .../Common/TypeSystem/Ecma/EcmaMethod.cs | 4 +- .../TypeSystem/Ecma/EcmaModule.Sorting.cs | 2 +- .../TypeSystem/Ecma/EcmaModule.Symbols.cs | 2 +- .../Common/TypeSystem/Ecma/EcmaModule.cs | 44 +- .../TypeSystem/Ecma/EcmaSignatureEncoder.cs | 5 +- .../TypeSystem/Ecma/EcmaSignatureParser.cs | 38 +- .../Ecma/EcmaSignatureTranslator.cs | 21 +- .../TypeSystem/Ecma/EcmaType.Diagnostic.cs | 7 - .../TypeSystem/Ecma/EcmaType.Interfaces.cs | 6 - .../TypeSystem/Ecma/EcmaType.MethodImpls.cs | 13 +- .../TypeSystem/Ecma/EcmaType.Serialization.cs | 2 +- .../TypeSystem/Ecma/EcmaType.Sorting.cs | 2 +- .../tools/Common/TypeSystem/Ecma/EcmaType.cs | 3 +- .../Common/TypeSystem/Ecma/IEcmaModule.cs | 7 +- .../Ecma/IMetadataStringDecoderProvider.cs | 1 - .../TypeSystem/Ecma/MetadataExtensions.cs | 8 +- .../SymbolReader/PortablePdbSymbolReader.cs | 4 +- .../SymbolReader/UnmanagedPdbSymbolReader.cs | 58 +- .../Common/TypeSystem/IL/DelegateInfo.cs | 5 +- .../TypeSystem/IL/EcmaMethodIL.Symbols.cs | 2 +- .../Common/TypeSystem/IL/HelperExtensions.cs | 10 +- .../Common/TypeSystem/IL/ILDisassembler.cs | 17 +- .../tools/Common/TypeSystem/IL/ILImporter.cs | 13 +- .../tools/Common/TypeSystem/IL/ILOpcode.cs | 2 - .../tools/Common/TypeSystem/IL/ILReader.cs | 9 +- .../Common/TypeSystem/IL/ILStackHelper.cs | 4 +- .../Common/TypeSystem/IL/ILTokenReplacer.cs | 2 +- .../TypeSystem/IL/InstantiatedMethodIL.cs | 13 +- .../Common/TypeSystem/IL/MethodIL.Symbols.cs | 6 +- .../tools/Common/TypeSystem/IL/MethodIL.cs | 8 +- .../Common/TypeSystem/IL/MethodILDebugView.cs | 14 +- .../TypeSystem/IL/NativeAotILProvider.cs | 6 +- .../IL/Stubs/ArrayMethodILEmitter.cs | 2 +- ...GetExecutingAssemblyMethodThunk.Sorting.cs | 2 +- ...AssemblyGetExecutingAssemblyMethodThunk.cs | 6 +- .../CalliMarshallingMethodThunk.Mangling.cs | 1 - .../CalliMarshallingMethodThunk.Sorting.cs | 2 +- .../IL/Stubs/CalliMarshallingMethodThunk.cs | 4 - .../TypeSystem/IL/Stubs/ComparerIntrinsics.cs | 10 +- ...DelegateMarshallingMethodThunk.Mangling.cs | 1 - .../DelegateMarshallingMethodThunk.Sorting.cs | 2 +- .../Stubs/DelegateMarshallingMethodThunk.cs | 10 +- .../IL/Stubs/DelegateThunks.Sorting.cs | 14 +- .../TypeSystem/IL/Stubs/DelegateThunks.cs | 6 +- .../DynamicInvokeMethodThunk.Mangling.cs | 1 - .../Stubs/DynamicInvokeMethodThunk.Sorting.cs | 5 +- .../IL/Stubs/DynamicInvokeMethodThunk.cs | 6 - .../TypeSystem/IL/Stubs/EnumThunks.Sorting.cs | 4 +- .../Common/TypeSystem/IL/Stubs/EnumThunks.cs | 4 +- .../ForwardDelegateCreationThunk.Sorting.cs | 2 +- .../IL/Stubs/ForwardDelegateCreationThunk.cs | 20 +- .../IL/Stubs/GetCanonTypeIntrinsic.cs | 2 - .../Common/TypeSystem/IL/Stubs/ILEmitter.cs | 21 +- .../IL/Stubs/InterlockedIntrinsics.cs | 1 - .../IL/Stubs/MemoryMarshalIntrinsics.cs | 3 +- ...ethodBaseGetCurrentMethodThunk.Mangling.cs | 2 +- ...MethodBaseGetCurrentMethodThunk.Sorting.cs | 2 +- .../Stubs/MethodBaseGetCurrentMethodThunk.cs | 6 +- .../IL/Stubs/PInvokeILCodeStreams.cs | 4 +- .../TypeSystem/IL/Stubs/PInvokeILEmitter.cs | 2 +- .../IL/Stubs/PInvokeLazyFixupField.Sorting.cs | 2 +- .../PInvokeTargetNativeMethod.Diagnostic.cs | 4 +- .../PInvokeTargetNativeMethod.Mangling.cs | 2 +- .../PInvokeTargetNativeMethod.Sorting.cs | 2 +- .../IL/Stubs/PInvokeTargetNativeMethod.cs | 2 +- .../IL/Stubs/RuntimeHelpersIntrinsics.cs | 1 - .../TypeSystem/IL/Stubs/StreamIntrinsics.cs | 2 - .../Stubs/StructMarshallingThunk.Sorting.cs | 2 +- .../IL/Stubs/StructMarshallingThunk.cs | 20 +- .../Stubs/TypeGetTypeMethodThunk.Sorting.cs | 2 +- .../IL/Stubs/TypeGetTypeMethodThunk.cs | 6 +- .../TypeSystem/IL/Stubs/UnsafeIntrinsics.cs | 2 +- ...ypeGetFieldHelperMethodOverride.Sorting.cs | 2 +- .../ValueTypeGetFieldHelperMethodOverride.cs | 4 +- .../TypeSystem/Interop/FieldDesc.Interop.cs | 4 +- .../Interop/IL/InlineArrayType.Sorting.cs | 6 +- .../TypeSystem/Interop/IL/InlineArrayType.cs | 15 +- .../Interop/IL/MarshalHelpers.Aot.cs | 6 +- .../TypeSystem/Interop/IL/MarshalHelpers.cs | 2 - .../TypeSystem/Interop/IL/MarshalUtils.cs | 2 - .../TypeSystem/Interop/IL/Marshaller.Aot.cs | 49 +- .../TypeSystem/Interop/IL/Marshaller.cs | 54 +- .../TypeSystem/Interop/IL/MarshallerKind.cs | 2 +- .../Interop/IL/NativeStructType.Mangling.cs | 2 +- .../Interop/IL/NativeStructType.Sorting.cs | 4 +- .../TypeSystem/Interop/IL/NativeStructType.cs | 3 +- .../IL/PInvokeDelegateWrapper.Mangling.cs | 2 +- .../IL/PInvokeDelegateWrapper.Sorting.cs | 2 +- .../Interop/IL/PInvokeDelegateWrapper.cs | 5 +- ...nvokeDelegateWrapperConstructor.Sorting.cs | 2 +- .../IL/PInvokeDelegateWrapperConstructor.cs | 9 +- .../TypeSystem/Interop/InteropStateManager.cs | 41 +- .../Common/TypeSystem/Interop/InteropTypes.cs | 2 - .../TypeSystem/Interop/MarshalAsDescriptor.cs | 2 - .../Interop/MetadataType.Interop.cs | 2 - .../Interop/MethodDelegator.Interop.cs | 2 +- .../TypeSystem/Interop/MethodDesc.Interop.cs | 6 +- .../TypeSystemMetadataEmitter.cs | 54 +- .../ArrayType.RuntimeDetermined.cs | 4 +- .../ByRefType.RuntimeDetermined.cs | 2 +- .../DefType.RuntimeDetermined.cs | 2 +- .../FieldDesc.RuntimeDetermined.cs | 2 +- .../FunctionPointerType.RuntimeDetermined.cs | 2 +- .../GenericParameterDesc.RuntimeDetermined.cs | 2 +- .../MethodDesc.RuntimeDetermined.cs | 4 +- ...thodForRuntimeDeterminedType.Diagnostic.cs | 2 +- .../MethodForRuntimeDeterminedType.Sorting.cs | 2 +- .../MethodForRuntimeDeterminedType.cs | 1 - .../ParameterizedType.RuntimeDetermined.cs | 2 +- .../PointerType.RuntimeDetermined.cs | 2 +- ...timeDeterminedCanonicalizationAlgorithm.cs | 2 +- .../RuntimeDeterminedFieldLayoutAlgorithm.cs | 5 +- .../RuntimeDeterminedType.Diagnostic.cs | 6 +- .../RuntimeDeterminedType.Sorting.cs | 2 +- .../RuntimeDeterminedType.cs | 7 +- .../SignatureVariable.RuntimeDetermined.cs | 2 +- .../TypeDesc.RuntimeDetermined.cs | 2 +- .../TypeSystemContext.RuntimeDetermined.cs | 6 +- .../Serialization/FieldDesc.Serialization.cs | 4 +- .../Serialization/TypeDesc.Serialization.cs | 4 +- .../TypeSystem/Sorting/ArrayType.Sorting.cs | 4 +- .../TypeSystem/Sorting/ByRefType.Sorting.cs | 2 +- .../TypeSystem/Sorting/FieldDesc.Sorting.cs | 2 +- .../FieldForInstantiatedType.Sorting.cs | 2 +- .../Sorting/FunctionPointerType.Sorting.cs | 2 +- .../Sorting/InstantiatedMethod.Sorting.cs | 6 +- .../Sorting/InstantiatedType.Sorting.cs | 8 +- .../TypeSystem/Sorting/MethodDesc.Sorting.cs | 2 +- .../MethodForInstantiatedType.Sorting.cs | 2 +- .../Sorting/MethodSignature.Sorting.cs | 2 +- .../TypeSystem/Sorting/PointerType.Sorting.cs | 2 +- .../Sorting/SignatureVariable.Sorting.cs | 8 +- .../TypeSystem/Sorting/TypeDesc.Sorting.cs | 2 +- .../TypeSystem/Sorting/TypeSystemComparer.cs | 1 - src/coreclr/tools/aot/.editorconfig | 39 + .../Compiler/AnalysisBasedMetadataManager.cs | 4 +- .../BlockedInternalsBlockingPolicy.cs | 20 +- .../Compiler/BodySubstitution.cs | 6 +- .../Compiler/BodySubstitutionParser.cs | 8 +- .../Compiler/Compilation.cs | 19 +- .../Compiler/CompilationBuilder.Aot.cs | 4 +- .../Compiler/CompilationModuleGroup.Aot.cs | 6 +- .../CompilerGeneratedInteropStubManager.cs | 2 +- .../CompilerMetadataFieldLayoutAlgorithm.cs | 5 +- .../Compiler/CompilerTypeSystemContext.Aot.cs | 7 +- .../CompilerTypeSystemContext.BoxedTypes.cs | 41 +- .../CompilerTypeSystemContext.DelegateInfo.cs | 10 +- ...CompilerTypeSystemContext.DynamicInvoke.cs | 9 +- .../CompilerTypeSystemContext.EnumMethods.cs | 9 +- ...SystemContext.GeneratedAssembly.Sorting.cs | 4 +- ...ilerTypeSystemContext.GeneratedAssembly.cs | 4 +- ...mpilerTypeSystemContext.InterfaceThunks.cs | 14 +- .../CompilerTypeSystemContext.Mangling.cs | 9 +- .../CompilerTypeSystemContext.Sorting.cs | 14 +- ...pilerTypeSystemContext.ValueTypeMethods.cs | 11 +- .../Compiler/Dataflow/ArrayValue.cs | 10 +- .../Compiler/Dataflow/AttributeDataFlow.cs | 14 +- .../Dataflow/CompilerGeneratedCallGraph.cs | 7 +- .../Dataflow/CompilerGeneratedNames.cs | 2 +- .../Dataflow/CompilerGeneratedState.cs | 26 +- .../Compiler/Dataflow/DiagnosticContext.cs | 10 +- .../Compiler/Dataflow/DiagnosticUtilities.cs | 6 +- .../Compiler/Dataflow/EcmaExtensions.cs | 2 +- .../Compiler/Dataflow/FieldValue.cs | 2 +- .../Compiler/Dataflow/FlowAnnotations.cs | 33 +- .../Dataflow/GenericArgumentDataFlow.cs | 10 +- .../Dataflow/GenericParameterValue.cs | 2 +- .../Compiler/Dataflow/HandleCallAction.cs | 8 +- .../Compiler/Dataflow/HoistedLocalKey.cs | 2 +- .../Compiler/Dataflow/IValueWithStaticType.cs | 2 +- .../Compiler/Dataflow/InterproceduralState.cs | 14 +- .../Compiler/Dataflow/MethodBodyScanner.cs | 43 +- .../Compiler/Dataflow/MethodParameterValue.cs | 2 +- .../Compiler/Dataflow/MethodProxy.cs | 2 +- .../Compiler/Dataflow/MethodReturnValue.cs | 2 +- .../Dataflow/MethodThisParameterValue.cs | 2 +- .../Compiler/Dataflow/Origin.cs | 13 +- .../Compiler/Dataflow/ReflectionMarker.cs | 9 +- .../Dataflow/ReflectionMethodBodyScanner.cs | 19 +- ...RequireDynamicallyAccessedMembersAction.cs | 6 +- .../Compiler/Dataflow/ScannerExtensions.cs | 4 - .../Dataflow/TrimAnalysisPatternStore.cs | 8 +- .../Compiler/Dataflow/TypeExtensions.cs | 4 +- .../Compiler/Dataflow/ValueNode.cs | 2 +- .../ArrayOfEmbeddedDataNode.cs | 7 +- .../ArrayOfEmbeddedPointersNode.cs | 6 +- .../ArrayOfFrozenObjectsNode.cs | 3 +- .../Compiler/DependencyAnalysis/BlobNode.cs | 1 - .../BlockReflectionTypeMapNode.cs | 4 +- .../CallingConventionConverterKey.cs | 10 +- .../CanonicalDefinitionEETypeNode.cs | 2 - .../DependencyAnalysis/CanonicalEETypeNode.cs | 10 +- .../ClassConstructorContextMap.cs | 2 +- .../CodeBasedDependencyAlgorithm.cs | 12 +- .../ConstructedEETypeNode.cs | 6 +- ...CustomAttributeBasedDependencyAlgorithm.cs | 6 +- .../CustomAttributeMetadataNode.cs | 8 +- .../DataflowAnalyzedMethodNode.cs | 3 +- .../DefaultConstructorMapNode.cs | 8 +- .../DictionaryLayoutNode.cs | 14 +- .../DynamicDependencyAttributeAlgorithm.cs | 3 +- .../Compiler/DependencyAnalysis/EETypeNode.cs | 24 +- .../EETypeOptionalFieldsNode.cs | 8 +- .../EmbeddedPointerIndirectionNode.cs | 1 - .../EmbeddedTrimmingDescriptorNode.cs | 4 +- .../ExactMethodInstantiationsNode.cs | 2 +- .../DependencyAnalysis/ExternSymbolNode.cs | 5 +- .../ExternSymbolsImportedNodeProvider.cs | 4 - .../ExternalReferencesTableNode.cs | 6 +- .../FatFunctionPointerNode.cs | 2 +- .../DependencyAnalysis/FieldMetadataNode.cs | 2 +- .../DependencyAnalysis/FieldRvaDataNode.cs | 2 +- .../DependencyAnalysis/FrozenObjectNode.cs | 2 +- .../DependencyAnalysis/GCStaticEETypeNode.cs | 1 - .../DependencyAnalysis/GCStaticsNode.cs | 4 +- .../GCStaticsPreInitDataNode.cs | 2 +- .../DependencyAnalysis/GVMDependenciesNode.cs | 4 +- .../GenericCompositionNode.cs | 4 +- .../GenericDefinitionEETypeNode.cs | 3 +- .../GenericDictionaryNode.cs | 4 +- .../DependencyAnalysis/GenericLookupResult.cs | 13 +- .../GenericMethodsHashtableNode.cs | 4 +- .../GenericMethodsTemplateMap.cs | 2 +- .../GenericTypesTemplateMap.cs | 5 +- .../DependencyAnalysis/ILScanNodeFactory.cs | 2 - .../INodeWithCodeInfo.Aot.cs | 2 - .../DependencyAnalysis/INodeWithDebugInfo.cs | 2 +- .../ISpecialUnboxThunkNode.cs | 2 - .../ImportedNodeProvider.cs | 4 - .../IndirectionExtensions.cs | 7 +- .../InterfaceDispatchCellNode.cs | 4 +- .../InterfaceDispatchCellSectionNode.cs | 4 +- .../InterfaceDispatchMapNode.cs | 8 +- .../InterfaceGenericVirtualMethodTableNode.cs | 14 +- .../DependencyAnalysis/JumpStubNode.cs | 2 +- .../DependencyAnalysis/MetadataNode.cs | 3 +- .../MethodAssociatedDataNode.cs | 1 - .../MethodExceptionHandlingInfoNode.cs | 2 - .../DependencyAnalysis/MethodMetadataNode.cs | 2 +- .../ModuleInitializerListNode.cs | 12 +- .../DependencyAnalysis/ModuleMetadataNode.cs | 2 +- .../ModuleUseBasedDependencyAlgorithm.cs | 2 +- .../DependencyAnalysis/ModulesSectionNode.cs | 2 - .../NativeLayoutInfoNode.cs | 1 - .../NativeLayoutVertexNode.cs | 146 ++- .../NecessaryCanonicalEETypeNode.cs | 1 - .../NodeFactory.GenericLookups.cs | 4 +- .../NodeFactory.NativeLayout.cs | 7 +- .../DependencyAnalysis/NodeFactory.cs | 32 +- .../DependencyAnalysis/NonGCStaticsNode.cs | 3 +- .../ObjectGetTypeFlowDependenciesNode.cs | 8 +- .../DependencyAnalysis/ObjectWriter.cs | 39 +- .../PInvokeMethodFixupNode.cs | 2 +- .../ReadyToRunGenericHelperNode.cs | 6 +- .../ReadyToRunHeaderNode.cs | 15 +- .../ReadyToRunHelperNode.cs | 12 +- .../ReflectableFieldNode.cs | 1 - .../ReflectableMethodNode.cs | 1 - .../ReflectionFieldMapNode.cs | 3 +- .../ReflectionInvokeMapNode.cs | 3 +- .../ReflectionMethodBodyScanner.cs | 8 +- .../ReflectionVirtualInvokeMapNode.cs | 19 +- .../DependencyAnalysis/ResourceDataNode.cs | 9 +- .../DependencyAnalysis/ResourceIndexNode.cs | 5 +- .../RuntimeFieldHandleNode.cs | 1 - .../RuntimeMethodHandleNode.cs | 3 +- .../DependencyAnalysis/ScannedMethodNode.cs | 2 +- .../DependencyAnalysis/SealedVTableNode.cs | 7 +- .../ShadowConcreteUnboxingThunkNode.cs | 4 +- .../StackTraceMethodMappingNode.cs | 1 - .../StaticsInfoHashtableNode.cs | 5 +- .../StringAllocatorMethodNode.cs | 2 +- .../DependencyAnalysis/Target_ARM/ARMDebug.cs | 3 +- .../ARMInitialInterfaceDispatchStubNode.cs | 2 +- .../Target_ARM/ARMNodeFactory.cs | 7 +- .../ARMReadyToRunGenericHelperNode.cs | 4 +- .../Target_ARM/ARMReadyToRunHelperNode.cs | 4 +- .../Target_ARM/ARMUnboxingStubNode.cs | 2 +- .../ARM64ReadyToRunGenericHelperNode.cs | 4 +- .../Target_ARM64/ARM64ReadyToRunHelperNode.cs | 2 +- .../Target_ARM64/ARM64UnboxingStubNode.cs | 3 +- .../LoongArch64ReadyToRunGenericHelperNode.cs | 4 +- .../LoongArch64UnboxingStubNode.cs | 1 - .../X64ReadyToRunGenericHelperNode.cs | 6 +- .../X86ReadyToRunGenericHelperNode.cs | 14 +- .../TentativeInstanceMethodNode.cs | 5 - .../DependencyAnalysis/TentativeMethodNode.cs | 2 +- .../DependencyAnalysis/ThreadStaticsNode.cs | 2 +- .../TrimmingDescriptorNode.cs | 4 - .../DependencyAnalysis/TypeGVMEntriesNode.cs | 7 +- .../TypeManagerIndirectionNode.cs | 3 - .../DependencyAnalysis/TypeMetadataMapNode.cs | 3 +- .../DependencyAnalysis/TypeMetadataNode.cs | 7 +- .../DependencyAnalysis/UnboxingStubNode.cs | 8 +- .../DependencyAnalysis/VTableSliceNode.cs | 8 +- .../VariantInterfaceMethodUseNode.cs | 5 +- .../VirtualMethodUseNode.cs | 7 +- .../Compiler/DescriptorMarker.cs | 36 +- .../Compiler/Disassembler.cs | 2 +- .../Compiler/EmptyInteropStubManager.cs | 2 - .../Compiler/FeatureSettings.cs | 5 +- .../Compiler/FeatureSwitchManager.cs | 17 +- .../Compiler/GeneratingMetadataManager.cs | 8 +- .../Compiler/GenericDictionaryLookup.cs | 2 +- .../Compiler/GenericRootProvider.cs | 2 - ...semblyGeneratingMethodDebugInfoProvider.cs | 4 +- .../ILCompiler.Compiler/Compiler/ILScanner.cs | 15 +- .../Compiler/ILScannerBuilder.cs | 2 - .../Compiler/ILStreamReader.cs | 2 +- .../Compiler/ILogWriter.cs | 2 - .../Compiler/InteropStubManager.cs | 2 - .../ILCompiler.Compiler/Compiler/JitHelper.cs | 2 +- .../Compiler/LazyGenerics/Graph.Cycles.cs | 35 +- .../Compiler/LazyGenerics/Graph.Vertex.cs | 10 +- .../Compiler/LazyGenerics/Graph.cs | 3 +- .../LazyGenerics/GraphBuilder.ForEach.cs | 9 +- .../LazyGenerics/GraphBuilder.MethodCall.cs | 3 +- .../Compiler/LazyGenerics/GraphBuilder.cs | 2 +- .../Compiler/LazyGenerics/ModuleCycleInfo.cs | 8 +- .../Compiler/LibraryRootProvider.cs | 9 +- .../ILCompiler.Compiler/Compiler/Logger.cs | 10 +- ...mentationSignatureGenerator.PartVisitor.cs | 5 +- .../Logging/DocumentationSignatureParser.cs | 53 +- .../Compiler/Logging/MessageContainer.cs | 12 +- .../Compiler/Logging/MessageOrigin.cs | 7 +- .../ManifestResourceBlockingPolicy.cs | 6 +- .../Compiler/MetadataManager.cs | 3 +- .../Compiler/MstatObjectDumper.cs | 3 +- .../MultiFileCompilationModuleGroup.cs | 3 +- .../NativeLibraryInitializerRootProvider.cs | 2 - .../Compiler/NodeMangler.cs | 3 +- .../Compiler/ObjectDumper.cs | 7 +- .../Compiler/PreinitializationManager.cs | 8 +- .../Compiler/ProcessLinkerXmlBase.cs | 62 +- .../Compiler/ProcessXmlBase.cs | 20 +- .../Compiler/RootingHelpers.cs | 3 - .../Compiler/RootingServiceProvider.cs | 2 +- .../RuntimeConfigurationRootProvider.cs | 2 +- .../Compiler/TextLogWriter.cs | 3 +- .../Compiler/TypePreinit.cs | 26 +- .../Compiler/UniversalGenericsRootProvider.cs | 2 +- .../Compiler/UnixNodeMangler.cs | 1 - .../Compiler/UsageBasedInteropStubManager.cs | 10 +- .../Compiler/UsageBasedMetadataManager.cs | 33 +- .../Compiler/UserDefinedTypeDescriptor.cs | 58 +- .../Compiler/VectorOfTFieldLayoutAlgorithm.cs | 2 +- .../Compiler/VirtualMethodCallHelper.cs | 5 +- .../Compiler/WindowsNodeMangler.cs | 3 +- .../Compiler/XmlObjectDumper.cs | 2 +- .../IL/ILImporter.Scanner.cs | 106 +- .../IL/Stubs/PInvokeILProvider.cs | 2 - .../AppContextInitializerMethod.Sorting.cs | 2 +- .../AppContextInitializerMethod.cs | 5 +- .../NativeLibraryStartupMethod.Sorting.cs | 5 +- .../StartupCode/NativeLibraryStartupMethod.cs | 8 +- .../StartupCodeMainMethod.Sorting.cs | 9 +- .../StartupCode/StartupCodeMainMethod.cs | 9 +- .../ILCompiler.Compiler.csproj | 1 + .../ComputedStaticDependencyNode.cs | 3 - .../DependencyAnalyzer.cs | 41 +- .../DependencyAnalyzerBase.cs | 7 +- .../DependencyNode.cs | 3 +- .../DependencyNodeCore.cs | 11 +- .../DgmlWriter.cs | 6 +- .../EventSourceLogStrategy.cs | 21 +- .../FirstMarkLogStrategy.cs | 10 +- .../FullGraphLogStrategy.cs | 8 +- .../IDependencyAnalysisMarkStrategy.cs | 1 - .../IDependencyAnalyzerLogEdgeVisitor.cs | 6 - .../IDependencyNode.cs | 2 +- ...ompiler.DependencyAnalysisFramework.csproj | 1 + .../NoLogStrategy.cs | 5 - .../PerfEventSource.cs | 4 +- .../ILCompiler.MetadataTransform.csproj | 1 + .../ILCompiler/Metadata/EntityMap.cs | 2 +- .../ILCompiler/Metadata/Transform.Constant.cs | 2 +- .../Metadata/Transform.CustomAttribute.cs | 2 +- .../ILCompiler/Metadata/Transform.Event.cs | 3 +- .../ILCompiler/Metadata/Transform.Field.cs | 4 +- .../ILCompiler/Metadata/Transform.Method.cs | 12 +- .../Metadata/Transform.Namespace.cs | 10 +- .../Metadata/Transform.Parameter.cs | 2 +- .../ILCompiler/Metadata/Transform.Property.cs | 4 +- .../ILCompiler/Metadata/Transform.Scope.cs | 6 +- .../ILCompiler/Metadata/Transform.String.cs | 2 +- .../ILCompiler/Metadata/Transform.Type.cs | 9 +- .../Metadata/Transform.TypeForwarders.cs | 6 +- .../ILCompiler/Metadata/Transform.cs | 2 +- .../NativeFormat/Writer/ConstantValues.cs | 61 +- .../NativeFormat/Writer/MdBinaryWriter.cs | 6 - .../NativeFormat/Writer/MdBinaryWriterGen.cs | 4 - .../Writer/NativeFormatWriterGen.cs | 1030 ++++++++++------- .../Writer/NativeMetadataWriter.cs | 91 +- .../Compiler/ProfileData.cs | 9 +- .../ILCompiler.ReadyToRun/IBC/IBCDataModel.cs | 2 +- .../IBC/MIbcProfileParser.cs | 33 +- .../IBC/ReaderExtensions.cs | 2 +- .../DependencyAnalysis/MethodCodeNode.cs | 12 +- .../DependencyAnalysis/RyuJitNodeFactory.cs | 2 - .../Compiler/ProfileDataManager.cs | 2 +- .../Compiler/RyuJitCompilationBuilder.cs | 7 +- .../ILCompiler.RyuJit.csproj | 1 + .../JitInterface/CorInfoImpl.RyuJit.cs | 29 +- .../ArchitectureSpecificFieldLayoutTests.cs | 56 +- .../CanonicalizationTests.cs | 2 - .../CastingTests.cs | 4 +- .../ConstraintsValidationTest.cs | 4 +- .../ExceptionStringTests.cs | 2 +- .../GCPointerMapTests.cs | 4 +- .../GenericTypeAndMethodTests.cs | 4 +- .../HashcodeTests.cs | 10 +- .../ILCompiler.TypeSystem.Tests.csproj | 1 + .../InstanceFieldLayoutTests.cs | 6 +- .../InterfacesTests.cs | 5 +- .../RuntimeDeterminedTypesTests.cs | 4 +- .../SignatureTests.cs | 5 +- .../StaticFieldLayoutTests.cs | 4 +- ...eticVirtualOverrideTests.DiagnosticName.cs | 6 - .../SyntheticVirtualOverrideTests.cs | 14 +- .../TestMetadataFieldLayoutAlgorithm.cs | 5 +- .../TestTypeSystemContext.cs | 24 +- .../TypeNameParsingTests.cs | 38 +- .../UniversalGenericFieldLayoutTests.cs | 28 +- .../ValueTypeShapeCharacteristicsTests.cs | 11 +- .../VirtualFunctionOverrideTests.cs | 14 +- .../ILCompiler.TypeSystem.csproj | 1 + .../ILCompiler/ConfigurablePInvokePolicy.cs | 2 +- .../tools/aot/ILCompiler/ILCompiler.csproj | 3 +- src/coreclr/tools/aot/ILCompiler/Program.cs | 32 +- .../tools/aot/ILCompiler/RdXmlRootProvider.cs | 6 +- .../tools/aot/ILLink.Shared/Annotations.cs | 4 +- .../aot/ILLink.Shared/ClosedAttribute.cs | 2 +- .../DataFlow/DefaultValueDictionary.cs | 9 +- .../DataFlow/ForwardDataFlowAnalysis.cs | 15 +- .../ILLink.Shared/DataFlow/MaybeLattice.cs | 2 +- .../aot/ILLink.Shared/DataFlow/ValueSet.cs | 16 +- .../aot/ILLink.Shared/DiagnosticString.cs | 4 +- .../tools/aot/ILLink.Shared/HashUtils.cs | 2 +- .../tools/aot/ILLink.Shared/IsExternalInit.cs | 2 +- .../ILLink.Shared/TrimAnalysis/ArrayValue.cs | 4 +- .../TrimAnalysis/ConstIntValue.cs | 2 +- .../TrimAnalysis/DiagnosticContext.cs | 2 +- .../ILLink.Shared/TrimAnalysis/FieldValue.cs | 2 +- .../TrimAnalysis/FlowAnnotations.cs | 4 +- .../TrimAnalysis/GenericParameterValue.cs | 2 +- .../TrimAnalysis/HandleCallAction.cs | 20 +- .../ILLink.Shared/TrimAnalysis/IntrinsicId.cs | 2 +- .../ILLink.Shared/TrimAnalysis/Intrinsics.cs | 2 +- .../TrimAnalysis/KnownStringValue.cs | 2 +- .../TrimAnalysis/MethodParameterValue.cs | 2 +- .../TrimAnalysis/MethodReturnValue.cs | 2 +- .../TrimAnalysis/MethodThisParameterValue.cs | 2 +- .../ILLink.Shared/TrimAnalysis/NullValue.cs | 2 +- .../TrimAnalysis/NullableSystemTypeValue.cs | 2 +- ...ableValueWithDynamicallyAccessedMembers.cs | 4 +- .../TrimAnalysis/ReferenceKind.cs | 2 +- ...RequireDynamicallyAccessedMembersAction.cs | 4 +- .../TrimAnalysis/RuntimeMethodHandleValue.cs | 2 +- ...ntimeTypeHandleForGenericParameterValue.cs | 2 +- ...imeTypeHandleForNullableSystemTypeValue.cs | 2 +- ...ableValueWithDynamicallyAccessedMembers.cs | 6 +- .../TrimAnalysis/RuntimeTypeHandleValue.cs | 2 +- .../SystemReflectionMethodBaseValue.cs | 2 +- .../TrimAnalysis/SystemTypeValue.cs | 2 +- .../TrimAnalysis/UnknownValue.cs | 2 +- .../TrimAnalysis/ValueExtensions.cs | 8 +- .../TypeSystemProxy/IMemberProxy.cs | 2 +- .../BaseExpectedLinkedBehaviorAttribute.cs | 2 +- .../BaseMemberAssertionAttribute.cs | 2 +- .../Assertions/CreatedMemberAttribute.cs | 2 +- .../Assertions/EnableLoggerAttribute.cs | 2 +- .../Assertions/ExpectBodyModifiedAttribute.cs | 2 +- ...ResolvedDocumentationSignatureAttribute.cs | 2 +- ...xpectExceptionHandlersModifiedAttribute.cs | 2 +- ...eneratedDocumentationSignatureAttribute.cs | 2 +- .../ExpectLocalsModifiedAttribute.cs | 2 +- ...ResolvedDocumentationSignatureAttribute.cs | 2 +- ...resolvedDocumentationSignatureAttribute.cs | 2 +- .../ExpectedInstructionSequenceAttribute.cs | 2 +- ...tionSequenceOnMemberInAssemblyAttribute.cs | 2 +- .../ExpectedLocalsSequenceAttribute.cs | 2 +- .../Assertions/IgnoreTestCaseAttribute.cs | 2 +- ...ptAllTypesAndMembersInAssemblyAttribute.cs | 2 +- .../Assertions/KeptAssemblyAttribute.cs | 2 +- .../Assertions/KeptAttribute.cs | 2 +- .../KeptAttributeInAssemblyAttribute.cs | 2 +- ...KeptAttributeOnFixedBufferTypeAttribute.cs | 2 +- .../KeptBaseOnTypeInAssemblyAttribute.cs | 2 +- .../Assertions/KeptBaseTypeAttribute.cs | 2 +- .../Assertions/KeptFixedBufferAttribute.cs | 2 +- .../Assertions/KeptInitializerData.cs | 2 +- .../Assertions/KeptInterfaceAttribute.cs | 2 +- .../KeptInterfaceOnTypeInAssemblyAttribute.cs | 2 +- .../Assertions/KeptMemberAttribute.cs | 2 +- .../KeptPrivateImplementationDetails.cs | 2 +- .../Assertions/KeptReferenceAttribute.cs | 2 +- .../KeptReferencesInAssemblyAttribute.cs | 2 +- .../Assertions/KeptSymbolsAttribute.cs | 2 +- .../Assertions/RemovedAssemblyAttribute.cs | 2 +- .../Assertions/RemovedAttributeInAssembly.cs | 2 +- ...movedInterfaceOnTypeInAssemblyAttribute.cs | 2 +- .../RemovedPseudoAttributeAttribute.cs | 2 +- .../Assertions/RemovedSymbolsAttribute.cs | 2 +- .../Helpers/PlatformAssemblies.cs | 2 +- .../Metadata/NotATestCaseAttribute.cs | 2 +- .../Metadata/ReferenceDependencyAttribute.cs | 2 +- .../Metadata/SandboxDependencyAttribute.cs | 2 +- .../SetupCompileAsLibraryAttribute.cs | 2 +- .../SetupCompileAssemblyNameAttribute.cs | 2 +- .../Metadata/SetupLinkerArgumentAttribute.cs | 2 +- .../SetupLinkerDefaultActionAttribute.cs | 2 +- .../SetupLinkerKeepDebugMembersAttribute.cs | 2 +- ...SetupLinkerLinkPublicAndFamilyAttribute.cs | 2 +- .../SetupLinkerResponseFileAttribute.cs | 2 +- .../SetupLinkerSubstitutionFileAttribute.cs | 2 +- ...ono.Linker.Tests.Cases.Expectations.csproj | 1 + .../RemoveAttributeInstancesAttribute.cs | 2 +- .../Mono.Linker.Tests.Cases.csproj | 1 + .../Extensions/CecilExtensions.cs | 16 +- .../Mono.Linker.Tests/Extensions/NiceIO.cs | 26 +- .../Mono.Linker.Tests.csproj | 1 + .../TestCases/TestDatabase.cs | 9 +- .../TestCasesRunner/AssemblyChecker.cs | 83 +- .../TestCasesRunner/BaseMetadataProvider.cs | 2 +- .../TestCasesRunner/ILCompilerDriver.cs | 4 +- .../ILCompilerOptionsBuilder.cs | 2 +- .../ILCompilerTestCaseResult.cs | 1 - .../TestCasesRunner/ILInputCompiler.cs | 2 +- .../TestCasesRunner/IgnoreTestException.cs | 2 +- .../TestCasesRunner/ResultChecker.cs | 35 +- .../TestCaseAssemblyResolver.cs | 2 +- .../TestCaseCompilationMetadataProvider.cs | 6 +- .../TestCasesRunner/TestCaseCompiler.cs | 10 +- .../TestCaseMetadataProvider.cs | 5 +- .../TestCasesRunner/TestCaseSandbox.cs | 5 +- ...estInfraMultiFileCompilationModuleGroup.cs | 75 +- .../TestCasesRunner/TestLogWriter.cs | 4 - .../TestCasesRunner/TestRunner.cs | 3 +- 714 files changed, 3115 insertions(+), 3651 deletions(-) diff --git a/src/coreclr/tools/Common/CommandLine/ArgumentParser.cs b/src/coreclr/tools/Common/CommandLine/ArgumentParser.cs index 86515f5cb132bb..b538a669b93e77 100644 --- a/src/coreclr/tools/Common/CommandLine/ArgumentParser.cs +++ b/src/coreclr/tools/Common/CommandLine/ArgumentParser.cs @@ -18,7 +18,7 @@ public ArgumentParser(IEnumerable arguments) public ArgumentParser(IEnumerable arguments, Func> responseFileReader) { if (arguments == null) - throw new ArgumentNullException("arguments"); + throw new ArgumentNullException(nameof(arguments)); _tokens = ArgumentLexer.Lex(arguments, responseFileReader); } diff --git a/src/coreclr/tools/Common/CommandLine/ArgumentSyntax.cs b/src/coreclr/tools/Common/CommandLine/ArgumentSyntax.cs index 4cea1200b3a94c..976f2a559b1c5b 100644 --- a/src/coreclr/tools/Common/CommandLine/ArgumentSyntax.cs +++ b/src/coreclr/tools/Common/CommandLine/ArgumentSyntax.cs @@ -34,10 +34,10 @@ internal ArgumentSyntax(IEnumerable arguments) public static ArgumentSyntax Parse(IEnumerable arguments, Action defineAction) { if (arguments == null) - throw new ArgumentNullException("arguments"); + throw new ArgumentNullException(nameof(arguments)); if (defineAction == null) - throw new ArgumentNullException("defineAction"); + throw new ArgumentNullException(nameof(defineAction)); var syntax = new ArgumentSyntax(arguments); defineAction(syntax); @@ -107,12 +107,12 @@ public void ReportError(string message) public ArgumentCommand DefineCommand(string name, T value) { if (string.IsNullOrEmpty(name)) - throw new ArgumentException(Strings.NameMissing, "name"); + throw new ArgumentException(Strings.NameMissing, nameof(name)); if (!IsValidName(name)) { var message = string.Format(Strings.CommandNameIsNotValidFmt, name); - throw new ArgumentException(message, "name"); + throw new ArgumentException(message, nameof(name)); } if (_commands.Any(c => string.Equals(c.Name, name, StringComparison.Ordinal))) @@ -143,7 +143,7 @@ public ArgumentCommand DefineCommand(string name, T value) public Argument DefineOption(string name, T defaultValue, Func valueConverter, bool isRequired) { if (string.IsNullOrEmpty(name)) - throw new ArgumentException(Strings.NameMissing, "name"); + throw new ArgumentException(Strings.NameMissing, nameof(name)); if (DefinedParameters.Any()) throw new InvalidOperationException(Strings.OptionsMustBeDefinedBeforeParameters); @@ -178,7 +178,7 @@ public Argument DefineOption(string name, T defaultValue, Func public ArgumentList DefineOptionList(string name, IReadOnlyList defaultValue, Func valueConverter, bool isRequired) { if (string.IsNullOrEmpty(name)) - throw new ArgumentException(Strings.NameMissing, "name"); + throw new ArgumentException(Strings.NameMissing, nameof(name)); if (DefinedParameters.Any()) throw new InvalidOperationException(Strings.OptionsMustBeDefinedBeforeParameters); @@ -213,12 +213,12 @@ public ArgumentList DefineOptionList(string name, IReadOnlyList default public Argument DefineParameter(string name, T defaultValue, Func valueConverter) { if (string.IsNullOrEmpty(name)) - throw new ArgumentException(Strings.NameMissing, "name"); + throw new ArgumentException(Strings.NameMissing, nameof(name)); if (!IsValidName(name)) { var message = string.Format(Strings.ParameterNameIsNotValidFmt, name); - throw new ArgumentException(message, "name"); + throw new ArgumentException(message, nameof(name)); } if (DefinedParameters.Any(p => p.IsList)) @@ -252,12 +252,12 @@ public Argument DefineParameter(string name, T defaultValue, Func DefineParameterList(string name, IReadOnlyList defaultValue, Func valueConverter) { if (string.IsNullOrEmpty(name)) - throw new ArgumentException(Strings.NameMissing, "name"); + throw new ArgumentException(Strings.NameMissing, nameof(name)); if (!IsValidName(name)) { var message = string.Format(Strings.ParameterNameIsNotValidFmt, name); - throw new ArgumentException(message, "name"); + throw new ArgumentException(message, nameof(name)); } if (DefinedParameters.Any(p => p.IsList)) @@ -304,7 +304,7 @@ private IEnumerable ParseOptionNameList(string name) if (!IsValidName(alias)) { var message = string.Format(Strings.OptionNameIsNotValidFmt, alias); - throw new ArgumentException(message, "name"); + throw new ArgumentException(message, nameof(name)); } foreach (var option in DefinedOptions) @@ -358,8 +358,7 @@ private ArgumentParser Parser { get { - if (_parser == null) - _parser = new ArgumentParser(_arguments, ParseResponseFile); + _parser ??= new ArgumentParser(_arguments, ParseResponseFile); return _parser; } @@ -457,15 +456,15 @@ public string GetHelpText(int maxWidth) public IReadOnlyList ExtraHelpParagraphs { + get + { + return _extraHelpParagraphs.ToArray(); + } set { _extraHelpParagraphs.Clear(); _extraHelpParagraphs.AddRange(value); } - get - { - return _extraHelpParagraphs.ToArray(); - } } } } diff --git a/src/coreclr/tools/Common/CommandLine/ArgumentSyntax_Definers.cs b/src/coreclr/tools/Common/CommandLine/ArgumentSyntax_Definers.cs index 0d98ced079d975..83d9f675b42180 100644 --- a/src/coreclr/tools/Common/CommandLine/ArgumentSyntax_Definers.cs +++ b/src/coreclr/tools/Common/CommandLine/ArgumentSyntax_Definers.cs @@ -10,7 +10,7 @@ namespace Internal.CommandLine public partial class ArgumentSyntax { private static readonly Func s_stringParser = v => v; - private static readonly Func s_booleanParser = v => bool.Parse(v); + private static readonly Func s_booleanParser = bool.Parse; private static readonly Func s_int32Parser = v => int.Parse(v, CultureInfo.InvariantCulture); // Commands diff --git a/src/coreclr/tools/Common/CommandLine/ArgumentToken.cs b/src/coreclr/tools/Common/CommandLine/ArgumentToken.cs index c93c63f961b52a..83ef63435d84b6 100644 --- a/src/coreclr/tools/Common/CommandLine/ArgumentToken.cs +++ b/src/coreclr/tools/Common/CommandLine/ArgumentToken.cs @@ -49,14 +49,14 @@ private bool Equals(ArgumentToken other) public override bool Equals(object obj) { - if (ReferenceEquals(obj, null)) + if (obj is null) return false; if (ReferenceEquals(obj, this)) return true; var other = obj as ArgumentToken; - return !ReferenceEquals(other, null) && Equals(other); + return other is not null && Equals(other); } public override int GetHashCode() diff --git a/src/coreclr/tools/Common/CommandLine/CommandLineException.cs b/src/coreclr/tools/Common/CommandLine/CommandLineException.cs index 1c42daf007f2ac..3785047b6a5a51 100644 --- a/src/coreclr/tools/Common/CommandLine/CommandLineException.cs +++ b/src/coreclr/tools/Common/CommandLine/CommandLineException.cs @@ -5,7 +5,7 @@ namespace Internal.CommandLine { - internal class CommandLineException : Exception + internal sealed class CommandLineException : Exception { public CommandLineException(string message) : base(message) diff --git a/src/coreclr/tools/Common/CommandLine/CommandLineHelpers.cs b/src/coreclr/tools/Common/CommandLine/CommandLineHelpers.cs index 25f2c7b9851919..d7fa472f748acd 100644 --- a/src/coreclr/tools/Common/CommandLine/CommandLineHelpers.cs +++ b/src/coreclr/tools/Common/CommandLine/CommandLineHelpers.cs @@ -12,7 +12,7 @@ namespace Internal.CommandLine // // Helpers for command line processing // - internal class Helpers + internal static class Helpers { // Helper to create a collection of paths unique in their simple names. public static void AppendExpandedPaths(Dictionary dictionary, string pattern, bool strict) @@ -102,7 +102,7 @@ public static void MakeReproPackage(string makeReproPath, string outputFilePath, } } - HashCode hashCodeOfArgs = new HashCode(); + HashCode hashCodeOfArgs = default(HashCode); foreach (string s in details) hashCodeOfArgs.Add(s); @@ -143,7 +143,7 @@ public static void MakeReproPackage(string makeReproPath, string outputFilePath, Dictionary dictionary = new Dictionary(); foreach (string optInList in (IEnumerable)option.Value) { - Helpers.AppendExpandedPaths(dictionary, optInList, false); + AppendExpandedPaths(dictionary, optInList, false); } foreach (string inputFile in dictionary.Values) { diff --git a/src/coreclr/tools/Common/CommandLine/HelpTextGenerator.cs b/src/coreclr/tools/Common/CommandLine/HelpTextGenerator.cs index afe1f0a1a5d118..3c2f621901321d 100644 --- a/src/coreclr/tools/Common/CommandLine/HelpTextGenerator.cs +++ b/src/coreclr/tools/Common/CommandLine/HelpTextGenerator.cs @@ -65,7 +65,7 @@ private static void WriteUsage(this StringBuilder sb, string applicationName, IE sb.Append(usageHeader); if (syntaxElements.Any()) - sb.Append(@" "); + sb.Append(' '); var syntaxIndent = usageHeader.Length + 1; var syntaxMaxWidth = maxWidth - syntaxIndent; @@ -169,7 +169,7 @@ private static string GetOptionSyntax(Argument option) { var sb = new StringBuilder(); - sb.Append(@"["); + sb.Append('['); sb.Append(option.GetDisplayName()); if (!option.IsFlag) @@ -178,7 +178,7 @@ private static string GetOptionSyntax(Argument option) if (option.IsList) sb.Append(@"..."); - sb.Append(@"]"); + sb.Append(']'); return sb.ToString(); } @@ -252,7 +252,7 @@ private static IEnumerable WordWrapLines(IEnumerable tokens, int } if (sb.Length > 0) - sb.Append(@" "); + sb.Append(' '); sb.Append(token); } diff --git a/src/coreclr/tools/Common/Compiler/CodeGenerationFailedException.cs b/src/coreclr/tools/Common/Compiler/CodeGenerationFailedException.cs index 0001807c0cf482..671bb60ec2eb7a 100644 --- a/src/coreclr/tools/Common/Compiler/CodeGenerationFailedException.cs +++ b/src/coreclr/tools/Common/Compiler/CodeGenerationFailedException.cs @@ -19,7 +19,7 @@ public CodeGenerationFailedException(MethodDesc method) } public CodeGenerationFailedException(MethodDesc method, Exception inner) - : base(String.Format(MessageText, method), inner) + : base(string.Format(MessageText, method), inner) { Method = method; } diff --git a/src/coreclr/tools/Common/Compiler/CompilerTypeSystemContext.Validation.cs b/src/coreclr/tools/Common/Compiler/CompilerTypeSystemContext.Validation.cs index 2766d7226bfb71..dcbccd62283eaf 100644 --- a/src/coreclr/tools/Common/Compiler/CompilerTypeSystemContext.Validation.cs +++ b/src/coreclr/tools/Common/Compiler/CompilerTypeSystemContext.Validation.cs @@ -9,7 +9,7 @@ namespace ILCompiler { // Validates types to the extent that is required to make sure the compilation won't fail // in unpredictable spots. - partial class CompilerTypeSystemContext + public partial class CompilerTypeSystemContext { /// /// Ensures that the type can be fully loaded. The method will throw one of the type system @@ -33,7 +33,7 @@ public void EnsureLoadableMethod(MethodDesc method) } } - class ValidTypeHashTable : LockFreeReaderHashtable + private sealed class ValidTypeHashTable : LockFreeReaderHashtable { protected override bool CompareKeyToValue(TypeDesc key, TypeDesc value) => key == value; protected override bool CompareValueToValue(TypeDesc value1, TypeDesc value2) => value1 == value2; diff --git a/src/coreclr/tools/Common/Compiler/CompilerTypeSystemContext.cs b/src/coreclr/tools/Common/Compiler/CompilerTypeSystemContext.cs index 510a657cc84d74..21a1a0307e6c0e 100644 --- a/src/coreclr/tools/Common/Compiler/CompilerTypeSystemContext.cs +++ b/src/coreclr/tools/Common/Compiler/CompilerTypeSystemContext.cs @@ -21,7 +21,7 @@ public partial class CompilerTypeSystemContext : MetadataTypeSystemContext, IMet private MetadataStringDecoder _metadataStringDecoder; - private class ModuleData + private sealed class ModuleData { public string SimpleName; public string FilePath; @@ -30,7 +30,7 @@ private class ModuleData public MemoryMappedViewAccessor MappedViewAccessor; } - private class ModuleHashtable : LockFreeReaderHashtable + private sealed class ModuleHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(EcmaModule key) { @@ -42,11 +42,11 @@ protected override int GetValueHashCode(ModuleData value) } protected override bool CompareKeyToValue(EcmaModule key, ModuleData value) { - return Object.ReferenceEquals(key, value.Module); + return ReferenceEquals(key, value.Module); } protected override bool CompareValueToValue(ModuleData value1, ModuleData value2) { - return Object.ReferenceEquals(value1.Module, value2.Module); + return ReferenceEquals(value1.Module, value2.Module); } protected override ModuleData CreateValueFromKey(EcmaModule key) { @@ -56,9 +56,9 @@ protected override ModuleData CreateValueFromKey(EcmaModule key) } private readonly ModuleHashtable _moduleHashtable = new ModuleHashtable(); - private class SimpleNameHashtable : LockFreeReaderHashtable + private sealed class SimpleNameHashtable : LockFreeReaderHashtable { - StringComparer _comparer = StringComparer.OrdinalIgnoreCase; + private StringComparer _comparer = StringComparer.OrdinalIgnoreCase; protected override int GetKeyHashCode(string key) { @@ -254,10 +254,8 @@ private EcmaModule AddModule(string filePath, string expectedSimpleName, bool us } finally { - if (mappedViewAccessor != null) - mappedViewAccessor.Dispose(); - if (pdbReader != null) - pdbReader.Dispose(); + mappedViewAccessor?.Dispose(); + pdbReader?.Dispose(); } } @@ -314,8 +312,7 @@ protected override TypeDesc ConvertToCanon(TypeDesc typeToConvert, ref Canonical public MetadataStringDecoder GetMetadataStringDecoder() { - if (_metadataStringDecoder == null) - _metadataStringDecoder = new CachingMetadataStringDecoder(0x10000); // TODO: Tune the size + _metadataStringDecoder ??= new CachingMetadataStringDecoder(0x10000); // TODO: Tune the size return _metadataStringDecoder; } @@ -354,11 +351,8 @@ private PdbSymbolReader OpenAssociatedSymbolFile(string peFilePath, PEReader peR // Try to open the symbol file as portable pdb first PdbSymbolReader reader = PortablePdbSymbolReader.TryOpen(pdbFileName, GetMetadataStringDecoder(), pdbContentId); - if (reader == null) - { - // Fallback to the diasymreader for non-portable pdbs - reader = UnmanagedPdbSymbolReader.TryOpenSymbolReaderForMetadataFile(peFilePath, Path.GetDirectoryName(pdbFileName)); - } + // Fallback to the diasymreader for non-portable pdbs + reader ??= UnmanagedPdbSymbolReader.TryOpenSymbolReaderForMetadataFile(peFilePath, Path.GetDirectoryName(pdbFileName)); return reader; } diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/CompilerComparer.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/CompilerComparer.cs index 46f9e704a848ba..c95c6c318dc0cf 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/CompilerComparer.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/CompilerComparer.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Diagnostics; using System.Collections.Generic; diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/EmbeddedDataContainerNode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/EmbeddedDataContainerNode.cs index da756fcd16b55d..3aa40631fb3fae 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/EmbeddedDataContainerNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/EmbeddedDataContainerNode.cs @@ -1,12 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Internal.TypeSystem; - namespace ILCompiler.DependencyAnalysis { /// - /// Represents a node that contains a set of embedded objects. The main function is + /// Represents a node that contains a set of embedded objects. The main function is /// to serve as a base class, providing symbol name boundaries and node ordering. /// public abstract class EmbeddedDataContainerNode : ObjectNode diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/INodeWithRuntimeDeterminedDependencies.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/INodeWithRuntimeDeterminedDependencies.cs index 301cf4d2948b1c..645835a365d4cd 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/INodeWithRuntimeDeterminedDependencies.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/INodeWithRuntimeDeterminedDependencies.cs @@ -4,11 +4,10 @@ using System.Collections.Generic; using Internal.TypeSystem; +using DependencyListEntry = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyListEntry; namespace ILCompiler.DependencyAnalysis { - using DependencyListEntry = DependencyAnalysisFramework.DependencyNodeCore.DependencyListEntry; - /// /// Represents a node whose dependencies are runtime determined (they depend on the generic context) /// and which provides means to compute concrete dependencies when given the generic context. diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ISymbolNode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ISymbolNode.cs index 92ea4ca92b1593..336c0121502952 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ISymbolNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ISymbolNode.cs @@ -76,13 +76,12 @@ public interface ISymbolDefinitionNode : ISymbolNode public static class ISymbolNodeExtensions { [ThreadStatic] - static Utf8StringBuilder s_cachedUtf8StringBuilder; + private static Utf8StringBuilder s_cachedUtf8StringBuilder; public static string GetMangledName(this ISymbolNode symbolNode, NameMangler nameMangler) { Utf8StringBuilder sb = s_cachedUtf8StringBuilder; - if (sb == null) - sb = new Utf8StringBuilder(); + sb ??= new Utf8StringBuilder(); symbolNode.AppendMangledName(nameMangler, sb); string ret = sb.ToString(); diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/MethodReadOnlyDataNode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/MethodReadOnlyDataNode.cs index 205266622422e1..9a8e941f0225d2 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/MethodReadOnlyDataNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/MethodReadOnlyDataNode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Diagnostics; using Internal.Text; @@ -52,4 +51,3 @@ public override int CompareToImpl(ISortableNode other, CompilerComparer comparer #endif } } - diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectAndOffsetSymbolNode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectAndOffsetSymbolNode.cs index ab8cb36d111b81..0f15706ea685c8 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectAndOffsetSymbolNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectAndOffsetSymbolNode.cs @@ -24,7 +24,7 @@ public ObjectAndOffsetSymbolNode(ObjectNode obj, int offset, Utf8String name, bo _includeCompilationUnitPrefix = includeCompilationUnitPrefix; } - protected override string GetName(NodeFactory factory) => $"Symbol {_name.ToString()} at offset {_offset.ToStringInvariant()}"; + protected override string GetName(NodeFactory factory) => $"Symbol {_name} at offset {_offset.ToStringInvariant()}"; public override bool HasConditionalStaticDependencies => false; public override bool HasDynamicDependencies => false; diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectDataBuilder.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectDataBuilder.cs index f20020ad71051a..ff5cee89663c6b 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectDataBuilder.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectDataBuilder.cs @@ -21,10 +21,10 @@ public ObjectDataBuilder(NodeFactory factory, bool relocsOnly) : this(factory.Ta public ObjectDataBuilder(TargetDetails target, bool relocsOnly) { _target = target; - _data = new ArrayBuilder(); - _relocs = new ArrayBuilder(); + _data = default(ArrayBuilder); + _relocs = default(ArrayBuilder); Alignment = 1; - _definedSymbols = new ArrayBuilder(); + _definedSymbols = default(ArrayBuilder); #if DEBUG _numReservations = 0; _checkAllSymbolDependenciesMustBeMarked = !relocsOnly; @@ -213,7 +213,9 @@ private Reservation GetReservationTicket(int size) return ticket; } +#pragma warning disable CA1822 // Mark members as static private int ReturnReservationTicket(Reservation reservation) +#pragma warning restore CA1822 // Mark members as static { #if DEBUG Debug.Assert(_numReservations > 0); @@ -308,7 +310,7 @@ public void EmitReloc(ISymbolNode symbol, RelocType relocType, int delta = 0) Debug.Assert(delta == 0); // Do not vacate space for this kind of relocation, because // the space is embedded in the instruction. - break; + break; default: throw new NotImplementedException(); } diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectNode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectNode.cs index 68b984519d2781..5122c584ae041d 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectNode.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using ILCompiler.DependencyAnalysisFramework; -using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { @@ -61,8 +60,7 @@ public sealed override IEnumerable GetStaticDependencies(No if (relocs != null) { - if (dependencies == null) - dependencies = new DependencyList(); + dependencies ??= new DependencyList(); foreach (Relocation reloc in relocs) { diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectNodeSection.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectNodeSection.cs index f4a6179b7f393a..c5ad884fa4c93a 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectNodeSection.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ObjectNodeSection.cs @@ -1,8 +1,6 @@ // 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 ILCompiler.DependencyAnalysis { public enum SectionType @@ -41,7 +39,7 @@ public bool IsStandardSection return this == DataSection || this == ReadOnlyDataSection || this == FoldableReadOnlyDataSection || this == TextSection || this == XDataSection || this == BssSection; } } - + public static readonly ObjectNodeSection XDataSection = new ObjectNodeSection("xdata", SectionType.ReadOnly); public static readonly ObjectNodeSection DataSection = new ObjectNodeSection("data", SectionType.Writeable); public static readonly ObjectNodeSection ReadOnlyDataSection = new ObjectNodeSection("rdata", SectionType.ReadOnly); diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ShadowConcreteMethodNode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ShadowConcreteMethodNode.cs index 57ea2b981490d7..140a97f70924ee 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ShadowConcreteMethodNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/ShadowConcreteMethodNode.cs @@ -85,7 +85,7 @@ public override IEnumerable GetStaticDependencies(NodeFacto return dependencies; } - protected override string GetName(NodeFactory factory) => $"{Method.ToString()} backed by {CanonicalMethodNode.GetMangledName(factory.NameMangler)}"; + protected override string GetName(NodeFactory factory) => $"{Method} backed by {CanonicalMethodNode.GetMangledName(factory.NameMangler)}"; public sealed override bool HasConditionalStaticDependencies => false; public sealed override bool HasDynamicDependencies => false; diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/SortableDependencyNode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/SortableDependencyNode.cs index 2c677d51b052c0..a29c732e0814e3 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/SortableDependencyNode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/SortableDependencyNode.cs @@ -7,7 +7,6 @@ using System.Runtime.CompilerServices; using ILCompiler.DependencyAnalysisFramework; -using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { @@ -49,7 +48,7 @@ protected enum ObjectNodePhase protected enum ObjectNodeOrder { // - // The ordering of this sequence of nodes is deliberate and currently required for + // The ordering of this sequence of nodes is deliberate and currently required for // compiler correctness. // diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM/ARMEmitter.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM/ARMEmitter.cs index 53bcb335e0542b..dd41f891552a1f 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM/ARMEmitter.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM/ARMEmitter.cs @@ -1,7 +1,6 @@ // 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; namespace ILCompiler.DependencyAnalysis.ARM @@ -82,7 +81,7 @@ public void EmitDebugBreak() Builder.EmitByte(0xde); Builder.EmitByte(0xfe); } - + // push reg // reg range: [0..12, LR] public void EmitPUSH(Register reg) diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM/Register.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM/Register.cs index 59cc4b74753f10..5217786257072e 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM/Register.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM/Register.cs @@ -1,12 +1,6 @@ // 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.Text; -using System.Threading.Tasks; - namespace ILCompiler.DependencyAnalysis.ARM { public enum Register @@ -27,7 +21,7 @@ public enum Register R13 = 13, R14 = 14, R15 = 15, - + None = 16, RegDirect = 24, diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM/TargetRegisterMap.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM/TargetRegisterMap.cs index 73dc986c569738..4091fa26344073 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM/TargetRegisterMap.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM/TargetRegisterMap.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis.ARM diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/ARM64Emitter.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/ARM64Emitter.cs index 895f2f9d1a0553..7ef040f23c285f 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/ARM64Emitter.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/ARM64Emitter.cs @@ -175,11 +175,11 @@ public void EmitJE(ISymbolNode symbol) uint offset = symbol.RepresentsIndirectionCell ? 6u : 2u; Builder.EmitUInt(0b01010100_0000000000000000000_0_0001u | offset << 5); - + EmitJMP(symbol); } - private bool InSignedByteRange(int i) + private static bool InSignedByteRange(int i) { return i == (int)(sbyte)i; } diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/AddrMode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/AddrMode.cs index 410eb8b349fa92..e984d130bc22d5 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/AddrMode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/AddrMode.cs @@ -1,8 +1,6 @@ // 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 ILCompiler.DependencyAnalysis.ARM64 { public enum AddrModeSize diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/Register.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/Register.cs index aa102c85db7a05..05b853de18c3a9 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/Register.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/Register.cs @@ -1,12 +1,6 @@ // 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.Text; -using System.Threading.Tasks; - namespace ILCompiler.DependencyAnalysis.ARM64 { public enum Register @@ -42,9 +36,9 @@ public enum Register X28 = 28, X29 = 29, X30 = 30, - + X31 = 31, - + None = 32, NoIndex = 128, } diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/TargetRegisterMap.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/TargetRegisterMap.cs index 5a328f4c650a23..1ea6409b34d19f 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/TargetRegisterMap.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_ARM64/TargetRegisterMap.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis.ARM64 diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_LoongArch64/AddrMode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_LoongArch64/AddrMode.cs index 5616941cae238f..117c766383d938 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_LoongArch64/AddrMode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_LoongArch64/AddrMode.cs @@ -1,8 +1,6 @@ // 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 ILCompiler.DependencyAnalysis.LoongArch64 { public enum AddrModeSize diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_LoongArch64/Register.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_LoongArch64/Register.cs index 1ce65e76622878..445964479742b4 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_LoongArch64/Register.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_LoongArch64/Register.cs @@ -1,12 +1,6 @@ // 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.Text; -using System.Threading.Tasks; - namespace ILCompiler.DependencyAnalysis.LoongArch64 { public enum Register diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_LoongArch64/TargetRegisterMap.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_LoongArch64/TargetRegisterMap.cs index a1b5808c94b448..e66dd4824e3513 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_LoongArch64/TargetRegisterMap.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_LoongArch64/TargetRegisterMap.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis.LoongArch64 diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/AddrMode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/AddrMode.cs index c787523125fead..f13f68773f344e 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/AddrMode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/AddrMode.cs @@ -1,8 +1,6 @@ // 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 ILCompiler.DependencyAnalysis.X64 { public enum AddrModeSize diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/Register.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/Register.cs index 9b88bd61595278..09768266eb0657 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/Register.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/Register.cs @@ -1,12 +1,6 @@ // 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.Text; -using System.Threading.Tasks; - namespace ILCompiler.DependencyAnalysis.X64 { public enum Register diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/X64Emitter.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/X64Emitter.cs index 17135f6c4e405a..b88bb7f1002c57 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/X64Emitter.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X64/X64Emitter.cs @@ -189,7 +189,7 @@ public void EmitZeroReg(Register reg) Builder.EmitByte((byte)(0xC0 | (((int)reg & 0x07) << 3) | ((int)reg & 0x07))); } - private bool InSignedByteRange(int i) + private static bool InSignedByteRange(int i) { return i == (int)(sbyte)i; } @@ -228,8 +228,7 @@ private void EmitModRM(byte subOpcode, ref AddrMode addrMode) { byte lowOrderBitsOfBaseReg = (byte)((int)addrMode.BaseReg & 0x07); modRM |= lowOrderBitsOfBaseReg; - int offsetSize = 0; - + int offsetSize; if (addrMode.Offset == 0 && (lowOrderBitsOfBaseReg != (byte)Register.RBP)) { offsetSize = 0; @@ -250,7 +249,7 @@ private void EmitModRM(byte subOpcode, ref AddrMode addrMode) if (addrMode.BaseReg == Register.None) { - //# ifdef _TARGET_AMD64_ + //# ifdef _TARGET_AMD64_ // x64 requires SIB to avoid RIP relative address emitSibByte = true; //#else @@ -287,7 +286,7 @@ private void EmitModRM(byte subOpcode, ref AddrMode addrMode) modRM = (byte)((modRM & 0xF8) | (int)Register.RSP); Builder.EmitByte(modRM); - int indexRegAsInt = (int)(addrMode.IndexReg.HasValue ? addrMode.IndexReg.Value : Register.RSP); + int indexRegAsInt = (int)(addrMode.IndexReg ?? Register.RSP); Builder.EmitByte((byte)((addrMode.Scale << 6) + ((indexRegAsInt & 0x07) << 3) + ((int)sibByteBaseRegister & 0x07))); } diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/AddrMode.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/AddrMode.cs index b09e5a32ad152e..302e234ded3744 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/AddrMode.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/AddrMode.cs @@ -1,8 +1,6 @@ // 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 ILCompiler.DependencyAnalysis.X86 { public enum AddrModeSize diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/Register.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/Register.cs index e75f86e6bc3750..4989557832c2e7 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/Register.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/Register.cs @@ -1,12 +1,6 @@ // 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.Text; -using System.Threading.Tasks; - namespace ILCompiler.DependencyAnalysis.X86 { public enum Register @@ -19,7 +13,7 @@ public enum Register EBP = 5, ESI = 6, EDI = 7, - + None = 8, RegDirect = 24, diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/TargetRegisterMap.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/TargetRegisterMap.cs index 70ca0daf934d18..de2c913f8e1a52 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/TargetRegisterMap.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/TargetRegisterMap.cs @@ -26,7 +26,7 @@ public TargetRegisterMap(TargetOS os) Arg1 = Register.EDX; Result = Register.EAX; break; - + default: throw new NotImplementedException(); } diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/X86Emitter.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/X86Emitter.cs index cd95c3cbcf0b57..e386e9a34da6de 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/X86Emitter.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/X86Emitter.cs @@ -118,7 +118,7 @@ public void EmitRETIfEqual() Builder.EmitByte(0xC3); } - private bool InSignedByteRange(int i) + private static bool InSignedByteRange(int i) { return i == (int)(sbyte)i; } @@ -157,8 +157,7 @@ private void EmitModRM(byte subOpcode, ref AddrMode addrMode) { byte lowOrderBitsOfBaseReg = (byte)((int)addrMode.BaseReg & 0x07); modRM |= lowOrderBitsOfBaseReg; - int offsetSize = 0; - + int offsetSize; if (addrMode.Offset == 0 && (lowOrderBitsOfBaseReg != (byte)Register.EBP)) { offsetSize = 0; @@ -208,7 +207,7 @@ private void EmitModRM(byte subOpcode, ref AddrMode addrMode) { modRM = (byte)((modRM & 0xF8) | (int)Register.ESP); Builder.EmitByte(modRM); - int indexRegAsInt = (int)(addrMode.IndexReg.HasValue ? addrMode.IndexReg.Value : Register.ESP); + int indexRegAsInt = (int)(addrMode.IndexReg ?? Register.ESP); Builder.EmitByte((byte)((addrMode.Scale << 6) + ((indexRegAsInt & 0x07) << 3) + ((int)sibByteBaseRegister & 0x07))); } EmitImmediate(addrMode.Offset, offsetSize); @@ -226,7 +225,7 @@ private void EmitExtendedOpcode(int opcode) Builder.EmitByte((byte)(opcode >> 16)); } Builder.EmitByte((byte)(opcode >> 8)); - } + } private void EmitIndirInstruction(int opcode, byte subOpcode, ref AddrMode addrMode) { diff --git a/src/coreclr/tools/Common/Compiler/DevirtualizationManager.cs b/src/coreclr/tools/Common/Compiler/DevirtualizationManager.cs index 2fb34cede261f1..6222ec6d649cca 100644 --- a/src/coreclr/tools/Common/Compiler/DevirtualizationManager.cs +++ b/src/coreclr/tools/Common/Compiler/DevirtualizationManager.cs @@ -1,7 +1,6 @@ // 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 Internal.TypeSystem; using CORINFO_DEVIRTUALIZATION_DETAIL = Internal.JitInterface.CORINFO_DEVIRTUALIZATION_DETAIL; using Debug = System.Diagnostics.Debug; @@ -107,7 +106,6 @@ protected virtual MethodDesc ResolveVirtualMethod(MethodDesc declMethod, DefType } else { - MethodDesc dimMethod = null; // This isn't the correct lookup algorithm for variant default interface methods // but as we will drop any results we find in any case, it doesn't matter much. // Non-variant dispatch can simply use ResolveInterfaceMethodToDefaultImplementationOnType @@ -130,6 +128,7 @@ protected virtual MethodDesc ResolveVirtualMethod(MethodDesc declMethod, DefType if (defaultInterfaceDispatchDeclMethod != null) { + MethodDesc dimMethod; switch (implType.ResolveInterfaceMethodToDefaultImplementationOnType(defaultInterfaceDispatchDeclMethod, out dimMethod)) { case DefaultInterfaceMethodResolution.Diamond: diff --git a/src/coreclr/tools/Common/Compiler/DisplayNameHelpers.cs b/src/coreclr/tools/Common/Compiler/DisplayNameHelpers.cs index 55be359be4bea0..341c361253db28 100644 --- a/src/coreclr/tools/Common/Compiler/DisplayNameHelpers.cs +++ b/src/coreclr/tools/Common/Compiler/DisplayNameHelpers.cs @@ -7,8 +7,6 @@ using Internal.TypeSystem; using Internal.TypeSystem.Ecma; -using Debug = System.Diagnostics.Debug; - namespace ILCompiler { public static class DisplayNameHelpers @@ -140,9 +138,9 @@ public static string GetDisplayNameWithoutNamespace(this TypeDesc type) return Formatter.Instance.FormatName(type, FormatOptions.None); } - private class Formatter : TypeNameFormatter + private sealed class Formatter : TypeNameFormatter { - public readonly static Formatter Instance = new Formatter(); + public static readonly Formatter Instance = new Formatter(); public override Unit AppendName(StringBuilder sb, ArrayType type, FormatOptions options) { @@ -243,7 +241,7 @@ protected override Unit AppendNameForNestedType(StringBuilder sb, DefType nested return default; } - private void NamespaceQualify(StringBuilder sb, DefType type, FormatOptions options) + private static void NamespaceQualify(StringBuilder sb, DefType type, FormatOptions options) { if ((options & FormatOptions.NamespaceQualify) != 0) { diff --git a/src/coreclr/tools/Common/Compiler/HardwareIntrinsicHelpers.cs b/src/coreclr/tools/Common/Compiler/HardwareIntrinsicHelpers.cs index f20fa1ae352b4c..a523f1c5f0979c 100644 --- a/src/coreclr/tools/Common/Compiler/HardwareIntrinsicHelpers.cs +++ b/src/coreclr/tools/Common/Compiler/HardwareIntrinsicHelpers.cs @@ -1,12 +1,7 @@ // 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 Internal.TypeSystem; -using Internal.IL; -using Internal.IL.Stubs; -using System.Diagnostics; namespace ILCompiler { diff --git a/src/coreclr/tools/Common/Compiler/InstructionSetSupport.cs b/src/coreclr/tools/Common/Compiler/InstructionSetSupport.cs index 1ce1851dc1d108..affc29d19310c0 100644 --- a/src/coreclr/tools/Common/Compiler/InstructionSetSupport.cs +++ b/src/coreclr/tools/Common/Compiler/InstructionSetSupport.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using Internal.TypeSystem; using Internal.JitInterface; @@ -124,8 +123,8 @@ public SimdVectorLength GetVectorTSimdVector() public class InstructionSetSupportBuilder { - static Dictionary> s_instructionSetSupport = ComputeInstructionSetSupport(); - static Dictionary s_nonSpecifiableInstructionSets = ComputeNonSpecifiableInstructionSetSupport(); + private static Dictionary> s_instructionSetSupport = ComputeInstructionSetSupport(); + private static Dictionary s_nonSpecifiableInstructionSets = ComputeNonSpecifiableInstructionSetSupport(); private static Dictionary> ComputeInstructionSetSupport() { diff --git a/src/coreclr/tools/Common/Compiler/MethodExtensions.cs b/src/coreclr/tools/Common/Compiler/MethodExtensions.cs index 6b7513410e3188..dd43f2d4c2ae8e 100644 --- a/src/coreclr/tools/Common/Compiler/MethodExtensions.cs +++ b/src/coreclr/tools/Common/Compiler/MethodExtensions.cs @@ -1,12 +1,9 @@ // 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 Internal.TypeSystem; using Internal.TypeSystem.Ecma; -using Debug = System.Diagnostics.Debug; - namespace ILCompiler { public static class MethodExtensions diff --git a/src/coreclr/tools/Common/Compiler/NativeAotNameMangler.cs b/src/coreclr/tools/Common/Compiler/NativeAotNameMangler.cs index 65e58642acaf45..bcb1aeeed2ae21 100644 --- a/src/coreclr/tools/Common/Compiler/NativeAotNameMangler.cs +++ b/src/coreclr/tools/Common/Compiler/NativeAotNameMangler.cs @@ -15,8 +15,6 @@ namespace ILCompiler { public class NativeAotNameMangler : NameMangler { - private SHA256 _sha256; - #if !READYTORUN private readonly bool _mangleForCplusPlus; @@ -32,12 +30,12 @@ public NativeAotNameMangler(NodeMangler nodeMangler, bool mangleForCplusPlus) : public override string CompilationUnitPrefix { - set { _compilationUnitPrefix = SanitizeNameWithHash(value); } get { Debug.Assert(_compilationUnitPrefix != null); return _compilationUnitPrefix; } + set { _compilationUnitPrefix = SanitizeNameWithHash(value); } } // @@ -50,29 +48,25 @@ public override string SanitizeName(string s, bool typeName = false) { char c = s[i]; - if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'))) + if (char.IsAsciiLetter(c)) { - if (sb != null) - sb.Append(c); + sb?.Append(c); continue; } - if ((c >= '0') && (c <= '9')) + if (char.IsAsciiDigit(c)) { // C identifiers cannot start with a digit. Prepend underscores. if (i == 0) { - if (sb == null) - sb = new StringBuilder(s.Length + 2); - sb.Append("_"); + sb ??= new StringBuilder(s.Length + 2); + sb.Append('_'); } - if (sb != null) - sb.Append(c); + sb?.Append(c); continue; } - if (sb == null) - sb = new StringBuilder(s, 0, i, s.Length); + sb ??= new StringBuilder(s, 0, i, s.Length); // For CppCodeGen, replace "." (C# namespace separator) with "::" (C++ namespace separator) if (typeName && c == '.' && _mangleForCplusPlus) @@ -83,7 +77,7 @@ public override string SanitizeName(string s, bool typeName = false) // Everything else is replaced by underscore. // TODO: We assume that there won't be collisions with our own or C++ built-in identifiers. - sb.Append("_"); + sb.Append('_'); } string sanitizedName = (sb != null) ? sb.ToString() : s; @@ -121,16 +115,11 @@ private string SanitizeNameWithHash(string literal) byte[] hash; lock (this) { - if (_sha256 == null) - { - // Use SHA256 hash here to provide a high degree of uniqueness to symbol names without requiring them to be long - // This hash function provides an exceedingly high likelihood that no two strings will be given equal symbol names - // This is not considered used for security purpose; however collisions would be highly unfortunate as they will cause compilation - // failure. - _sha256 = SHA256.Create(); - } - - hash = _sha256.ComputeHash(GetBytesFromString(literal)); + // Use SHA256 hash here to provide a high degree of uniqueness to symbol names without requiring them to be long + // This hash function provides an exceedingly high likelihood that no two strings will be given equal symbol names + // This is not considered used for security purpose; however collisions would be highly unfortunate as they will cause compilation + // failure. + hash = SHA256.HashData(GetBytesFromString(literal)); } mangledName += "_" + BitConverter.ToString(hash).Replace("-", ""); @@ -151,7 +140,7 @@ private string SanitizeNameWithHash(string literal) /// Name to check for uniqueness. /// Set of names already used. /// A name based on that is not part of . - private string DisambiguateName(string origName, ISet set) + private static string DisambiguateName(string origName, ISet set) { int iter = 0; string result = origName; @@ -193,10 +182,8 @@ protected string NestMangledName(string name) /// Mangled name for . private string ComputeMangledTypeName(TypeDesc type) { - if (type is EcmaType) + if (type is EcmaType ecmaType) { - EcmaType ecmaType = (EcmaType)type; - string assemblyName = ((EcmaAssembly)ecmaType.EcmaModule).GetName().Name; bool isSystemPrivate = assemblyName.StartsWith("System.Private."); @@ -204,7 +191,7 @@ private string ComputeMangledTypeName(TypeDesc type) // but we already have a problem due to running SanitizeName without disambiguating the result // This problem needs a better fix. if (isSystemPrivate && !_mangleForCplusPlus) - assemblyName = "S.P." + assemblyName.Substring(15); + assemblyName = string.Concat("S.P.", assemblyName.AsSpan(15)); string prependAssemblyName = SanitizeName(assemblyName); var deduplicator = new HashSet(); diff --git a/src/coreclr/tools/Common/Compiler/TypeExtensions.cs b/src/coreclr/tools/Common/Compiler/TypeExtensions.cs index 47cdc09d7bb935..f50028f09c4af0 100644 --- a/src/coreclr/tools/Common/Compiler/TypeExtensions.cs +++ b/src/coreclr/tools/Common/Compiler/TypeExtensions.cs @@ -3,8 +3,6 @@ using System; using System.Runtime.CompilerServices; - -using Internal.IL; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; @@ -91,9 +89,9 @@ public static bool IsArrayAddressMethod(this MethodDesc method) public static bool IsArrayMethod(this MethodDesc method) { var arrayMethod = method as ArrayMethod; - return arrayMethod != null && (arrayMethod.Kind == ArrayMethodKind.Address || - arrayMethod.Kind == ArrayMethodKind.Get || - arrayMethod.Kind == ArrayMethodKind.Set || + return arrayMethod != null && (arrayMethod.Kind == ArrayMethodKind.Address || + arrayMethod.Kind == ArrayMethodKind.Get || + arrayMethod.Kind == ArrayMethodKind.Set || arrayMethod.Kind == ArrayMethodKind.Ctor); } @@ -279,7 +277,7 @@ public static TypeDesc MergeTypesToCommonParent(TypeDesc ta, TypeDesc tb) if (ta.IsInterface) { // - // Both classes are interfaces. Check that if one + // Both classes are interfaces. Check that if one // interface extends the other. // // Does tb extend ta ? diff --git a/src/coreclr/tools/Common/Compiler/VectorFieldLayoutAlgorithm.cs b/src/coreclr/tools/Common/Compiler/VectorFieldLayoutAlgorithm.cs index a4e49bde5fec5f..e2be8774058722 100644 --- a/src/coreclr/tools/Common/Compiler/VectorFieldLayoutAlgorithm.cs +++ b/src/coreclr/tools/Common/Compiler/VectorFieldLayoutAlgorithm.cs @@ -36,7 +36,7 @@ public override ComputedInstanceFieldLayout ComputeInstanceLayout(DefType defTyp { if (defType.Context.Target.Architecture == TargetArchitecture.ARM) { - // The Procedure Call Standard for ARM defaults to 8-byte alignment for __m128 + // The Procedure Call Standard for ARM defaults to 8-byte alignment for __m128 alignment = new LayoutInt(8); } else @@ -50,13 +50,13 @@ public override ComputedInstanceFieldLayout ComputeInstanceLayout(DefType defTyp if (defType.Context.Target.Architecture == TargetArchitecture.ARM) { - // No such type exists for the Procedure Call Standard for ARM. We will default + // No such type exists for the Procedure Call Standard for ARM. We will default // to the same alignment as __m128, which is supported by the ABI. alignment = new LayoutInt(8); } else if (defType.Context.Target.Architecture == TargetArchitecture.ARM64) { - // The Procedure Call Standard for ARM 64-bit (with SVE support) defaults to + // The Procedure Call Standard for ARM 64-bit (with SVE support) defaults to // 16-byte alignment for __m256. alignment = new LayoutInt(16); } diff --git a/src/coreclr/tools/Common/Internal/LowLevelLinq/LowLevelEnumerable.ToList.cs b/src/coreclr/tools/Common/Internal/LowLevelLinq/LowLevelEnumerable.ToList.cs index 8ab46e8b8caead..09fa4608ff6d59 100644 --- a/src/coreclr/tools/Common/Internal/LowLevelLinq/LowLevelEnumerable.ToList.cs +++ b/src/coreclr/tools/Common/Internal/LowLevelLinq/LowLevelEnumerable.ToList.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Diagnostics; using System.Collections.Generic; namespace Internal.LowLevelLinq diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/MdBinaryWriterGen.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/MdBinaryWriterGen.cs index 19e870feb39183..2069fd6c78a0cd 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/MdBinaryWriterGen.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/MdBinaryWriterGen.cs @@ -19,13 +19,9 @@ public void EmitSource() WriteLine("#pragma warning disable 649"); WriteLine(); - WriteLine("using System;"); - WriteLine("using System.IO;"); WriteLine("using System.Collections.Generic;"); WriteLine("using System.Reflection;"); - WriteLine("using Internal.LowLevelLinq;"); WriteLine("using Internal.NativeFormat;"); - WriteLine("using Debug = System.Diagnostics.Debug;"); WriteLine(); OpenScope("namespace Internal.Metadata.NativeFormat.Writer"); diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/ReaderGen.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/ReaderGen.cs index 212426070491a7..d8d13be9591efe 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/ReaderGen.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/ReaderGen.cs @@ -25,10 +25,7 @@ public void EmitSource() WriteLine("#pragma warning disable IDE0059"); WriteLine(); - WriteLine("using System;"); WriteLine("using System.Reflection;"); - WriteLine("using System.Collections.Generic;"); - WriteLine("using System.Runtime.CompilerServices;"); WriteLine("using Internal.NativeFormat;"); WriteLine(); @@ -266,7 +263,7 @@ private void EmitMetadataReader() if (record.Name == "ConstantStringValue") { WriteLine("if (IsNull(handle))"); - WriteLine(" return new ConstantStringValue();"); + WriteLine(" return default(ConstantStringValue);"); } WriteLine($"{record.Name} record;"); WriteLine("record._reader = this;"); diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs index 0b2980033426d6..dbad36a8914b64 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/SchemaDef.cs @@ -274,7 +274,7 @@ class SchemaDef ( from primitiveType in PrimitiveTypes select new RecordDef( - name: "Constant" + primitiveType.TypeName + "Value", + name: "Constant" + primitiveType.Name + "Value", members: new MemberDef[] { new MemberDef(name: "Value", typeName: primitiveType.Name, flags: primitiveType.CustomCompare ? MemberDefFlags.CustomCompare : 0) @@ -309,9 +309,9 @@ from primitiveType in PrimitiveTypes select ( from primitiveType in PrimitiveTypes select new RecordDef( - name: "Constant" + primitiveType.TypeName + "Array", + name: "Constant" + primitiveType.Name + "Array", members: new MemberDef[] { - new MemberDef(name: "Value", typeName: primitiveType.TypeName, + new MemberDef(name: "Value", typeName: primitiveType.Name, flags: MemberDefFlags.Array | (primitiveType.CustomCompare ? MemberDefFlags.CustomCompare : 0)) } ) @@ -759,10 +759,10 @@ from primitiveType in PrimitiveTypes select public static readonly string[] TypeNamesWithCollectionTypes = RecordSchema.SelectMany(r => from member in r.Members - let memberTypeName = member.TypeName as string - where memberTypeName != null && + let memberName = member.Name as string + where memberName != null && (member.Flags & MemberDefFlags.Collection) != 0 && - !PrimitiveTypes.Any(pt => pt.TypeName == memberTypeName) - select memberTypeName + !PrimitiveTypes.Any(pt => pt.Name == memberName) + select memberName ).Concat(new[] { "ScopeDefinition" }).Distinct().ToArray(); } diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/WriterGen.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/WriterGen.cs index 6b03f4d8c78698..14156a9bc003ed 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/WriterGen.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/WriterGen.cs @@ -13,15 +13,10 @@ public void EmitSource() WriteLine("#pragma warning disable 649"); WriteLine(); - WriteLine("using System;"); - WriteLine("using System.IO;"); WriteLine("using System.Collections.Generic;"); WriteLine("using System.Reflection;"); WriteLine("using System.Threading;"); - WriteLine("using Internal.LowLevelLinq;"); - WriteLine("using Internal.Metadata.NativeFormat.Writer;"); WriteLine("using Internal.NativeFormat;"); - WriteLine("using HandleType = Internal.Metadata.NativeFormat.HandleType;"); WriteLine("using Debug = System.Diagnostics.Debug;"); WriteLine(); @@ -64,8 +59,8 @@ private void EmitRecord(RecordDef record) } CloseScope("Visit"); - OpenScope("public override sealed bool Equals(Object obj)"); - WriteLine("if (Object.ReferenceEquals(this, obj)) return true;"); + OpenScope("public sealed override bool Equals(object obj)"); + WriteLine("if (ReferenceEquals(this, obj)) return true;"); WriteLine($"var other = obj as {record.Name};"); WriteLine("if (other == null) return false;"); if ((record.Flags & RecordDefFlags.ReentrantEquals) != 0) @@ -94,7 +89,7 @@ private void EmitRecord(RecordDef record) else if ((member.Flags & (MemberDefFlags.Map | MemberDefFlags.RecordRef)) != 0) { - WriteLine($"if (!Object.Equals({member.Name}, other.{member.Name})) return false;"); + WriteLine($"if (!Equals({member.Name}, other.{member.Name})) return false;"); } else if ((member.Flags & MemberDefFlags.CustomCompare) != 0) @@ -113,7 +108,7 @@ private void EmitRecord(RecordDef record) WriteLine("finally"); WriteLine("{"); WriteLine(" var popped = _equalsReentrancyGuard.Value.Pop();"); - WriteLine(" Debug.Assert(Object.ReferenceEquals(other, popped));"); + WriteLine(" Debug.Assert(ReferenceEquals(other, popped));"); WriteLine("}"); } WriteLine("return true;"); @@ -121,7 +116,7 @@ private void EmitRecord(RecordDef record) if ((record.Flags & RecordDefFlags.ReentrantEquals) != 0) WriteLine("private ThreadLocal _equalsReentrancyGuard;"); - OpenScope("public override sealed int GetHashCode()"); + OpenScope("public sealed override int GetHashCode()"); WriteLine("if (_hash != 0)"); WriteLine(" return _hash;"); WriteLine("EnterGetHashCode();"); diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MdBinaryReader.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MdBinaryReader.cs index 660c2f5d20d363..b52493d1b4bb1c 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MdBinaryReader.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MdBinaryReader.cs @@ -1,13 +1,6 @@ // 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.Collections.Generic; -using System.Reflection; -using Debug = System.Diagnostics.Debug; -using System.Threading; -using System.Text; using Internal.NativeFormat; namespace Internal.Metadata.NativeFormat diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MdBinaryReaderGen.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MdBinaryReaderGen.cs index d0e425b36790b7..f295f220a0d992 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MdBinaryReaderGen.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MdBinaryReaderGen.cs @@ -5,12 +5,8 @@ #pragma warning disable 649 -using System; -using System.IO; -using System.Collections.Generic; using System.Reflection; using Internal.NativeFormat; -using Debug = System.Diagnostics.Debug; namespace Internal.Metadata.NativeFormat { diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs index faa24815ba5c99..ad38fab1bf24e0 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs @@ -10700,7 +10700,7 @@ public ConstantStringArray GetConstantStringArray(ConstantStringArrayHandle hand public ConstantStringValue GetConstantStringValue(ConstantStringValueHandle handle) { if (IsNull(handle)) - return new ConstantStringValue(); + return default(ConstantStringValue); ConstantStringValue record; record._reader = this; record._handle = handle; diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeMetadataReader.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeMetadataReader.cs index 170dbc9efda39f..673867d0f99461 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeMetadataReader.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeMetadataReader.cs @@ -6,10 +6,12 @@ #pragma warning disable CA1066 // IEquatable implementations aren't used using System; +#pragma warning disable IDE0005 // Using directive is unnecessary. using System.IO; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; +#pragma warning restore IDE0005 // Using directive is unnecessary. using Internal.NativeFormat; namespace Internal.Metadata.NativeFormat @@ -248,7 +250,7 @@ internal bool StringEquals(ConstantStringValueHandle handle, string value) } } - internal partial class MetadataHeader + internal sealed partial class MetadataHeader { /// /// Signature should be updated every time the metadata schema changes. diff --git a/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.Primitives.cs b/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.Primitives.cs index e30810799e605f..7f7a8ebdcec53a 100644 --- a/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.Primitives.cs +++ b/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.Primitives.cs @@ -7,9 +7,7 @@ // Utilities to read native data from images, that are written by the NativeFormatWriter engine // --------------------------------------------------------------------------- -using System; using System.Diagnostics; -using System.Runtime.CompilerServices; namespace Internal.NativeFormat { diff --git a/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.String.cs b/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.String.cs index a044494d834326..e3b90b71132bf8 100644 --- a/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.String.cs +++ b/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.String.cs @@ -7,7 +7,6 @@ // UTF8 string reading methods // --------------------------------------------------------------------------- -using System; using System.Text; namespace Internal.NativeFormat diff --git a/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.cs b/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.cs index 61dcffe2403047..91ed075a79dd2c 100644 --- a/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.cs +++ b/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.cs @@ -9,7 +9,6 @@ using System; using System.Diagnostics; -using System.Runtime.CompilerServices; namespace Internal.NativeFormat { @@ -215,7 +214,7 @@ public static void SkipInteger(ref byte* stream) } } - internal unsafe partial class NativeReader + internal sealed unsafe partial class NativeReader { private readonly byte* _base; private readonly uint _size; diff --git a/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatWriter.cs b/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatWriter.cs index e81869f783a385..bd4f0e20dac96a 100644 --- a/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatWriter.cs +++ b/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatWriter.cs @@ -92,24 +92,23 @@ public Vertex Pop() #endif class NativeWriter { - List
_sections = new List
(); + private List
_sections = new List
(); - enum SavePhase + private enum SavePhase { Initial, Shrinking, Growing } + private int _iteration; + private SavePhase _phase; // Current save phase + private int _offsetAdjustment; // Cumulative offset adjustment compared to previous iteration + private int _paddingSize; // How much padding was used - int _iteration = 0; - SavePhase _phase; // Current save phase - int _offsetAdjustment; // Cumulative offset adjustment compared to previous iteration - int _paddingSize; // How much padding was used + private Dictionary _unifier = new Dictionary(); - Dictionary _unifier = new Dictionary(); - - NativePrimitiveEncoder _encoder = new NativePrimitiveEncoder(); + private NativePrimitiveEncoder _encoder; #if NATIVEFORMAT_COMPRESSION struct Tentative @@ -397,17 +396,7 @@ public void Save(Stream stream) } } -#if NATIVEFORMAT_COMPRESSION - // TODO: -#else - internal struct TypeSignatureCompressor - { - internal TypeSignatureCompressor(NativeWriter pWriter) { } - internal void Pack(Vertex vertex) { } - } -#endif - - T Unify(T vertex) where T : Vertex + private T Unify(T vertex) where T : Vertex { Vertex existing; if (_unifier.TryGetValue(vertex, out existing)) @@ -537,9 +526,9 @@ public Vertex GetCallingConventionConverterSignature(uint flags, Vertex signatur } } - class PlacedVertex : Vertex + internal sealed class PlacedVertex : Vertex { - Vertex _unified; + private Vertex _unified; public PlacedVertex(Vertex unified) { @@ -559,7 +548,7 @@ internal override void Save(NativeWriter writer) #endif class UnsignedConstant : Vertex { - uint _value; + private uint _value; public UnsignedConstant(uint value) { @@ -586,7 +575,7 @@ public override bool Equals(object other) } } - class Tuple : Vertex + internal sealed class Tuple : Vertex { private Vertex _item1; private Vertex _item2; @@ -603,8 +592,7 @@ internal override void Save(NativeWriter writer) { _item1.Save(writer); _item2.Save(writer); - if (_item3 != null) - _item3.Save(writer); + _item3?.Save(writer); } public override int GetHashCode() @@ -621,9 +609,9 @@ public override bool Equals(object obj) if (other == null) return false; - return Object.Equals(_item1, other._item1) && - Object.Equals(_item2, other._item2) && - Object.Equals(_item3, other._item3); + return Equals(_item1, other._item1) && + Equals(_item2, other._item2) && + Equals(_item3, other._item3); } } @@ -639,9 +627,9 @@ public override bool Equals(object obj) #endif class VertexBag : Vertex { - enum EntryType { Vertex, Unsigned, Signed } + private enum EntryType { Vertex, Unsigned, Signed } - struct Entry + private struct Entry { internal BagElementKind _id; internal EntryType _type; @@ -752,7 +740,7 @@ public override bool Equals(object obj) return false; for (int i = 0; i < _elements.Count; i++) - if (!Object.Equals(_elements[i], other._elements[i])) + if (!Equals(_elements[i], other._elements[i])) return false; return true; @@ -804,7 +792,7 @@ public override bool Equals(object obj) if (other == null) return false; - return Object.Equals(_methodName, other._methodName) && Object.Equals(_signature, other._signature); + return Equals(_methodName, other._methodName) && Equals(_signature, other._signature); } } @@ -876,7 +864,7 @@ public override bool Equals(object obj) if (other == null) return false; - return Object.Equals(_item, other._item); + return Equals(_item, other._item); } } @@ -916,7 +904,7 @@ public override bool Equals(object obj) if (other == null) return false; - return Object.Equals(_item, other._item); + return Equals(_item, other._item); } } @@ -936,11 +924,7 @@ public ExternalTypeSignature(uint externalTypeId) internal override void Save(NativeWriter writer) { - NativeWriter.TypeSignatureCompressor compressor = new NativeWriter.TypeSignatureCompressor(writer); - writer.WriteUnsigned((uint)TypeSignatureKind.External | (_externalTypeId << 4)); - - compressor.Pack(this); } public override int GetHashCode() @@ -1021,8 +1005,8 @@ public override bool Equals(object obj) if (!( _flags == other._flags && _fptrReferenceId == other._fptrReferenceId && - Object.Equals(_containingType, other._containingType) && - Object.Equals(_methodNameAndSig, other._methodNameAndSig))) + Equals(_containingType, other._containingType) && + Equals(_methodNameAndSig, other._methodNameAndSig))) { return false; } @@ -1032,7 +1016,7 @@ public override bool Equals(object obj) if (other._args == null) return false; if (other._args.Length != _args.Length) return false; for (uint iArg = 0; _args != null && iArg < _args.Length; iArg++) - if (!Object.Equals(_args[iArg], other._args[iArg])) + if (!Equals(_args[iArg], other._args[iArg])) return false; } else if (other._args != null) @@ -1079,10 +1063,10 @@ public override bool Equals(object obj) if (other == null) return false; - if (!Object.Equals(other._containingType, _containingType)) + if (!Equals(other._containingType, _containingType)) return false; - if (!Object.Equals(other._name, _name)) + if (!Equals(other._name, _name)) return false; return true; @@ -1108,8 +1092,7 @@ public FixupSignature(FixupSignatureKind kind, Vertex signature) internal override void Save(NativeWriter writer) { writer.WriteUnsigned((uint)_kind); - if (_signature != null) - _signature.Save(writer); + _signature?.Save(writer); } public override int GetHashCode() @@ -1126,7 +1109,7 @@ public override bool Equals(object obj) if (other._kind != _kind) return false; - if (!Object.Equals(other._signature, _signature)) + if (!Equals(other._signature, _signature)) return false; return true; @@ -1166,7 +1149,7 @@ public override bool Equals(object obj) if (other == null) return false; - if (!Object.Equals(other._type, _type)) + if (!Equals(other._type, _type)) return false; if (other._staticDataKind != _staticDataKind) @@ -1209,7 +1192,7 @@ public override bool Equals(object obj) if (other == null) return false; - if (!Object.Equals(other._type, _type)) + if (!Equals(other._type, _type)) return false; if (other._slot != _slot) @@ -1273,13 +1256,13 @@ public override bool Equals(object obj) _callingConvention == other._callingConvention && _genericArgCount == other._genericArgCount && _parameters.Length == other._parameters.Length && - Object.Equals(_returnType, other._returnType))) + Equals(_returnType, other._returnType))) { return false; } for (int i = 0; i < _parameters.Length; i++) - if (!Object.Equals(_parameters[i], other._parameters[i])) + if (!Equals(_parameters[i], other._parameters[i])) return false; return true; @@ -1304,12 +1287,8 @@ public ModifierTypeSignature(TypeModifierKind modifier, Vertex param) internal override void Save(NativeWriter writer) { - NativeWriter.TypeSignatureCompressor compressor = new NativeWriter.TypeSignatureCompressor(writer); - writer.WriteUnsigned((uint)TypeSignatureKind.Modifier | ((uint)_modifier << 4)); _param.Save(writer); - - compressor.Pack(this); } public override int GetHashCode() @@ -1323,7 +1302,7 @@ public override bool Equals(object obj) if (other == null) return false; - return _modifier == other._modifier && Object.Equals(_param, other._param); + return _modifier == other._modifier && Equals(_param, other._param); } } @@ -1343,11 +1322,7 @@ public VariableTypeSignature(uint index, bool method) internal override void Save(NativeWriter writer) { - NativeWriter.TypeSignatureCompressor compressor = new NativeWriter.TypeSignatureCompressor(writer); - writer.WriteUnsigned((uint)TypeSignatureKind.Variable | (_variableId << 4)); - - compressor.Pack(this); } public override int GetHashCode() @@ -1383,14 +1358,10 @@ public InstantiationTypeSignature(Vertex typeDef, Vertex[] args) internal override void Save(NativeWriter writer) { - NativeWriter.TypeSignatureCompressor compressor = new NativeWriter.TypeSignatureCompressor(writer); - writer.WriteUnsigned((uint)TypeSignatureKind.Instantiation | ((uint)_args.Length << 4)); _typeDef.Save(writer); for (int iArg = 0; iArg < _args.Length; iArg++) _args[iArg].Save(writer); - - compressor.Pack(this); } public override int GetHashCode() @@ -1409,11 +1380,11 @@ public override bool Equals(object obj) if (other == null) return false; - if (_args.Length != other._args.Length || !Object.Equals(_typeDef, other._typeDef)) + if (_args.Length != other._args.Length || !Equals(_typeDef, other._typeDef)) return false; for (uint iArg = 0; iArg < _args.Length; iArg++) - if (!Object.Equals(_args[iArg], other._args[iArg])) + if (!Equals(_args[iArg], other._args[iArg])) return false; return true; @@ -1444,8 +1415,6 @@ public MDArrayTypeSignature(Vertex arrayElementType, uint rank, uint[] bounds, u internal override void Save(NativeWriter writer) { - NativeWriter.TypeSignatureCompressor compressor = new NativeWriter.TypeSignatureCompressor(writer); - writer.WriteUnsigned((uint)TypeSignatureKind.MultiDimArray | ((uint)_rank << 4)); _arrayElementType.Save(writer); @@ -1456,8 +1425,6 @@ internal override void Save(NativeWriter writer) writer.WriteUnsigned((uint)_lowerBounds.Length); foreach (uint b in _lowerBounds) writer.WriteUnsigned(b); - - compressor.Pack(this); } public override int GetHashCode() @@ -1479,7 +1446,7 @@ public override bool Equals(object obj) if (other == null) return false; - if (!Object.Equals(_arrayElementType, other._arrayElementType) || + if (!Equals(_arrayElementType, other._arrayElementType) || _rank != other._rank || _bounds.Length != other._bounds.Length || _lowerBounds.Length != other._lowerBounds.Length) @@ -1741,7 +1708,7 @@ class VertexArray : Vertex ///
private uint _entryIndexSize; - class VertexLeaf : Vertex + private sealed class VertexLeaf : Vertex { private Vertex _vertex; private int _leafIndex; @@ -1756,14 +1723,11 @@ internal override void Save(NativeWriter writer) { writer.WriteUnsigned((uint)_leafIndex << 2); - if (_vertex != null) - { - _vertex.Save(writer); - } + _vertex?.Save(writer); } } - class VertexTree : Vertex + private sealed class VertexTree : Vertex { private Vertex _first; private Vertex _second; @@ -1801,8 +1765,7 @@ internal override void Save(NativeWriter writer) writer.WriteUnsigned(value); - if (_first != null) - _first.Save(writer); + _first?.Save(writer); } } @@ -1830,7 +1793,7 @@ private Vertex ExpandBlock(int index, int depth, bool place, out bool isLeaf) if (first == null || second == null) { VertexLeaf leaf = new VertexLeaf( - first == null ? second : first, + first ?? second, (first == null ? index + 1 : index) & (BlockSize - 1)); if (place) @@ -1921,8 +1884,7 @@ public void ExpandLayout() VertexLeaf nullBlock = null; for (int i = 0; i < _entries.Count; i += BlockSize) { - bool isLeaf; - Vertex block = ExpandBlock(i, 4, true, out isLeaf); + Vertex block = ExpandBlock(i, 4, true, out _); if (block == null) { @@ -2009,7 +1971,7 @@ internal override void Save(NativeWriter writer) #endif class VertexHashtable : Vertex { - struct Entry + private struct Entry { public Entry(uint hashcode, Vertex vertex) { @@ -2059,7 +2021,7 @@ public void Append(uint hashcode, Vertex element) } // Returns 1 + log2(x) rounded up, 0 iff x == 0 - static int HighestBit(uint x) + private static int HighestBit(uint x) { int ret = 0; while (x != 0) @@ -2071,7 +2033,7 @@ static int HighestBit(uint x) } // Helper method to back patch entry index in the bucket table - static void PatchEntryIndex(NativeWriter writer, int patchOffset, int entryIndexSize, int entryIndex) + private static void PatchEntryIndex(NativeWriter writer, int patchOffset, int entryIndexSize, int entryIndex) { if (entryIndexSize == 0) { @@ -2091,7 +2053,7 @@ static void PatchEntryIndex(NativeWriter writer, int patchOffset, int entryIndex } } - void ComputeLayout() + private void ComputeLayout() { uint bucketsEstimate = (uint)(_Entries.Count / _nFillFactor); @@ -2117,7 +2079,6 @@ internal override void Save(NativeWriter writer) ComputeLayout(); int nEntries = _Entries.Count; - int startOffset = writer.GetCurrentOffset(); uint bucketMask = (_nBuckets - 1); // Lowest two bits are entry index size, the rest is log2 number of buckets diff --git a/src/coreclr/tools/Common/Internal/Runtime/CorConstants.cs b/src/coreclr/tools/Common/Internal/Runtime/CorConstants.cs index 5591b062f551ea..9754321213b9de 100644 --- a/src/coreclr/tools/Common/Internal/Runtime/CorConstants.cs +++ b/src/coreclr/tools/Common/Internal/Runtime/CorConstants.cs @@ -1,8 +1,6 @@ // 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 Internal.CorConstants { public enum CorElementType : byte diff --git a/src/coreclr/tools/Common/Internal/Runtime/EETypeBuilderHelpers.cs b/src/coreclr/tools/Common/Internal/Runtime/EETypeBuilderHelpers.cs index a225665dcee12b..db9e131861ca4a 100644 --- a/src/coreclr/tools/Common/Internal/Runtime/EETypeBuilderHelpers.cs +++ b/src/coreclr/tools/Common/Internal/Runtime/EETypeBuilderHelpers.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Diagnostics; using Internal.TypeSystem; @@ -97,7 +96,9 @@ public static ushort ComputeFlags(TypeDesc type) // the rest of the padding data. // If paddings of greater than 7 bytes are necessary, then the high bits of the field represent that padding private const uint ValueTypePaddingLowMask = 0x7; +#pragma warning disable CA1823 // Avoid unused private fields private const uint ValueTypePaddingHighMask = 0xFFFFFF00; +#pragma warning restore CA1823 // Avoid unused private fields private const uint ValueTypePaddingMax = 0x07FFFFFF; private const int ValueTypePaddingHighShift = 8; private const uint ValueTypePaddingAlignmentMask = 0xF8; diff --git a/src/coreclr/tools/Common/Internal/Runtime/EETypeOptionalFieldsBuilder.cs b/src/coreclr/tools/Common/Internal/Runtime/EETypeOptionalFieldsBuilder.cs index 6481e6ef32cf50..e8d7f8407ec554 100644 --- a/src/coreclr/tools/Common/Internal/Runtime/EETypeOptionalFieldsBuilder.cs +++ b/src/coreclr/tools/Common/Internal/Runtime/EETypeOptionalFieldsBuilder.cs @@ -2,15 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Runtime.InteropServices; -using Internal.Runtime; using Internal.NativeFormat; using System.Diagnostics; using System.Text; namespace Internal.Runtime { - internal unsafe partial class EETypeOptionalFieldsBuilder + internal sealed unsafe partial class EETypeOptionalFieldsBuilder { private NativePrimitiveEncoder _encoder; private OptionalField[] _rgFields = new OptionalField[(int)EETypeOptionalFieldTag.Count]; @@ -18,17 +16,17 @@ internal unsafe partial class EETypeOptionalFieldsBuilder private struct OptionalField { internal bool _fieldPresent; - internal UInt32 _value; + internal uint _value; } internal EETypeOptionalFieldsBuilder() { } - internal UInt32 GetFieldValue(EETypeOptionalFieldTag eTag, UInt32 defaultValueIfNotFound) + internal uint GetFieldValue(EETypeOptionalFieldTag eTag, uint defaultValueIfNotFound) { return _rgFields[(int)eTag]._fieldPresent ? _rgFields[(int)eTag]._value : defaultValueIfNotFound; } - internal void SetFieldValue(EETypeOptionalFieldTag eTag, UInt32 value) + internal void SetFieldValue(EETypeOptionalFieldTag eTag, uint value) { _rgFields[(int)eTag]._fieldPresent = true; _rgFields[(int)eTag]._value = value; @@ -49,7 +47,7 @@ private int Encode() if (eLastTag == EETypeOptionalFieldTag.Count) return 0; - _encoder = new NativePrimitiveEncoder(); + _encoder = default(NativePrimitiveEncoder); _encoder.Init(); for (EETypeOptionalFieldTag eTag = 0; eTag < EETypeOptionalFieldTag.Count; eTag++) @@ -98,13 +96,13 @@ public override string ToString() } else { - sb.Append("x"); + sb.Append('x'); } if (i != (int)EETypeOptionalFieldTag.Count - 1) { - sb.Append("_"); + sb.Append('_'); } } diff --git a/src/coreclr/tools/Common/Internal/Runtime/GCDescEncoder.cs b/src/coreclr/tools/Common/Internal/Runtime/GCDescEncoder.cs index c842e61164ccf3..207f67e1522cbf 100644 --- a/src/coreclr/tools/Common/Internal/Runtime/GCDescEncoder.cs +++ b/src/coreclr/tools/Common/Internal/Runtime/GCDescEncoder.cs @@ -154,7 +154,7 @@ private static void EncodeAllGCPointersArrayGCDesc(ref T builder, int baseSiz where T : struct, ITargetBinaryWriter { // Construct the gc info as if this array contains exactly one pointer - // - the encoding trick where the size of the series is measured as a difference from + // - the encoding trick where the size of the series is measured as a difference from // total object size will make this work for arbitrary array lengths // Series size diff --git a/src/coreclr/tools/Common/Internal/Runtime/InterfaceDispatchCellCachePointerFlags.cs b/src/coreclr/tools/Common/Internal/Runtime/InterfaceDispatchCellCachePointerFlags.cs index a8fb3254fc2c00..bff58e834d218e 100644 --- a/src/coreclr/tools/Common/Internal/Runtime/InterfaceDispatchCellCachePointerFlags.cs +++ b/src/coreclr/tools/Common/Internal/Runtime/InterfaceDispatchCellCachePointerFlags.cs @@ -1,8 +1,6 @@ // 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 Internal.Runtime { // diff --git a/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs b/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs index cc286f81b03619..4c5799acf72ba4 100644 --- a/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs +++ b/src/coreclr/tools/Common/Internal/Runtime/ModuleHeaders.cs @@ -17,7 +17,7 @@ internal struct ReadyToRunHeaderConstants public const ushort CurrentMajorVersion = 8; public const ushort CurrentMinorVersion = 0; } - +#if READYTORUN #pragma warning disable 0169 internal struct ReadyToRunHeader { @@ -34,6 +34,7 @@ internal struct ReadyToRunHeader // Array of sections follows. }; #pragma warning restore 0169 +#endif // // ReadyToRunSectionType IDs are used by the runtime to look up specific global data sections diff --git a/src/coreclr/tools/Common/Internal/Runtime/ReadyToRunConstants.cs b/src/coreclr/tools/Common/Internal/Runtime/ReadyToRunConstants.cs index b0126289eb7a9e..15c02b57113ab6 100644 --- a/src/coreclr/tools/Common/Internal/Runtime/ReadyToRunConstants.cs +++ b/src/coreclr/tools/Common/Internal/Runtime/ReadyToRunConstants.cs @@ -80,7 +80,7 @@ public enum ReadyToRunVirtualFunctionOverrideFlags : uint } [Flags] - enum ReadyToRunCrossModuleInlineFlags : uint + internal enum ReadyToRunCrossModuleInlineFlags : uint { CrossModuleInlinee = 0x1, HasCrossModuleInliners = 0x2, diff --git a/src/coreclr/tools/Common/Internal/Runtime/UniversalGenericParameterLayout.cs b/src/coreclr/tools/Common/Internal/Runtime/UniversalGenericParameterLayout.cs index d3d576972e6c40..47d9234f1fbf66 100644 --- a/src/coreclr/tools/Common/Internal/Runtime/UniversalGenericParameterLayout.cs +++ b/src/coreclr/tools/Common/Internal/Runtime/UniversalGenericParameterLayout.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Diagnostics; - using Internal.TypeSystem; namespace Internal.Runtime @@ -17,27 +14,27 @@ private enum HasVarsInvestigationLevel } /// - /// IF THESE SEMANTICS EVER CHANGE UPDATE THE LOGIC WHICH DEFINES THIS BEHAVIOR IN - /// THE DYNAMIC TYPE LOADER AS WELL AS THE COMPILER. + /// IF THESE SEMANTICS EVER CHANGE UPDATE THE LOGIC WHICH DEFINES THIS BEHAVIOR IN + /// THE DYNAMIC TYPE LOADER AS WELL AS THE COMPILER. /// (There is a version of this in TypeLoaderEnvironment.SignatureParsing.cs that must be kept in sync with this.) /// /// Parameter's are considered to have type layout dependent on their generic instantiation - /// if the type of the parameter in its signature is a type variable, or if the type is a generic + /// if the type of the parameter in its signature is a type variable, or if the type is a generic /// structure which meets 2 characteristics: /// 1. Structure size/layout is affected by the size/layout of one or more of its generic parameters /// 2. One or more of the generic parameters is a type variable, or a generic structure which also recursively /// would satisfy constraint 2. (Note, that in the recursion case, whether or not the structure is affected /// by the size/layout of its generic parameters is not investigated.) - /// + /// /// Examples parameter types, and behavior. - /// + /// /// T = true /// List[T] = false /// StructNotDependentOnArgsForSize[T] = false /// GenStructDependencyOnArgsForSize[T] = true /// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[T]] = true /// StructNotDependentOnArgsForSize[GenStructDependencyOnArgsForSize[List[T]]]] = false - /// + /// /// Example non-parameter type behavior /// T = true /// List[T] = false diff --git a/src/coreclr/tools/Common/Internal/Text/Utf8String.cs b/src/coreclr/tools/Common/Internal/Text/Utf8String.cs index 9b44102c582c5a..360aa3d27e943c 100644 --- a/src/coreclr/tools/Common/Internal/Text/Utf8String.cs +++ b/src/coreclr/tools/Common/Internal/Text/Utf8String.cs @@ -3,7 +3,6 @@ using System; using System.Numerics; -using System.Runtime.CompilerServices; using System.Text; namespace Internal.Text @@ -43,7 +42,7 @@ public override bool Equals(object obj) return (obj is Utf8String) && Equals((Utf8String)obj); } - public unsafe override int GetHashCode() + public override unsafe int GetHashCode() { int length = _value.Length; uint hash = (uint)length; diff --git a/src/coreclr/tools/Common/Internal/Text/Utf8StringBuilder.cs b/src/coreclr/tools/Common/Internal/Text/Utf8StringBuilder.cs index a2144946a08ac3..edf5b185b3c442 100644 --- a/src/coreclr/tools/Common/Internal/Text/Utf8StringBuilder.cs +++ b/src/coreclr/tools/Common/Internal/Text/Utf8StringBuilder.cs @@ -10,7 +10,7 @@ namespace Internal.Text public class Utf8StringBuilder { private byte[] _buffer = Array.Empty(); - private int _length = 0; + private int _length; public Utf8StringBuilder() { @@ -103,7 +103,7 @@ private void Grow(int extraSpace) _buffer = newBuffer; } - // Find the boundary of the last character prior to a position + // Find the boundary of the last character prior to a position // If pos points to the last byte of a char, then return pos; Otherwise, // return the position of the last byte of the preceding char. public int LastCharBoundary(int pos) diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoBase.cs b/src/coreclr/tools/Common/JitInterface/CorInfoBase.cs index 541c0dc424c550..2aa2105765b84d 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoBase.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoBase.cs @@ -10,10 +10,10 @@ namespace Internal.JitInterface { - unsafe partial class CorInfoImpl + internal unsafe partial class CorInfoImpl { [UnmanagedCallersOnly] - static byte _isIntrinsic(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn) + private static byte _isIntrinsic(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn) { var _this = GetThis(thisHandle); try @@ -28,7 +28,7 @@ static byte _isIntrinsic(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_ } [UnmanagedCallersOnly] - static uint _getMethodAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn) + private static uint _getMethodAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn) { var _this = GetThis(thisHandle); try @@ -43,7 +43,7 @@ static uint _getMethodAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_ME } [UnmanagedCallersOnly] - static void _setMethodAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CorInfoMethodRuntimeFlags attribs) + private static void _setMethodAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CorInfoMethodRuntimeFlags attribs) { var _this = GetThis(thisHandle); try @@ -57,7 +57,7 @@ static void _setMethodAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_ME } [UnmanagedCallersOnly] - static void _getMethodSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CORINFO_SIG_INFO* sig, CORINFO_CLASS_STRUCT_* memberParent) + private static void _getMethodSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CORINFO_SIG_INFO* sig, CORINFO_CLASS_STRUCT_* memberParent) { var _this = GetThis(thisHandle); try @@ -71,7 +71,7 @@ static void _getMethodSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD } [UnmanagedCallersOnly] - static byte _getMethodInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CORINFO_METHOD_INFO* info) + private static byte _getMethodInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CORINFO_METHOD_INFO* info) { var _this = GetThis(thisHandle); try @@ -86,7 +86,7 @@ static byte _getMethodInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHO } [UnmanagedCallersOnly] - static CorInfoInline _canInline(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd) + private static CorInfoInline _canInline(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd) { var _this = GetThis(thisHandle); try @@ -101,7 +101,7 @@ static CorInfoInline _canInline(IntPtr thisHandle, IntPtr* ppException, CORINFO_ } [UnmanagedCallersOnly] - static void _beginInlining(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* inlinerHnd, CORINFO_METHOD_STRUCT_* inlineeHnd) + private static void _beginInlining(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* inlinerHnd, CORINFO_METHOD_STRUCT_* inlineeHnd) { var _this = GetThis(thisHandle); try @@ -115,7 +115,7 @@ static void _beginInlining(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHO } [UnmanagedCallersOnly] - static void _reportInliningDecision(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* inlinerHnd, CORINFO_METHOD_STRUCT_* inlineeHnd, CorInfoInline inlineResult, byte* reason) + private static void _reportInliningDecision(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* inlinerHnd, CORINFO_METHOD_STRUCT_* inlineeHnd, CorInfoInline inlineResult, byte* reason) { var _this = GetThis(thisHandle); try @@ -129,7 +129,7 @@ static void _reportInliningDecision(IntPtr thisHandle, IntPtr* ppException, CORI } [UnmanagedCallersOnly] - static byte _canTailCall(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* declaredCalleeHnd, CORINFO_METHOD_STRUCT_* exactCalleeHnd, byte fIsTailPrefix) + private static byte _canTailCall(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* declaredCalleeHnd, CORINFO_METHOD_STRUCT_* exactCalleeHnd, byte fIsTailPrefix) { var _this = GetThis(thisHandle); try @@ -144,7 +144,7 @@ static byte _canTailCall(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_ } [UnmanagedCallersOnly] - static void _reportTailCallDecision(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd, byte fIsTailPrefix, CorInfoTailCall tailCallResult, byte* reason) + private static void _reportTailCallDecision(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd, byte fIsTailPrefix, CorInfoTailCall tailCallResult, byte* reason) { var _this = GetThis(thisHandle); try @@ -158,7 +158,7 @@ static void _reportTailCallDecision(IntPtr thisHandle, IntPtr* ppException, CORI } [UnmanagedCallersOnly] - static void _getEHinfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint EHnumber, CORINFO_EH_CLAUSE* clause) + private static void _getEHinfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint EHnumber, CORINFO_EH_CLAUSE* clause) { var _this = GetThis(thisHandle); try @@ -172,7 +172,7 @@ static void _getEHinfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_ST } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _getMethodClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method) + private static CORINFO_CLASS_STRUCT_* _getMethodClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method) { var _this = GetThis(thisHandle); try @@ -187,7 +187,7 @@ static void _getEHinfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_ST } [UnmanagedCallersOnly] - static CORINFO_MODULE_STRUCT_* _getMethodModule(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method) + private static CORINFO_MODULE_STRUCT_* _getMethodModule(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method) { var _this = GetThis(thisHandle); try @@ -202,7 +202,7 @@ static void _getEHinfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_ST } [UnmanagedCallersOnly] - static void _getMethodVTableOffset(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, uint* offsetOfIndirection, uint* offsetAfterIndirection, bool* isRelative) + private static void _getMethodVTableOffset(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, uint* offsetOfIndirection, uint* offsetAfterIndirection, bool* isRelative) { var _this = GetThis(thisHandle); try @@ -216,7 +216,7 @@ static void _getMethodVTableOffset(IntPtr thisHandle, IntPtr* ppException, CORIN } [UnmanagedCallersOnly] - static byte _resolveVirtualMethod(IntPtr thisHandle, IntPtr* ppException, CORINFO_DEVIRTUALIZATION_INFO* info) + private static byte _resolveVirtualMethod(IntPtr thisHandle, IntPtr* ppException, CORINFO_DEVIRTUALIZATION_INFO* info) { var _this = GetThis(thisHandle); try @@ -231,7 +231,7 @@ static byte _resolveVirtualMethod(IntPtr thisHandle, IntPtr* ppException, CORINF } [UnmanagedCallersOnly] - static CORINFO_METHOD_STRUCT_* _getUnboxedEntry(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, bool* requiresInstMethodTableArg) + private static CORINFO_METHOD_STRUCT_* _getUnboxedEntry(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, bool* requiresInstMethodTableArg) { var _this = GetThis(thisHandle); try @@ -246,7 +246,7 @@ static byte _resolveVirtualMethod(IntPtr thisHandle, IntPtr* ppException, CORINF } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _getDefaultComparerClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* elemType) + private static CORINFO_CLASS_STRUCT_* _getDefaultComparerClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* elemType) { var _this = GetThis(thisHandle); try @@ -261,7 +261,7 @@ static byte _resolveVirtualMethod(IntPtr thisHandle, IntPtr* ppException, CORINF } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _getDefaultEqualityComparerClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* elemType) + private static CORINFO_CLASS_STRUCT_* _getDefaultEqualityComparerClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* elemType) { var _this = GetThis(thisHandle); try @@ -276,7 +276,7 @@ static byte _resolveVirtualMethod(IntPtr thisHandle, IntPtr* ppException, CORINF } [UnmanagedCallersOnly] - static void _expandRawHandleIntrinsic(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_GENERICHANDLE_RESULT* pResult) + private static void _expandRawHandleIntrinsic(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_GENERICHANDLE_RESULT* pResult) { var _this = GetThis(thisHandle); try @@ -290,7 +290,7 @@ static void _expandRawHandleIntrinsic(IntPtr thisHandle, IntPtr* ppException, CO } [UnmanagedCallersOnly] - static byte _isIntrinsicType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* classHnd) + private static byte _isIntrinsicType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* classHnd) { var _this = GetThis(thisHandle); try @@ -305,7 +305,7 @@ static byte _isIntrinsicType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLA } [UnmanagedCallersOnly] - static CorInfoCallConvExtension _getUnmanagedCallConv(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, CORINFO_SIG_INFO* callSiteSig, bool* pSuppressGCTransition) + private static CorInfoCallConvExtension _getUnmanagedCallConv(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, CORINFO_SIG_INFO* callSiteSig, bool* pSuppressGCTransition) { var _this = GetThis(thisHandle); try @@ -320,7 +320,7 @@ static CorInfoCallConvExtension _getUnmanagedCallConv(IntPtr thisHandle, IntPtr* } [UnmanagedCallersOnly] - static byte _pInvokeMarshalingRequired(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, CORINFO_SIG_INFO* callSiteSig) + private static byte _pInvokeMarshalingRequired(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, CORINFO_SIG_INFO* callSiteSig) { var _this = GetThis(thisHandle); try @@ -335,7 +335,7 @@ static byte _pInvokeMarshalingRequired(IntPtr thisHandle, IntPtr* ppException, C } [UnmanagedCallersOnly] - static byte _satisfiesMethodConstraints(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* parent, CORINFO_METHOD_STRUCT_* method) + private static byte _satisfiesMethodConstraints(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* parent, CORINFO_METHOD_STRUCT_* method) { var _this = GetThis(thisHandle); try @@ -350,7 +350,7 @@ static byte _satisfiesMethodConstraints(IntPtr thisHandle, IntPtr* ppException, } [UnmanagedCallersOnly] - static byte _isCompatibleDelegate(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* objCls, CORINFO_CLASS_STRUCT_* methodParentCls, CORINFO_METHOD_STRUCT_* method, CORINFO_CLASS_STRUCT_* delegateCls, bool* pfIsOpenDelegate) + private static byte _isCompatibleDelegate(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* objCls, CORINFO_CLASS_STRUCT_* methodParentCls, CORINFO_METHOD_STRUCT_* method, CORINFO_CLASS_STRUCT_* delegateCls, bool* pfIsOpenDelegate) { var _this = GetThis(thisHandle); try @@ -365,7 +365,7 @@ static byte _isCompatibleDelegate(IntPtr thisHandle, IntPtr* ppException, CORINF } [UnmanagedCallersOnly] - static void _methodMustBeLoadedBeforeCodeIsRun(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method) + private static void _methodMustBeLoadedBeforeCodeIsRun(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method) { var _this = GetThis(thisHandle); try @@ -379,7 +379,7 @@ static void _methodMustBeLoadedBeforeCodeIsRun(IntPtr thisHandle, IntPtr* ppExce } [UnmanagedCallersOnly] - static CORINFO_METHOD_STRUCT_* _mapMethodDeclToMethodImpl(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method) + private static CORINFO_METHOD_STRUCT_* _mapMethodDeclToMethodImpl(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method) { var _this = GetThis(thisHandle); try @@ -394,7 +394,7 @@ static void _methodMustBeLoadedBeforeCodeIsRun(IntPtr thisHandle, IntPtr* ppExce } [UnmanagedCallersOnly] - static void _getGSCookie(IntPtr thisHandle, IntPtr* ppException, IntPtr* pCookieVal, IntPtr** ppCookieVal) + private static void _getGSCookie(IntPtr thisHandle, IntPtr* ppException, IntPtr* pCookieVal, IntPtr** ppCookieVal) { var _this = GetThis(thisHandle); try @@ -408,7 +408,7 @@ static void _getGSCookie(IntPtr thisHandle, IntPtr* ppException, IntPtr* pCookie } [UnmanagedCallersOnly] - static void _setPatchpointInfo(IntPtr thisHandle, IntPtr* ppException, PatchpointInfo* patchpointInfo) + private static void _setPatchpointInfo(IntPtr thisHandle, IntPtr* ppException, PatchpointInfo* patchpointInfo) { var _this = GetThis(thisHandle); try @@ -422,7 +422,7 @@ static void _setPatchpointInfo(IntPtr thisHandle, IntPtr* ppException, Patchpoin } [UnmanagedCallersOnly] - static PatchpointInfo* _getOSRInfo(IntPtr thisHandle, IntPtr* ppException, uint* ilOffset) + private static PatchpointInfo* _getOSRInfo(IntPtr thisHandle, IntPtr* ppException, uint* ilOffset) { var _this = GetThis(thisHandle); try @@ -437,7 +437,7 @@ static void _setPatchpointInfo(IntPtr thisHandle, IntPtr* ppException, Patchpoin } [UnmanagedCallersOnly] - static void _resolveToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken) + private static void _resolveToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken) { var _this = GetThis(thisHandle); try @@ -451,7 +451,7 @@ static void _resolveToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLV } [UnmanagedCallersOnly] - static byte _tryResolveToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken) + private static byte _tryResolveToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken) { var _this = GetThis(thisHandle); try @@ -466,7 +466,7 @@ static byte _tryResolveToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_RES } [UnmanagedCallersOnly] - static void _findSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint sigTOK, CORINFO_CONTEXT_STRUCT* context, CORINFO_SIG_INFO* sig) + private static void _findSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint sigTOK, CORINFO_CONTEXT_STRUCT* context, CORINFO_SIG_INFO* sig) { var _this = GetThis(thisHandle); try @@ -480,7 +480,7 @@ static void _findSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRU } [UnmanagedCallersOnly] - static void _findCallSiteSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint methTOK, CORINFO_CONTEXT_STRUCT* context, CORINFO_SIG_INFO* sig) + private static void _findCallSiteSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint methTOK, CORINFO_CONTEXT_STRUCT* context, CORINFO_SIG_INFO* sig) { var _this = GetThis(thisHandle); try @@ -494,7 +494,7 @@ static void _findCallSiteSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_MOD } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _getTokenTypeAsHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken) + private static CORINFO_CLASS_STRUCT_* _getTokenTypeAsHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken) { var _this = GetThis(thisHandle); try @@ -509,7 +509,7 @@ static void _findCallSiteSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_MOD } [UnmanagedCallersOnly] - static byte _isValidToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint metaTOK) + private static byte _isValidToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint metaTOK) { var _this = GetThis(thisHandle); try @@ -524,7 +524,7 @@ static byte _isValidToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE } [UnmanagedCallersOnly] - static byte _isValidStringRef(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint metaTOK) + private static byte _isValidStringRef(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint metaTOK) { var _this = GetThis(thisHandle); try @@ -539,7 +539,7 @@ static byte _isValidStringRef(IntPtr thisHandle, IntPtr* ppException, CORINFO_MO } [UnmanagedCallersOnly] - static int _getStringLiteral(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint metaTOK, char* buffer, int bufferSize) + private static int _getStringLiteral(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, uint metaTOK, char* buffer, int bufferSize) { var _this = GetThis(thisHandle); try @@ -554,7 +554,7 @@ static int _getStringLiteral(IntPtr thisHandle, IntPtr* ppException, CORINFO_MOD } [UnmanagedCallersOnly] - static CorInfoType _asCorInfoType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static CorInfoType _asCorInfoType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -569,7 +569,7 @@ static CorInfoType _asCorInfoType(IntPtr thisHandle, IntPtr* ppException, CORINF } [UnmanagedCallersOnly] - static byte* _getClassName(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static byte* _getClassName(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -584,7 +584,7 @@ static CorInfoType _asCorInfoType(IntPtr thisHandle, IntPtr* ppException, CORINF } [UnmanagedCallersOnly] - static byte* _getClassNameFromMetadata(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, byte** namespaceName) + private static byte* _getClassNameFromMetadata(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, byte** namespaceName) { var _this = GetThis(thisHandle); try @@ -599,7 +599,7 @@ static CorInfoType _asCorInfoType(IntPtr thisHandle, IntPtr* ppException, CORINF } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _getTypeInstantiationArgument(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, uint index) + private static CORINFO_CLASS_STRUCT_* _getTypeInstantiationArgument(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, uint index) { var _this = GetThis(thisHandle); try @@ -614,7 +614,7 @@ static CorInfoType _asCorInfoType(IntPtr thisHandle, IntPtr* ppException, CORINF } [UnmanagedCallersOnly] - static int _appendClassName(IntPtr thisHandle, IntPtr* ppException, char** ppBuf, int* pnBufLen, CORINFO_CLASS_STRUCT_* cls, byte fNamespace, byte fFullInst, byte fAssembly) + private static int _appendClassName(IntPtr thisHandle, IntPtr* ppException, char** ppBuf, int* pnBufLen, CORINFO_CLASS_STRUCT_* cls, byte fNamespace, byte fFullInst, byte fAssembly) { var _this = GetThis(thisHandle); try @@ -629,7 +629,7 @@ static int _appendClassName(IntPtr thisHandle, IntPtr* ppException, char** ppBuf } [UnmanagedCallersOnly] - static byte _isValueClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static byte _isValueClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -644,7 +644,7 @@ static byte _isValueClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_ } [UnmanagedCallersOnly] - static CorInfoInlineTypeCheck _canInlineTypeCheck(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, CorInfoInlineTypeCheckSource source) + private static CorInfoInlineTypeCheck _canInlineTypeCheck(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, CorInfoInlineTypeCheckSource source) { var _this = GetThis(thisHandle); try @@ -659,7 +659,7 @@ static CorInfoInlineTypeCheck _canInlineTypeCheck(IntPtr thisHandle, IntPtr* ppE } [UnmanagedCallersOnly] - static uint _getClassAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static uint _getClassAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -674,7 +674,7 @@ static uint _getClassAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLA } [UnmanagedCallersOnly] - static CORINFO_MODULE_STRUCT_* _getClassModule(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static CORINFO_MODULE_STRUCT_* _getClassModule(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -689,7 +689,7 @@ static uint _getClassAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLA } [UnmanagedCallersOnly] - static CORINFO_ASSEMBLY_STRUCT_* _getModuleAssembly(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* mod) + private static CORINFO_ASSEMBLY_STRUCT_* _getModuleAssembly(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* mod) { var _this = GetThis(thisHandle); try @@ -704,7 +704,7 @@ static uint _getClassAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLA } [UnmanagedCallersOnly] - static byte* _getAssemblyName(IntPtr thisHandle, IntPtr* ppException, CORINFO_ASSEMBLY_STRUCT_* assem) + private static byte* _getAssemblyName(IntPtr thisHandle, IntPtr* ppException, CORINFO_ASSEMBLY_STRUCT_* assem) { var _this = GetThis(thisHandle); try @@ -719,7 +719,7 @@ static uint _getClassAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLA } [UnmanagedCallersOnly] - static void* _LongLifetimeMalloc(IntPtr thisHandle, IntPtr* ppException, UIntPtr sz) + private static void* _LongLifetimeMalloc(IntPtr thisHandle, IntPtr* ppException, UIntPtr sz) { var _this = GetThis(thisHandle); try @@ -734,7 +734,7 @@ static uint _getClassAttribs(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLA } [UnmanagedCallersOnly] - static void _LongLifetimeFree(IntPtr thisHandle, IntPtr* ppException, void* obj) + private static void _LongLifetimeFree(IntPtr thisHandle, IntPtr* ppException, void* obj) { var _this = GetThis(thisHandle); try @@ -748,7 +748,7 @@ static void _LongLifetimeFree(IntPtr thisHandle, IntPtr* ppException, void* obj) } [UnmanagedCallersOnly] - static UIntPtr _getClassModuleIdForStatics(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, CORINFO_MODULE_STRUCT_** pModule, void** ppIndirection) + private static UIntPtr _getClassModuleIdForStatics(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, CORINFO_MODULE_STRUCT_** pModule, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -763,7 +763,7 @@ static UIntPtr _getClassModuleIdForStatics(IntPtr thisHandle, IntPtr* ppExceptio } [UnmanagedCallersOnly] - static uint _getClassSize(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static uint _getClassSize(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -778,7 +778,7 @@ static uint _getClassSize(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_ } [UnmanagedCallersOnly] - static uint _getHeapClassSize(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static uint _getHeapClassSize(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -793,7 +793,7 @@ static uint _getHeapClassSize(IntPtr thisHandle, IntPtr* ppException, CORINFO_CL } [UnmanagedCallersOnly] - static byte _canAllocateOnStack(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static byte _canAllocateOnStack(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -808,7 +808,7 @@ static byte _canAllocateOnStack(IntPtr thisHandle, IntPtr* ppException, CORINFO_ } [UnmanagedCallersOnly] - static uint _getClassAlignmentRequirement(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, byte fDoubleAlignHint) + private static uint _getClassAlignmentRequirement(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, byte fDoubleAlignHint) { var _this = GetThis(thisHandle); try @@ -823,7 +823,7 @@ static uint _getClassAlignmentRequirement(IntPtr thisHandle, IntPtr* ppException } [UnmanagedCallersOnly] - static uint _getClassGClayout(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, byte* gcPtrs) + private static uint _getClassGClayout(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, byte* gcPtrs) { var _this = GetThis(thisHandle); try @@ -838,7 +838,7 @@ static uint _getClassGClayout(IntPtr thisHandle, IntPtr* ppException, CORINFO_CL } [UnmanagedCallersOnly] - static uint _getClassNumInstanceFields(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static uint _getClassNumInstanceFields(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -853,7 +853,7 @@ static uint _getClassNumInstanceFields(IntPtr thisHandle, IntPtr* ppException, C } [UnmanagedCallersOnly] - static CORINFO_FIELD_STRUCT_* _getFieldInClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* clsHnd, int num) + private static CORINFO_FIELD_STRUCT_* _getFieldInClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* clsHnd, int num) { var _this = GetThis(thisHandle); try @@ -868,7 +868,7 @@ static uint _getClassNumInstanceFields(IntPtr thisHandle, IntPtr* ppException, C } [UnmanagedCallersOnly] - static byte _checkMethodModifier(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* hMethod, byte* modifier, byte fOptional) + private static byte _checkMethodModifier(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* hMethod, byte* modifier, byte fOptional) { var _this = GetThis(thisHandle); try @@ -883,7 +883,7 @@ static byte _checkMethodModifier(IntPtr thisHandle, IntPtr* ppException, CORINFO } [UnmanagedCallersOnly] - static CorInfoHelpFunc _getNewHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, bool* pHasSideEffects) + private static CorInfoHelpFunc _getNewHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, bool* pHasSideEffects) { var _this = GetThis(thisHandle); try @@ -898,7 +898,7 @@ static CorInfoHelpFunc _getNewHelper(IntPtr thisHandle, IntPtr* ppException, COR } [UnmanagedCallersOnly] - static CorInfoHelpFunc _getNewArrHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* arrayCls) + private static CorInfoHelpFunc _getNewArrHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* arrayCls) { var _this = GetThis(thisHandle); try @@ -913,7 +913,7 @@ static CorInfoHelpFunc _getNewArrHelper(IntPtr thisHandle, IntPtr* ppException, } [UnmanagedCallersOnly] - static CorInfoHelpFunc _getCastingHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, byte fThrowing) + private static CorInfoHelpFunc _getCastingHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, byte fThrowing) { var _this = GetThis(thisHandle); try @@ -928,7 +928,7 @@ static CorInfoHelpFunc _getCastingHelper(IntPtr thisHandle, IntPtr* ppException, } [UnmanagedCallersOnly] - static CorInfoHelpFunc _getSharedCCtorHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* clsHnd) + private static CorInfoHelpFunc _getSharedCCtorHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* clsHnd) { var _this = GetThis(thisHandle); try @@ -943,7 +943,7 @@ static CorInfoHelpFunc _getSharedCCtorHelper(IntPtr thisHandle, IntPtr* ppExcept } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _getTypeForBox(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static CORINFO_CLASS_STRUCT_* _getTypeForBox(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -958,7 +958,7 @@ static CorInfoHelpFunc _getSharedCCtorHelper(IntPtr thisHandle, IntPtr* ppExcept } [UnmanagedCallersOnly] - static CorInfoHelpFunc _getBoxHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static CorInfoHelpFunc _getBoxHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -973,7 +973,7 @@ static CorInfoHelpFunc _getBoxHelper(IntPtr thisHandle, IntPtr* ppException, COR } [UnmanagedCallersOnly] - static CorInfoHelpFunc _getUnBoxHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static CorInfoHelpFunc _getUnBoxHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -988,7 +988,7 @@ static CorInfoHelpFunc _getUnBoxHelper(IntPtr thisHandle, IntPtr* ppException, C } [UnmanagedCallersOnly] - static byte _getReadyToRunHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_LOOKUP_KIND* pGenericLookupKind, CorInfoHelpFunc id, CORINFO_CONST_LOOKUP* pLookup) + private static byte _getReadyToRunHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_LOOKUP_KIND* pGenericLookupKind, CorInfoHelpFunc id, CORINFO_CONST_LOOKUP* pLookup) { var _this = GetThis(thisHandle); try @@ -1003,7 +1003,7 @@ static byte _getReadyToRunHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO } [UnmanagedCallersOnly] - static void _getReadyToRunDelegateCtorHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pTargetMethod, mdToken targetConstraint, CORINFO_CLASS_STRUCT_* delegateType, CORINFO_LOOKUP* pLookup) + private static void _getReadyToRunDelegateCtorHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pTargetMethod, mdToken targetConstraint, CORINFO_CLASS_STRUCT_* delegateType, CORINFO_LOOKUP* pLookup) { var _this = GetThis(thisHandle); try @@ -1017,7 +1017,7 @@ static void _getReadyToRunDelegateCtorHelper(IntPtr thisHandle, IntPtr* ppExcept } [UnmanagedCallersOnly] - static byte* _getHelperName(IntPtr thisHandle, IntPtr* ppException, CorInfoHelpFunc helpFunc) + private static byte* _getHelperName(IntPtr thisHandle, IntPtr* ppException, CorInfoHelpFunc helpFunc) { var _this = GetThis(thisHandle); try @@ -1032,7 +1032,7 @@ static void _getReadyToRunDelegateCtorHelper(IntPtr thisHandle, IntPtr* ppExcept } [UnmanagedCallersOnly] - static CorInfoInitClassResult _initClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, CORINFO_METHOD_STRUCT_* method, CORINFO_CONTEXT_STRUCT* context) + private static CorInfoInitClassResult _initClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, CORINFO_METHOD_STRUCT_* method, CORINFO_CONTEXT_STRUCT* context) { var _this = GetThis(thisHandle); try @@ -1047,7 +1047,7 @@ static CorInfoInitClassResult _initClass(IntPtr thisHandle, IntPtr* ppException, } [UnmanagedCallersOnly] - static void _classMustBeLoadedBeforeCodeIsRun(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static void _classMustBeLoadedBeforeCodeIsRun(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -1061,7 +1061,7 @@ static void _classMustBeLoadedBeforeCodeIsRun(IntPtr thisHandle, IntPtr* ppExcep } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _getBuiltinClass(IntPtr thisHandle, IntPtr* ppException, CorInfoClassId classId) + private static CORINFO_CLASS_STRUCT_* _getBuiltinClass(IntPtr thisHandle, IntPtr* ppException, CorInfoClassId classId) { var _this = GetThis(thisHandle); try @@ -1076,7 +1076,7 @@ static void _classMustBeLoadedBeforeCodeIsRun(IntPtr thisHandle, IntPtr* ppExcep } [UnmanagedCallersOnly] - static CorInfoType _getTypeForPrimitiveValueClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static CorInfoType _getTypeForPrimitiveValueClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -1091,7 +1091,7 @@ static CorInfoType _getTypeForPrimitiveValueClass(IntPtr thisHandle, IntPtr* ppE } [UnmanagedCallersOnly] - static CorInfoType _getTypeForPrimitiveNumericClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static CorInfoType _getTypeForPrimitiveNumericClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -1106,7 +1106,7 @@ static CorInfoType _getTypeForPrimitiveNumericClass(IntPtr thisHandle, IntPtr* p } [UnmanagedCallersOnly] - static byte _canCast(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* child, CORINFO_CLASS_STRUCT_* parent) + private static byte _canCast(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* child, CORINFO_CLASS_STRUCT_* parent) { var _this = GetThis(thisHandle); try @@ -1121,7 +1121,7 @@ static byte _canCast(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUC } [UnmanagedCallersOnly] - static byte _areTypesEquivalent(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2) + private static byte _areTypesEquivalent(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2) { var _this = GetThis(thisHandle); try @@ -1136,7 +1136,7 @@ static byte _areTypesEquivalent(IntPtr thisHandle, IntPtr* ppException, CORINFO_ } [UnmanagedCallersOnly] - static TypeCompareState _compareTypesForCast(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* fromClass, CORINFO_CLASS_STRUCT_* toClass) + private static TypeCompareState _compareTypesForCast(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* fromClass, CORINFO_CLASS_STRUCT_* toClass) { var _this = GetThis(thisHandle); try @@ -1151,7 +1151,7 @@ static TypeCompareState _compareTypesForCast(IntPtr thisHandle, IntPtr* ppExcept } [UnmanagedCallersOnly] - static TypeCompareState _compareTypesForEquality(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2) + private static TypeCompareState _compareTypesForEquality(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2) { var _this = GetThis(thisHandle); try @@ -1166,7 +1166,7 @@ static TypeCompareState _compareTypesForEquality(IntPtr thisHandle, IntPtr* ppEx } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _mergeClasses(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2) + private static CORINFO_CLASS_STRUCT_* _mergeClasses(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2) { var _this = GetThis(thisHandle); try @@ -1181,7 +1181,7 @@ static TypeCompareState _compareTypesForEquality(IntPtr thisHandle, IntPtr* ppEx } [UnmanagedCallersOnly] - static byte _isMoreSpecificType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2) + private static byte _isMoreSpecificType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls1, CORINFO_CLASS_STRUCT_* cls2) { var _this = GetThis(thisHandle); try @@ -1196,7 +1196,7 @@ static byte _isMoreSpecificType(IntPtr thisHandle, IntPtr* ppException, CORINFO_ } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _getParentType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static CORINFO_CLASS_STRUCT_* _getParentType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -1211,7 +1211,7 @@ static byte _isMoreSpecificType(IntPtr thisHandle, IntPtr* ppException, CORINFO_ } [UnmanagedCallersOnly] - static CorInfoType _getChildType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_CLASS_STRUCT_** clsRet) + private static CorInfoType _getChildType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_CLASS_STRUCT_** clsRet) { var _this = GetThis(thisHandle); try @@ -1226,7 +1226,7 @@ static CorInfoType _getChildType(IntPtr thisHandle, IntPtr* ppException, CORINFO } [UnmanagedCallersOnly] - static byte _satisfiesClassConstraints(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static byte _satisfiesClassConstraints(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -1241,7 +1241,7 @@ static byte _satisfiesClassConstraints(IntPtr thisHandle, IntPtr* ppException, C } [UnmanagedCallersOnly] - static byte _isSDArray(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static byte _isSDArray(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -1256,7 +1256,7 @@ static byte _isSDArray(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STR } [UnmanagedCallersOnly] - static uint _getArrayRank(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static uint _getArrayRank(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -1271,7 +1271,7 @@ static uint _getArrayRank(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_ } [UnmanagedCallersOnly] - static CorInfoArrayIntrinsic _getArrayIntrinsicID(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn) + private static CorInfoArrayIntrinsic _getArrayIntrinsicID(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn) { var _this = GetThis(thisHandle); try @@ -1286,7 +1286,7 @@ static CorInfoArrayIntrinsic _getArrayIntrinsicID(IntPtr thisHandle, IntPtr* ppE } [UnmanagedCallersOnly] - static void* _getArrayInitializationData(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, uint size) + private static void* _getArrayInitializationData(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, uint size) { var _this = GetThis(thisHandle); try @@ -1301,7 +1301,7 @@ static CorInfoArrayIntrinsic _getArrayIntrinsicID(IntPtr thisHandle, IntPtr* ppE } [UnmanagedCallersOnly] - static CorInfoIsAccessAllowedResult _canAccessClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_HELPER_DESC* pAccessHelper) + private static CorInfoIsAccessAllowedResult _canAccessClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_HELPER_DESC* pAccessHelper) { var _this = GetThis(thisHandle); try @@ -1316,7 +1316,7 @@ static CorInfoIsAccessAllowedResult _canAccessClass(IntPtr thisHandle, IntPtr* p } [UnmanagedCallersOnly] - static byte* _getFieldName(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* ftn, byte** moduleName) + private static byte* _getFieldName(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* ftn, byte** moduleName) { var _this = GetThis(thisHandle); try @@ -1331,7 +1331,7 @@ static CorInfoIsAccessAllowedResult _canAccessClass(IntPtr thisHandle, IntPtr* p } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _getFieldClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field) + private static CORINFO_CLASS_STRUCT_* _getFieldClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field) { var _this = GetThis(thisHandle); try @@ -1346,7 +1346,7 @@ static CorInfoIsAccessAllowedResult _canAccessClass(IntPtr thisHandle, IntPtr* p } [UnmanagedCallersOnly] - static CorInfoType _getFieldType(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, CORINFO_CLASS_STRUCT_** structType, CORINFO_CLASS_STRUCT_* memberParent) + private static CorInfoType _getFieldType(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, CORINFO_CLASS_STRUCT_** structType, CORINFO_CLASS_STRUCT_* memberParent) { var _this = GetThis(thisHandle); try @@ -1361,7 +1361,7 @@ static CorInfoType _getFieldType(IntPtr thisHandle, IntPtr* ppException, CORINFO } [UnmanagedCallersOnly] - static uint _getFieldOffset(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field) + private static uint _getFieldOffset(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field) { var _this = GetThis(thisHandle); try @@ -1376,7 +1376,7 @@ static uint _getFieldOffset(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIEL } [UnmanagedCallersOnly] - static void _getFieldInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_ACCESS_FLAGS flags, CORINFO_FIELD_INFO* pResult) + private static void _getFieldInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_ACCESS_FLAGS flags, CORINFO_FIELD_INFO* pResult) { var _this = GetThis(thisHandle); try @@ -1390,7 +1390,7 @@ static void _getFieldInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLV } [UnmanagedCallersOnly] - static byte _isFieldStatic(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* fldHnd) + private static byte _isFieldStatic(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* fldHnd) { var _this = GetThis(thisHandle); try @@ -1405,7 +1405,7 @@ static byte _isFieldStatic(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD } [UnmanagedCallersOnly] - static void _getBoundaries(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint* cILOffsets, uint** pILOffsets, BoundaryTypes* implicitBoundaries) + private static void _getBoundaries(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint* cILOffsets, uint** pILOffsets, BoundaryTypes* implicitBoundaries) { var _this = GetThis(thisHandle); try @@ -1419,7 +1419,7 @@ static void _getBoundaries(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHO } [UnmanagedCallersOnly] - static void _setBoundaries(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint cMap, OffsetMapping* pMap) + private static void _setBoundaries(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint cMap, OffsetMapping* pMap) { var _this = GetThis(thisHandle); try @@ -1433,7 +1433,7 @@ static void _setBoundaries(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHO } [UnmanagedCallersOnly] - static void _getVars(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint* cVars, ILVarInfo** vars, bool* extendOthers) + private static void _getVars(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint* cVars, ILVarInfo** vars, bool* extendOthers) { var _this = GetThis(thisHandle); try @@ -1447,7 +1447,7 @@ static void _getVars(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRU } [UnmanagedCallersOnly] - static void _setVars(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint cVars, NativeVarInfo* vars) + private static void _setVars(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, uint cVars, NativeVarInfo* vars) { var _this = GetThis(thisHandle); try @@ -1461,7 +1461,7 @@ static void _setVars(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRU } [UnmanagedCallersOnly] - static void _reportRichMappings(IntPtr thisHandle, IntPtr* ppException, InlineTreeNode* inlineTreeNodes, uint numInlineTreeNodes, RichOffsetMapping* mappings, uint numMappings) + private static void _reportRichMappings(IntPtr thisHandle, IntPtr* ppException, InlineTreeNode* inlineTreeNodes, uint numInlineTreeNodes, RichOffsetMapping* mappings, uint numMappings) { var _this = GetThis(thisHandle); try @@ -1475,7 +1475,7 @@ static void _reportRichMappings(IntPtr thisHandle, IntPtr* ppException, InlineTr } [UnmanagedCallersOnly] - static void* _allocateArray(IntPtr thisHandle, IntPtr* ppException, UIntPtr cBytes) + private static void* _allocateArray(IntPtr thisHandle, IntPtr* ppException, UIntPtr cBytes) { var _this = GetThis(thisHandle); try @@ -1490,7 +1490,7 @@ static void _reportRichMappings(IntPtr thisHandle, IntPtr* ppException, InlineTr } [UnmanagedCallersOnly] - static void _freeArray(IntPtr thisHandle, IntPtr* ppException, void* array) + private static void _freeArray(IntPtr thisHandle, IntPtr* ppException, void* array) { var _this = GetThis(thisHandle); try @@ -1504,7 +1504,7 @@ static void _freeArray(IntPtr thisHandle, IntPtr* ppException, void* array) } [UnmanagedCallersOnly] - static CORINFO_ARG_LIST_STRUCT_* _getArgNext(IntPtr thisHandle, IntPtr* ppException, CORINFO_ARG_LIST_STRUCT_* args) + private static CORINFO_ARG_LIST_STRUCT_* _getArgNext(IntPtr thisHandle, IntPtr* ppException, CORINFO_ARG_LIST_STRUCT_* args) { var _this = GetThis(thisHandle); try @@ -1519,7 +1519,7 @@ static void _freeArray(IntPtr thisHandle, IntPtr* ppException, void* array) } [UnmanagedCallersOnly] - static CorInfoTypeWithMod _getArgType(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args, CORINFO_CLASS_STRUCT_** vcTypeRet) + private static CorInfoTypeWithMod _getArgType(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args, CORINFO_CLASS_STRUCT_** vcTypeRet) { var _this = GetThis(thisHandle); try @@ -1534,7 +1534,7 @@ static CorInfoTypeWithMod _getArgType(IntPtr thisHandle, IntPtr* ppException, CO } [UnmanagedCallersOnly] - static int _getExactClasses(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* baseType, int maxExactClasses, CORINFO_CLASS_STRUCT_** exactClsRet) + private static int _getExactClasses(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* baseType, int maxExactClasses, CORINFO_CLASS_STRUCT_** exactClsRet) { var _this = GetThis(thisHandle); try @@ -1549,7 +1549,7 @@ static int _getExactClasses(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLAS } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _getArgClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args) + private static CORINFO_CLASS_STRUCT_* _getArgClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args) { var _this = GetThis(thisHandle); try @@ -1564,7 +1564,7 @@ static int _getExactClasses(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLAS } [UnmanagedCallersOnly] - static CorInfoHFAElemType _getHFAType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* hClass) + private static CorInfoHFAElemType _getHFAType(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* hClass) { var _this = GetThis(thisHandle); try @@ -1579,7 +1579,7 @@ static CorInfoHFAElemType _getHFAType(IntPtr thisHandle, IntPtr* ppException, CO } [UnmanagedCallersOnly] - static HRESULT _GetErrorHRESULT(IntPtr thisHandle, IntPtr* ppException, _EXCEPTION_POINTERS* pExceptionPointers) + private static HRESULT _GetErrorHRESULT(IntPtr thisHandle, IntPtr* ppException, _EXCEPTION_POINTERS* pExceptionPointers) { var _this = GetThis(thisHandle); try @@ -1594,7 +1594,7 @@ static HRESULT _GetErrorHRESULT(IntPtr thisHandle, IntPtr* ppException, _EXCEPTI } [UnmanagedCallersOnly] - static uint _GetErrorMessage(IntPtr thisHandle, IntPtr* ppException, char* buffer, uint bufferLength) + private static uint _GetErrorMessage(IntPtr thisHandle, IntPtr* ppException, char* buffer, uint bufferLength) { var _this = GetThis(thisHandle); try @@ -1609,7 +1609,7 @@ static uint _GetErrorMessage(IntPtr thisHandle, IntPtr* ppException, char* buffe } [UnmanagedCallersOnly] - static int _FilterException(IntPtr thisHandle, IntPtr* ppException, _EXCEPTION_POINTERS* pExceptionPointers) + private static int _FilterException(IntPtr thisHandle, IntPtr* ppException, _EXCEPTION_POINTERS* pExceptionPointers) { var _this = GetThis(thisHandle); try @@ -1624,7 +1624,7 @@ static int _FilterException(IntPtr thisHandle, IntPtr* ppException, _EXCEPTION_P } [UnmanagedCallersOnly] - static void _ThrowExceptionForJitResult(IntPtr thisHandle, IntPtr* ppException, HRESULT result) + private static void _ThrowExceptionForJitResult(IntPtr thisHandle, IntPtr* ppException, HRESULT result) { var _this = GetThis(thisHandle); try @@ -1638,7 +1638,7 @@ static void _ThrowExceptionForJitResult(IntPtr thisHandle, IntPtr* ppException, } [UnmanagedCallersOnly] - static void _ThrowExceptionForHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_HELPER_DESC* throwHelper) + private static void _ThrowExceptionForHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_HELPER_DESC* throwHelper) { var _this = GetThis(thisHandle); try @@ -1652,7 +1652,7 @@ static void _ThrowExceptionForHelper(IntPtr thisHandle, IntPtr* ppException, COR } [UnmanagedCallersOnly] - static byte _runWithErrorTrap(IntPtr thisHandle, IntPtr* ppException, void* function, void* parameter) + private static byte _runWithErrorTrap(IntPtr thisHandle, IntPtr* ppException, void* function, void* parameter) { var _this = GetThis(thisHandle); try @@ -1667,7 +1667,7 @@ static byte _runWithErrorTrap(IntPtr thisHandle, IntPtr* ppException, void* func } [UnmanagedCallersOnly] - static byte _runWithSPMIErrorTrap(IntPtr thisHandle, IntPtr* ppException, void* function, void* parameter) + private static byte _runWithSPMIErrorTrap(IntPtr thisHandle, IntPtr* ppException, void* function, void* parameter) { var _this = GetThis(thisHandle); try @@ -1682,7 +1682,7 @@ static byte _runWithSPMIErrorTrap(IntPtr thisHandle, IntPtr* ppException, void* } [UnmanagedCallersOnly] - static void _getEEInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_EE_INFO* pEEInfoOut) + private static void _getEEInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_EE_INFO* pEEInfoOut) { var _this = GetThis(thisHandle); try @@ -1696,7 +1696,7 @@ static void _getEEInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_EE_INFO* } [UnmanagedCallersOnly] - static char* _getJitTimeLogFilename(IntPtr thisHandle, IntPtr* ppException) + private static char* _getJitTimeLogFilename(IntPtr thisHandle, IntPtr* ppException) { var _this = GetThis(thisHandle); try @@ -1711,7 +1711,7 @@ static void _getEEInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_EE_INFO* } [UnmanagedCallersOnly] - static mdToken _getMethodDefFromMethod(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* hMethod) + private static mdToken _getMethodDefFromMethod(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* hMethod) { var _this = GetThis(thisHandle); try @@ -1726,7 +1726,7 @@ static mdToken _getMethodDefFromMethod(IntPtr thisHandle, IntPtr* ppException, C } [UnmanagedCallersOnly] - static byte* _getMethodName(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, byte** moduleName) + private static byte* _getMethodName(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, byte** moduleName) { var _this = GetThis(thisHandle); try @@ -1741,7 +1741,7 @@ static mdToken _getMethodDefFromMethod(IntPtr thisHandle, IntPtr* ppException, C } [UnmanagedCallersOnly] - static byte* _getMethodNameFromMetadata(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, byte** className, byte** namespaceName, byte** enclosingClassName) + private static byte* _getMethodNameFromMetadata(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, byte** className, byte** namespaceName, byte** enclosingClassName) { var _this = GetThis(thisHandle); try @@ -1756,7 +1756,7 @@ static mdToken _getMethodDefFromMethod(IntPtr thisHandle, IntPtr* ppException, C } [UnmanagedCallersOnly] - static uint _getMethodHash(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn) + private static uint _getMethodHash(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn) { var _this = GetThis(thisHandle); try @@ -1771,7 +1771,7 @@ static uint _getMethodHash(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHO } [UnmanagedCallersOnly] - static UIntPtr _findNameOfToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* moduleHandle, mdToken token, byte* szFQName, UIntPtr FQNameCapacity) + private static UIntPtr _findNameOfToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* moduleHandle, mdToken token, byte* szFQName, UIntPtr FQNameCapacity) { var _this = GetThis(thisHandle); try @@ -1786,7 +1786,7 @@ static UIntPtr _findNameOfToken(IntPtr thisHandle, IntPtr* ppException, CORINFO_ } [UnmanagedCallersOnly] - static byte _getSystemVAmd64PassStructInRegisterDescriptor(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* structHnd, SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structPassInRegDescPtr) + private static byte _getSystemVAmd64PassStructInRegisterDescriptor(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* structHnd, SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structPassInRegDescPtr) { var _this = GetThis(thisHandle); try @@ -1801,7 +1801,7 @@ static byte _getSystemVAmd64PassStructInRegisterDescriptor(IntPtr thisHandle, In } [UnmanagedCallersOnly] - static uint _getLoongArch64PassStructInRegisterFlags(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* structHnd) + private static uint _getLoongArch64PassStructInRegisterFlags(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* structHnd) { var _this = GetThis(thisHandle); try @@ -1816,7 +1816,7 @@ static uint _getLoongArch64PassStructInRegisterFlags(IntPtr thisHandle, IntPtr* } [UnmanagedCallersOnly] - static uint _getThreadTLSIndex(IntPtr thisHandle, IntPtr* ppException, void** ppIndirection) + private static uint _getThreadTLSIndex(IntPtr thisHandle, IntPtr* ppException, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -1831,7 +1831,7 @@ static uint _getThreadTLSIndex(IntPtr thisHandle, IntPtr* ppException, void** pp } [UnmanagedCallersOnly] - static void* _getInlinedCallFrameVptr(IntPtr thisHandle, IntPtr* ppException, void** ppIndirection) + private static void* _getInlinedCallFrameVptr(IntPtr thisHandle, IntPtr* ppException, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -1846,7 +1846,7 @@ static uint _getThreadTLSIndex(IntPtr thisHandle, IntPtr* ppException, void** pp } [UnmanagedCallersOnly] - static int* _getAddrOfCaptureThreadGlobal(IntPtr thisHandle, IntPtr* ppException, void** ppIndirection) + private static int* _getAddrOfCaptureThreadGlobal(IntPtr thisHandle, IntPtr* ppException, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -1861,7 +1861,7 @@ static uint _getThreadTLSIndex(IntPtr thisHandle, IntPtr* ppException, void** pp } [UnmanagedCallersOnly] - static void* _getHelperFtn(IntPtr thisHandle, IntPtr* ppException, CorInfoHelpFunc ftnNum, void** ppIndirection) + private static void* _getHelperFtn(IntPtr thisHandle, IntPtr* ppException, CorInfoHelpFunc ftnNum, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -1876,7 +1876,7 @@ static uint _getThreadTLSIndex(IntPtr thisHandle, IntPtr* ppException, void** pp } [UnmanagedCallersOnly] - static void _getFunctionEntryPoint(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CORINFO_CONST_LOOKUP* pResult, CORINFO_ACCESS_FLAGS accessFlags) + private static void _getFunctionEntryPoint(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, CORINFO_CONST_LOOKUP* pResult, CORINFO_ACCESS_FLAGS accessFlags) { var _this = GetThis(thisHandle); try @@ -1890,7 +1890,7 @@ static void _getFunctionEntryPoint(IntPtr thisHandle, IntPtr* ppException, CORIN } [UnmanagedCallersOnly] - static void _getFunctionFixedEntryPoint(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, byte isUnsafeFunctionPointer, CORINFO_CONST_LOOKUP* pResult) + private static void _getFunctionFixedEntryPoint(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, byte isUnsafeFunctionPointer, CORINFO_CONST_LOOKUP* pResult) { var _this = GetThis(thisHandle); try @@ -1904,7 +1904,7 @@ static void _getFunctionFixedEntryPoint(IntPtr thisHandle, IntPtr* ppException, } [UnmanagedCallersOnly] - static void* _getMethodSync(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, void** ppIndirection) + private static void* _getMethodSync(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftn, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -1919,7 +1919,7 @@ static void _getFunctionFixedEntryPoint(IntPtr thisHandle, IntPtr* ppException, } [UnmanagedCallersOnly] - static CorInfoHelpFunc _getLazyStringLiteralHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* handle) + private static CorInfoHelpFunc _getLazyStringLiteralHelper(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* handle) { var _this = GetThis(thisHandle); try @@ -1934,7 +1934,7 @@ static CorInfoHelpFunc _getLazyStringLiteralHelper(IntPtr thisHandle, IntPtr* pp } [UnmanagedCallersOnly] - static CORINFO_MODULE_STRUCT_* _embedModuleHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* handle, void** ppIndirection) + private static CORINFO_MODULE_STRUCT_* _embedModuleHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* handle, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -1949,7 +1949,7 @@ static CorInfoHelpFunc _getLazyStringLiteralHelper(IntPtr thisHandle, IntPtr* pp } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _embedClassHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* handle, void** ppIndirection) + private static CORINFO_CLASS_STRUCT_* _embedClassHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* handle, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -1964,7 +1964,7 @@ static CorInfoHelpFunc _getLazyStringLiteralHelper(IntPtr thisHandle, IntPtr* pp } [UnmanagedCallersOnly] - static CORINFO_METHOD_STRUCT_* _embedMethodHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* handle, void** ppIndirection) + private static CORINFO_METHOD_STRUCT_* _embedMethodHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* handle, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -1979,7 +1979,7 @@ static CorInfoHelpFunc _getLazyStringLiteralHelper(IntPtr thisHandle, IntPtr* pp } [UnmanagedCallersOnly] - static CORINFO_FIELD_STRUCT_* _embedFieldHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* handle, void** ppIndirection) + private static CORINFO_FIELD_STRUCT_* _embedFieldHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* handle, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -1994,7 +1994,7 @@ static CorInfoHelpFunc _getLazyStringLiteralHelper(IntPtr thisHandle, IntPtr* pp } [UnmanagedCallersOnly] - static void _embedGenericHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, byte fEmbedParent, CORINFO_GENERICHANDLE_RESULT* pResult) + private static void _embedGenericHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, byte fEmbedParent, CORINFO_GENERICHANDLE_RESULT* pResult) { var _this = GetThis(thisHandle); try @@ -2008,7 +2008,7 @@ static void _embedGenericHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_ } [UnmanagedCallersOnly] - static void _getLocationOfThisType(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* context, CORINFO_LOOKUP_KIND* pLookupKind) + private static void _getLocationOfThisType(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* context, CORINFO_LOOKUP_KIND* pLookupKind) { var _this = GetThis(thisHandle); try @@ -2022,7 +2022,7 @@ static void _getLocationOfThisType(IntPtr thisHandle, IntPtr* ppException, CORIN } [UnmanagedCallersOnly] - static void _getAddressOfPInvokeTarget(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, CORINFO_CONST_LOOKUP* pLookup) + private static void _getAddressOfPInvokeTarget(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, CORINFO_CONST_LOOKUP* pLookup) { var _this = GetThis(thisHandle); try @@ -2036,7 +2036,7 @@ static void _getAddressOfPInvokeTarget(IntPtr thisHandle, IntPtr* ppException, C } [UnmanagedCallersOnly] - static void* _GetCookieForPInvokeCalliSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* szMetaSig, void** ppIndirection) + private static void* _GetCookieForPInvokeCalliSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* szMetaSig, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -2051,7 +2051,7 @@ static void _getAddressOfPInvokeTarget(IntPtr thisHandle, IntPtr* ppException, C } [UnmanagedCallersOnly] - static byte _canGetCookieForPInvokeCalliSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* szMetaSig) + private static byte _canGetCookieForPInvokeCalliSig(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* szMetaSig) { var _this = GetThis(thisHandle); try @@ -2066,7 +2066,7 @@ static byte _canGetCookieForPInvokeCalliSig(IntPtr thisHandle, IntPtr* ppExcepti } [UnmanagedCallersOnly] - static CORINFO_JUST_MY_CODE_HANDLE_* _getJustMyCodeHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, CORINFO_JUST_MY_CODE_HANDLE_** ppIndirection) + private static CORINFO_JUST_MY_CODE_HANDLE_* _getJustMyCodeHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* method, CORINFO_JUST_MY_CODE_HANDLE_** ppIndirection) { var _this = GetThis(thisHandle); try @@ -2081,7 +2081,7 @@ static byte _canGetCookieForPInvokeCalliSig(IntPtr thisHandle, IntPtr* ppExcepti } [UnmanagedCallersOnly] - static void _GetProfilingHandle(IntPtr thisHandle, IntPtr* ppException, bool* pbHookFunction, void** pProfilerHandle, bool* pbIndirectedHandles) + private static void _GetProfilingHandle(IntPtr thisHandle, IntPtr* ppException, bool* pbHookFunction, void** pProfilerHandle, bool* pbIndirectedHandles) { var _this = GetThis(thisHandle); try @@ -2095,7 +2095,7 @@ static void _GetProfilingHandle(IntPtr thisHandle, IntPtr* ppException, bool* pb } [UnmanagedCallersOnly] - static void _getCallInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_CALLINFO_FLAGS flags, CORINFO_CALL_INFO* pResult) + private static void _getCallInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_CALLINFO_FLAGS flags, CORINFO_CALL_INFO* pResult) { var _this = GetThis(thisHandle); try @@ -2109,7 +2109,7 @@ static void _getCallInfo(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVE } [UnmanagedCallersOnly] - static byte _canAccessFamily(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* hCaller, CORINFO_CLASS_STRUCT_* hInstanceType) + private static byte _canAccessFamily(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* hCaller, CORINFO_CLASS_STRUCT_* hInstanceType) { var _this = GetThis(thisHandle); try @@ -2124,7 +2124,7 @@ static byte _canAccessFamily(IntPtr thisHandle, IntPtr* ppException, CORINFO_MET } [UnmanagedCallersOnly] - static byte _isRIDClassDomainID(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) + private static byte _isRIDClassDomainID(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls) { var _this = GetThis(thisHandle); try @@ -2139,7 +2139,7 @@ static byte _isRIDClassDomainID(IntPtr thisHandle, IntPtr* ppException, CORINFO_ } [UnmanagedCallersOnly] - static uint _getClassDomainID(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, void** ppIndirection) + private static uint _getClassDomainID(IntPtr thisHandle, IntPtr* ppException, CORINFO_CLASS_STRUCT_* cls, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -2154,7 +2154,7 @@ static uint _getClassDomainID(IntPtr thisHandle, IntPtr* ppException, CORINFO_CL } [UnmanagedCallersOnly] - static void* _getFieldAddress(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, void** ppIndirection) + private static void* _getFieldAddress(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -2169,7 +2169,7 @@ static uint _getClassDomainID(IntPtr thisHandle, IntPtr* ppException, CORINFO_CL } [UnmanagedCallersOnly] - static CORINFO_CLASS_STRUCT_* _getStaticFieldCurrentClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, byte* pIsSpeculative) + private static CORINFO_CLASS_STRUCT_* _getStaticFieldCurrentClass(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, byte* pIsSpeculative) { var _this = GetThis(thisHandle); try @@ -2184,7 +2184,7 @@ static uint _getClassDomainID(IntPtr thisHandle, IntPtr* ppException, CORINFO_CL } [UnmanagedCallersOnly] - static IntPtr _getVarArgsHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* pSig, void** ppIndirection) + private static IntPtr _getVarArgsHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* pSig, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -2199,7 +2199,7 @@ static IntPtr _getVarArgsHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_ } [UnmanagedCallersOnly] - static byte _canGetVarArgsHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* pSig) + private static byte _canGetVarArgsHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO_SIG_INFO* pSig) { var _this = GetThis(thisHandle); try @@ -2214,7 +2214,7 @@ static byte _canGetVarArgsHandle(IntPtr thisHandle, IntPtr* ppException, CORINFO } [UnmanagedCallersOnly] - static InfoAccessType _constructStringLiteral(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, mdToken metaTok, void** ppValue) + private static InfoAccessType _constructStringLiteral(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* module, mdToken metaTok, void** ppValue) { var _this = GetThis(thisHandle); try @@ -2229,7 +2229,7 @@ static InfoAccessType _constructStringLiteral(IntPtr thisHandle, IntPtr* ppExcep } [UnmanagedCallersOnly] - static InfoAccessType _emptyStringLiteral(IntPtr thisHandle, IntPtr* ppException, void** ppValue) + private static InfoAccessType _emptyStringLiteral(IntPtr thisHandle, IntPtr* ppException, void** ppValue) { var _this = GetThis(thisHandle); try @@ -2244,7 +2244,7 @@ static InfoAccessType _emptyStringLiteral(IntPtr thisHandle, IntPtr* ppException } [UnmanagedCallersOnly] - static uint _getFieldThreadLocalStoreID(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, void** ppIndirection) + private static uint _getFieldThreadLocalStoreID(IntPtr thisHandle, IntPtr* ppException, CORINFO_FIELD_STRUCT_* field, void** ppIndirection) { var _this = GetThis(thisHandle); try @@ -2259,7 +2259,7 @@ static uint _getFieldThreadLocalStoreID(IntPtr thisHandle, IntPtr* ppException, } [UnmanagedCallersOnly] - static void _addActiveDependency(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* moduleFrom, CORINFO_MODULE_STRUCT_* moduleTo) + private static void _addActiveDependency(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* moduleFrom, CORINFO_MODULE_STRUCT_* moduleTo) { var _this = GetThis(thisHandle); try @@ -2273,7 +2273,7 @@ static void _addActiveDependency(IntPtr thisHandle, IntPtr* ppException, CORINFO } [UnmanagedCallersOnly] - static CORINFO_METHOD_STRUCT_* _GetDelegateCtor(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* methHnd, CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_METHOD_STRUCT_* targetMethodHnd, DelegateCtorArgs* pCtorData) + private static CORINFO_METHOD_STRUCT_* _GetDelegateCtor(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* methHnd, CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_METHOD_STRUCT_* targetMethodHnd, DelegateCtorArgs* pCtorData) { var _this = GetThis(thisHandle); try @@ -2288,7 +2288,7 @@ static void _addActiveDependency(IntPtr thisHandle, IntPtr* ppException, CORINFO } [UnmanagedCallersOnly] - static void _MethodCompileComplete(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* methHnd) + private static void _MethodCompileComplete(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* methHnd) { var _this = GetThis(thisHandle); try @@ -2302,7 +2302,7 @@ static void _MethodCompileComplete(IntPtr thisHandle, IntPtr* ppException, CORIN } [UnmanagedCallersOnly] - static byte _getTailCallHelpers(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* callToken, CORINFO_SIG_INFO* sig, CORINFO_GET_TAILCALL_HELPERS_FLAGS flags, CORINFO_TAILCALL_HELPERS* pResult) + private static byte _getTailCallHelpers(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* callToken, CORINFO_SIG_INFO* sig, CORINFO_GET_TAILCALL_HELPERS_FLAGS flags, CORINFO_TAILCALL_HELPERS* pResult) { var _this = GetThis(thisHandle); try @@ -2317,7 +2317,7 @@ static byte _getTailCallHelpers(IntPtr thisHandle, IntPtr* ppException, CORINFO_ } [UnmanagedCallersOnly] - static byte _convertPInvokeCalliToCall(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, byte mustConvert) + private static byte _convertPInvokeCalliToCall(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN* pResolvedToken, byte mustConvert) { var _this = GetThis(thisHandle); try @@ -2332,7 +2332,7 @@ static byte _convertPInvokeCalliToCall(IntPtr thisHandle, IntPtr* ppException, C } [UnmanagedCallersOnly] - static byte _notifyInstructionSetUsage(IntPtr thisHandle, IntPtr* ppException, InstructionSet instructionSet, byte supportEnabled) + private static byte _notifyInstructionSetUsage(IntPtr thisHandle, IntPtr* ppException, InstructionSet instructionSet, byte supportEnabled) { var _this = GetThis(thisHandle); try @@ -2347,7 +2347,7 @@ static byte _notifyInstructionSetUsage(IntPtr thisHandle, IntPtr* ppException, I } [UnmanagedCallersOnly] - static void _updateEntryPointForTailCall(IntPtr thisHandle, IntPtr* ppException, CORINFO_CONST_LOOKUP* entryPoint) + private static void _updateEntryPointForTailCall(IntPtr thisHandle, IntPtr* ppException, CORINFO_CONST_LOOKUP* entryPoint) { var _this = GetThis(thisHandle); try @@ -2361,7 +2361,7 @@ static void _updateEntryPointForTailCall(IntPtr thisHandle, IntPtr* ppException, } [UnmanagedCallersOnly] - static void _allocMem(IntPtr thisHandle, IntPtr* ppException, AllocMemArgs* pArgs) + private static void _allocMem(IntPtr thisHandle, IntPtr* ppException, AllocMemArgs* pArgs) { var _this = GetThis(thisHandle); try @@ -2375,7 +2375,7 @@ static void _allocMem(IntPtr thisHandle, IntPtr* ppException, AllocMemArgs* pArg } [UnmanagedCallersOnly] - static void _reserveUnwindInfo(IntPtr thisHandle, IntPtr* ppException, byte isFunclet, byte isColdCode, uint unwindSize) + private static void _reserveUnwindInfo(IntPtr thisHandle, IntPtr* ppException, byte isFunclet, byte isColdCode, uint unwindSize) { var _this = GetThis(thisHandle); try @@ -2389,7 +2389,7 @@ static void _reserveUnwindInfo(IntPtr thisHandle, IntPtr* ppException, byte isFu } [UnmanagedCallersOnly] - static void _allocUnwindInfo(IntPtr thisHandle, IntPtr* ppException, byte* pHotCode, byte* pColdCode, uint startOffset, uint endOffset, uint unwindSize, byte* pUnwindBlock, CorJitFuncKind funcKind) + private static void _allocUnwindInfo(IntPtr thisHandle, IntPtr* ppException, byte* pHotCode, byte* pColdCode, uint startOffset, uint endOffset, uint unwindSize, byte* pUnwindBlock, CorJitFuncKind funcKind) { var _this = GetThis(thisHandle); try @@ -2403,7 +2403,7 @@ static void _allocUnwindInfo(IntPtr thisHandle, IntPtr* ppException, byte* pHotC } [UnmanagedCallersOnly] - static void* _allocGCInfo(IntPtr thisHandle, IntPtr* ppException, UIntPtr size) + private static void* _allocGCInfo(IntPtr thisHandle, IntPtr* ppException, UIntPtr size) { var _this = GetThis(thisHandle); try @@ -2418,7 +2418,7 @@ static void _allocUnwindInfo(IntPtr thisHandle, IntPtr* ppException, byte* pHotC } [UnmanagedCallersOnly] - static void _setEHcount(IntPtr thisHandle, IntPtr* ppException, uint cEH) + private static void _setEHcount(IntPtr thisHandle, IntPtr* ppException, uint cEH) { var _this = GetThis(thisHandle); try @@ -2432,7 +2432,7 @@ static void _setEHcount(IntPtr thisHandle, IntPtr* ppException, uint cEH) } [UnmanagedCallersOnly] - static void _setEHinfo(IntPtr thisHandle, IntPtr* ppException, uint EHnumber, CORINFO_EH_CLAUSE* clause) + private static void _setEHinfo(IntPtr thisHandle, IntPtr* ppException, uint EHnumber, CORINFO_EH_CLAUSE* clause) { var _this = GetThis(thisHandle); try @@ -2446,7 +2446,7 @@ static void _setEHinfo(IntPtr thisHandle, IntPtr* ppException, uint EHnumber, CO } [UnmanagedCallersOnly] - static byte _logMsg(IntPtr thisHandle, IntPtr* ppException, uint level, byte* fmt, IntPtr args) + private static byte _logMsg(IntPtr thisHandle, IntPtr* ppException, uint level, byte* fmt, IntPtr args) { var _this = GetThis(thisHandle); try @@ -2461,7 +2461,7 @@ static byte _logMsg(IntPtr thisHandle, IntPtr* ppException, uint level, byte* fm } [UnmanagedCallersOnly] - static int _doAssert(IntPtr thisHandle, IntPtr* ppException, byte* szFile, int iLine, byte* szExpr) + private static int _doAssert(IntPtr thisHandle, IntPtr* ppException, byte* szFile, int iLine, byte* szExpr) { var _this = GetThis(thisHandle); try @@ -2476,7 +2476,7 @@ static int _doAssert(IntPtr thisHandle, IntPtr* ppException, byte* szFile, int i } [UnmanagedCallersOnly] - static void _reportFatalError(IntPtr thisHandle, IntPtr* ppException, CorJitResult result) + private static void _reportFatalError(IntPtr thisHandle, IntPtr* ppException, CorJitResult result) { var _this = GetThis(thisHandle); try @@ -2490,7 +2490,7 @@ static void _reportFatalError(IntPtr thisHandle, IntPtr* ppException, CorJitResu } [UnmanagedCallersOnly] - static HRESULT _getPgoInstrumentationResults(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftnHnd, PgoInstrumentationSchema** pSchema, uint* pCountSchemaItems, byte** pInstrumentationData, PgoSource* pgoSource) + private static HRESULT _getPgoInstrumentationResults(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftnHnd, PgoInstrumentationSchema** pSchema, uint* pCountSchemaItems, byte** pInstrumentationData, PgoSource* pgoSource) { var _this = GetThis(thisHandle); try @@ -2505,7 +2505,7 @@ static HRESULT _getPgoInstrumentationResults(IntPtr thisHandle, IntPtr* ppExcept } [UnmanagedCallersOnly] - static HRESULT _allocPgoInstrumentationBySchema(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftnHnd, PgoInstrumentationSchema* pSchema, uint countSchemaItems, byte** pInstrumentationData) + private static HRESULT _allocPgoInstrumentationBySchema(IntPtr thisHandle, IntPtr* ppException, CORINFO_METHOD_STRUCT_* ftnHnd, PgoInstrumentationSchema* pSchema, uint countSchemaItems, byte** pInstrumentationData) { var _this = GetThis(thisHandle); try @@ -2520,7 +2520,7 @@ static HRESULT _allocPgoInstrumentationBySchema(IntPtr thisHandle, IntPtr* ppExc } [UnmanagedCallersOnly] - static void _recordCallSite(IntPtr thisHandle, IntPtr* ppException, uint instrOffset, CORINFO_SIG_INFO* callSig, CORINFO_METHOD_STRUCT_* methodHandle) + private static void _recordCallSite(IntPtr thisHandle, IntPtr* ppException, uint instrOffset, CORINFO_SIG_INFO* callSig, CORINFO_METHOD_STRUCT_* methodHandle) { var _this = GetThis(thisHandle); try @@ -2534,7 +2534,7 @@ static void _recordCallSite(IntPtr thisHandle, IntPtr* ppException, uint instrOf } [UnmanagedCallersOnly] - static void _recordRelocation(IntPtr thisHandle, IntPtr* ppException, void* location, void* locationRW, void* target, ushort fRelocType, ushort slotNum, int addlDelta) + private static void _recordRelocation(IntPtr thisHandle, IntPtr* ppException, void* location, void* locationRW, void* target, ushort fRelocType, ushort slotNum, int addlDelta) { var _this = GetThis(thisHandle); try @@ -2548,7 +2548,7 @@ static void _recordRelocation(IntPtr thisHandle, IntPtr* ppException, void* loca } [UnmanagedCallersOnly] - static ushort _getRelocTypeHint(IntPtr thisHandle, IntPtr* ppException, void* target) + private static ushort _getRelocTypeHint(IntPtr thisHandle, IntPtr* ppException, void* target) { var _this = GetThis(thisHandle); try @@ -2563,7 +2563,7 @@ static ushort _getRelocTypeHint(IntPtr thisHandle, IntPtr* ppException, void* ta } [UnmanagedCallersOnly] - static uint _getExpectedTargetArchitecture(IntPtr thisHandle, IntPtr* ppException) + private static uint _getExpectedTargetArchitecture(IntPtr thisHandle, IntPtr* ppException) { var _this = GetThis(thisHandle); try @@ -2578,7 +2578,7 @@ static uint _getExpectedTargetArchitecture(IntPtr thisHandle, IntPtr* ppExceptio } [UnmanagedCallersOnly] - static uint _getJitFlags(IntPtr thisHandle, IntPtr* ppException, CORJIT_FLAGS* flags, uint sizeInBytes) + private static uint _getJitFlags(IntPtr thisHandle, IntPtr* ppException, CORJIT_FLAGS* flags, uint sizeInBytes) { var _this = GetThis(thisHandle); try @@ -2592,8 +2592,7 @@ static uint _getJitFlags(IntPtr thisHandle, IntPtr* ppException, CORJIT_FLAGS* f } } - - static IntPtr GetUnmanagedCallbacks() + private static IntPtr GetUnmanagedCallbacks() { void** callbacks = (void**)Marshal.AllocCoTaskMem(sizeof(IntPtr) * 175); @@ -2777,4 +2776,3 @@ static IntPtr GetUnmanagedCallbacks() } } } - diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoHelpFunc.cs b/src/coreclr/tools/Common/JitInterface/CorInfoHelpFunc.cs index b0a53c8232e566..c6774127307e09 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoHelpFunc.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoHelpFunc.cs @@ -1,10 +1,6 @@ // 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.Text; - namespace Internal.JitInterface { // CorInfoHelpFunc defines the set of helpers (accessed via the ICorDynamicInfo::getHelperFtn()) @@ -54,9 +50,9 @@ which is the right helper to use to allocate an object of a given type. */ CORINFO_HELP_NEWSFAST, // allocator for small, non-finalizer, non-array object CORINFO_HELP_NEWSFAST_FINALIZE, // allocator for small, finalizable, non-array object CORINFO_HELP_NEWSFAST_ALIGN8, // allocator for small, non-finalizer, non-array object, 8 byte aligned - CORINFO_HELP_NEWSFAST_ALIGN8_VC,// allocator for small, value class, 8 byte aligned + CORINFO_HELP_NEWSFAST_ALIGN8_VC, // allocator for small, value class, 8 byte aligned CORINFO_HELP_NEWSFAST_ALIGN8_FINALIZE, // allocator for small, finalizable, non-array object, 8 byte aligned - CORINFO_HELP_NEW_MDARR,// multi-dim array helper (with or without lower bounds - dimensions passed in as unmanaged array) + CORINFO_HELP_NEW_MDARR, // multi-dim array helper (with or without lower bounds - dimensions passed in as unmanaged array) CORINFO_HELP_NEWARR_1_DIRECT, // helper for any one dimensional array creation CORINFO_HELP_NEWARR_1_OBJ, // optimized 1-D object arrays CORINFO_HELP_NEWARR_1_VC, // optimized 1-D value class arrays @@ -108,7 +104,7 @@ which is the right helper to use to allocate an object of a given type. */ CORINFO_HELP_VERIFICATION, // Throw a VerificationException CORINFO_HELP_FAIL_FAST, // Kill the process avoiding any exceptions or stack and data dependencies (use for GuardStack unsafe buffer checks) - CORINFO_HELP_METHOD_ACCESS_EXCEPTION,//Throw an access exception due to a failed member/class access check. + CORINFO_HELP_METHOD_ACCESS_EXCEPTION, //Throw an access exception due to a failed member/class access check. CORINFO_HELP_FIELD_ACCESS_EXCEPTION, CORINFO_HELP_CLASS_ACCESS_EXCEPTION, @@ -217,9 +213,9 @@ which is the right helper to use to allocate an object of a given type. */ CORINFO_HELP_MEMCPY, // Copy block of memory CORINFO_HELP_RUNTIMEHANDLE_METHOD, // determine a type/field/method handle at run-time - CORINFO_HELP_RUNTIMEHANDLE_METHOD_LOG,// determine a type/field/method handle at run-time, with IBC logging + CORINFO_HELP_RUNTIMEHANDLE_METHOD_LOG, // determine a type/field/method handle at run-time, with IBC logging CORINFO_HELP_RUNTIMEHANDLE_CLASS, // determine a type/field/method handle at run-time - CORINFO_HELP_RUNTIMEHANDLE_CLASS_LOG,// determine a type/field/method handle at run-time, with IBC logging + CORINFO_HELP_RUNTIMEHANDLE_CLASS_LOG, // determine a type/field/method handle at run-time, with IBC logging CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE, // Convert from a TypeHandle (native structure pointer) to RuntimeType at run-time CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE_MAYBENULL, // Convert from a TypeHandle (native structure pointer) to RuntimeType at run-time, the type may be null @@ -243,8 +239,8 @@ which is the right helper to use to allocate an object of a given type. */ CORINFO_HELP_READYTORUN_DELEGATE_CTOR, CORINFO_HELP_READYTORUN_GENERIC_STATIC_BASE, - CORINFO_HELP_EE_PERSONALITY_ROUTINE,// Not real JIT helper. Used in native images. - CORINFO_HELP_EE_PERSONALITY_ROUTINE_FILTER_FUNCLET,// Not real JIT helper. Used in native images to detect filter funclets. + CORINFO_HELP_EE_PERSONALITY_ROUTINE, // Not real JIT helper. Used in native images. + CORINFO_HELP_EE_PERSONALITY_ROUTINE_FILTER_FUNCLET, // Not real JIT helper. Used in native images to detect filter funclets. // ASSIGN_REF_EAX - CHECKED_ASSIGN_REF_EBP: NOGC_WRITE_BARRIERS JIT helper calls // diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs index c1f59c124b6769..c5f6ba41139354 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs @@ -3,11 +3,9 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Text; -using System.Reflection.Metadata; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; @@ -25,7 +23,6 @@ using ILCompiler; using ILCompiler.DependencyAnalysis; -using Internal.IL.Stubs; #if READYTORUN using System.Reflection.Metadata.Ecma335; @@ -34,7 +31,7 @@ namespace Internal.JitInterface { - enum CompilationResult + internal enum CompilationResult { CompilationComplete, CompilationRetryRequested @@ -76,18 +73,19 @@ private struct PgoInstrumentationResults public byte* pInstrumentationData; public HRESULT hr; } - Dictionary _pgoResults = new Dictionary(); + + private Dictionary _pgoResults = new Dictionary(); [DllImport(JitLibrary)] - private extern static IntPtr jitStartup(IntPtr host); + private static extern IntPtr jitStartup(IntPtr host); private static class JitPointerAccessor { [DllImport(JitLibrary)] - private extern static IntPtr getJit(); + private static extern IntPtr getJit(); [DllImport(JitSupportLibrary)] - private extern static CorJitResult JitProcessShutdownWork(IntPtr jit); + private static extern CorJitResult JitProcessShutdownWork(IntPtr jit); static JitPointerAccessor() { @@ -121,13 +119,13 @@ public LikelyClassMethodRecord(IntPtr handle, uint likelihood) } [DllImport(JitLibrary)] - private extern static uint getLikelyClasses(LikelyClassMethodRecord* pLikelyClasses, uint maxLikelyClasses, PgoInstrumentationSchema* schema, uint countSchemaItems, byte*pInstrumentationData, int ilOffset); + private static extern uint getLikelyClasses(LikelyClassMethodRecord* pLikelyClasses, uint maxLikelyClasses, PgoInstrumentationSchema* schema, uint countSchemaItems, byte*pInstrumentationData, int ilOffset); [DllImport(JitLibrary)] - private extern static uint getLikelyMethods(LikelyClassMethodRecord* pLikelyMethods, uint maxLikelyMethods, PgoInstrumentationSchema* schema, uint countSchemaItems, byte*pInstrumentationData, int ilOffset); + private static extern uint getLikelyMethods(LikelyClassMethodRecord* pLikelyMethods, uint maxLikelyMethods, PgoInstrumentationSchema* schema, uint countSchemaItems, byte*pInstrumentationData, int ilOffset); [DllImport(JitSupportLibrary)] - private extern static IntPtr GetJitHost(IntPtr configProvider); + private static extern IntPtr GetJitHost(IntPtr configProvider); // // Per-method initialization and state @@ -140,18 +138,18 @@ private static CorInfoImpl GetThis(IntPtr thisHandle) } [DllImport(JitSupportLibrary)] - private extern static CorJitResult JitCompileMethod(out IntPtr exception, + private static extern CorJitResult JitCompileMethod(out IntPtr exception, IntPtr jit, IntPtr thisHandle, IntPtr callbacks, ref CORINFO_METHOD_INFO info, uint flags, out IntPtr nativeEntry, out uint codeSize); [DllImport(JitSupportLibrary)] - private extern static uint GetMaxIntrinsicSIMDVectorLength(IntPtr jit, CORJIT_FLAGS* flags); + private static extern uint GetMaxIntrinsicSIMDVectorLength(IntPtr jit, CORJIT_FLAGS* flags); [DllImport(JitSupportLibrary)] - private extern static IntPtr AllocException([MarshalAs(UnmanagedType.LPWStr)]string message, int messageLength); + private static extern IntPtr AllocException([MarshalAs(UnmanagedType.LPWStr)]string message, int messageLength); [DllImport(JitSupportLibrary)] - private extern static void JitSetOs(IntPtr jit, CORINFO_OS os); + private static extern void JitSetOs(IntPtr jit, CORINFO_OS os); private IntPtr AllocException(Exception ex) { @@ -159,19 +157,16 @@ private IntPtr AllocException(Exception ex) string exString = ex.ToString(); IntPtr nativeException = AllocException(exString, exString.Length); - if (_nativeExceptions == null) - { - _nativeExceptions = new List(); - } + _nativeExceptions ??= new List(); _nativeExceptions.Add(nativeException); return nativeException; } [DllImport(JitSupportLibrary)] - private extern static void FreeException(IntPtr obj); + private static extern void FreeException(IntPtr obj); [DllImport(JitSupportLibrary)] - private extern static char* GetExceptionMessage(IntPtr obj); + private static extern char* GetExceptionMessage(IntPtr obj); public static void Startup(CORINFO_OS os) { @@ -312,7 +307,7 @@ IntPtr LocalObjectToHandle(object input) if (newData != null) { - PgoSchemaElem likelyClassElem = new PgoSchemaElem(); + PgoSchemaElem likelyClassElem = default(PgoSchemaElem); likelyClassElem.InstrumentationKind = isType ? PgoInstrumentationKind.GetLikelyClass : PgoInstrumentationKind.GetLikelyMethod; likelyClassElem.ILOffset = nativeSchema[index].ILOffset; likelyClassElem.Count = 1; @@ -469,11 +464,13 @@ private void PublishCode() } } +#pragma warning disable SA1001, SA1113, SA1115 // Comma should be on the same line as previous parameter _methodCodeNode.SetCode(objectData #if !SUPPORT_JIT && !READYTORUN , isFoldable: (_compilation._compilationOptions & RyuJitCompilationOptions.MethodBodyFolding) != 0 #endif ); +#pragma warning restore SA1001, SA1113, SA1115 // Comma should be on the same line as previous parameter _methodCodeNode.InitializeFrameInfos(_frameInfos); _methodCodeNode.InitializeDebugEHClauseInfos(debugEHClauseInfos); @@ -586,9 +583,9 @@ private int PointerSize } } - private Dictionary _pins = new Dictionary(); + private Dictionary _pins = new Dictionary(); - private IntPtr GetPin(Object obj) + private IntPtr GetPin(object obj) { GCHandle handle; if (!_pins.TryGetValue(obj, out handle)) @@ -622,8 +619,8 @@ private void CompileMethodCleanup() _roData = null; _roDataBlob = null; - _codeRelocs = new ArrayBuilder(); - _roDataRelocs = new ArrayBuilder(); + _codeRelocs = default(ArrayBuilder); + _roDataRelocs = default(ArrayBuilder); _numFrameInfos = 0; _usedFrameInfos = 0; @@ -656,8 +653,8 @@ private void CompileMethodCleanup() _pgoResults.Clear(); } - private Dictionary _objectToHandle = new Dictionary(); - private List _handleToObject = new List(); + private Dictionary _objectToHandle = new Dictionary(); + private List _handleToObject = new List(); private const int handleMultiplier = 8; private const int handleBase = 0x420000; @@ -666,7 +663,7 @@ private void CompileMethodCleanup() private static readonly IntPtr s_handleHighBitSet = (sizeof(IntPtr) == 4) ? new IntPtr(0x40000000) : new IntPtr(0x4000000000000000); #endif - private IntPtr ObjectToHandle(Object obj) + private IntPtr ObjectToHandle(object obj) { // SuperPMI relies on the handle returned from this function being stable for the lifetime of the crossgen2 process // If handle deletion is implemented, please update SuperPMI @@ -683,7 +680,7 @@ private IntPtr ObjectToHandle(Object obj) return handle; } - private Object HandleToObject(IntPtr handle) + private object HandleToObject(IntPtr handle) { #if DEBUG handle = new IntPtr(~(long)s_handleHighBitSet & (long) handle); @@ -693,9 +690,9 @@ private Object HandleToObject(IntPtr handle) } private MethodDesc HandleToObject(CORINFO_METHOD_STRUCT_* method) => (MethodDesc)HandleToObject((IntPtr)method); - private CORINFO_METHOD_STRUCT_* ObjectToHandle(MethodDesc method) => (CORINFO_METHOD_STRUCT_*)ObjectToHandle((Object)method); + private CORINFO_METHOD_STRUCT_* ObjectToHandle(MethodDesc method) => (CORINFO_METHOD_STRUCT_*)ObjectToHandle((object)method); private TypeDesc HandleToObject(CORINFO_CLASS_STRUCT_* type) => (TypeDesc)HandleToObject((IntPtr)type); - private CORINFO_CLASS_STRUCT_* ObjectToHandle(TypeDesc type) => (CORINFO_CLASS_STRUCT_*)ObjectToHandle((Object)type); + private CORINFO_CLASS_STRUCT_* ObjectToHandle(TypeDesc type) => (CORINFO_CLASS_STRUCT_*)ObjectToHandle((object)type); private FieldDesc HandleToObject(CORINFO_FIELD_STRUCT_* field) => (FieldDesc)HandleToObject((IntPtr)field); private CORINFO_FIELD_STRUCT_* ObjectToHandle(FieldDesc field) => (CORINFO_FIELD_STRUCT_*)ObjectToHandle((object)field); private MethodILScope HandleToObject(CORINFO_MODULE_STRUCT_* module) => (MethodIL)HandleToObject((IntPtr)module); @@ -740,14 +737,11 @@ private bool Get_CORINFO_METHOD_INFO(MethodDesc method, MethodIL methodIL, CORIN return true; } - private Dictionary _instantiationToJitVisibleInstantiation = null; + private Dictionary _instantiationToJitVisibleInstantiation; private CORINFO_CLASS_STRUCT_** GetJitInstantiation(Instantiation inst) { IntPtr [] jitVisibleInstantiation; - if (_instantiationToJitVisibleInstantiation == null) - { - _instantiationToJitVisibleInstantiation = new Dictionary(); - } + _instantiationToJitVisibleInstantiation ??= new Dictionary(); if (!_instantiationToJitVisibleInstantiation.TryGetValue(inst, out jitVisibleInstantiation)) { @@ -1084,7 +1078,9 @@ private uint getMethodAttribsInternal(MethodDesc method) return (uint)result; } +#pragma warning disable CA1822 // Mark members as static private void setMethodAttribs(CORINFO_METHOD_STRUCT_* ftn, CorInfoMethodRuntimeFlags attribs) +#pragma warning restore CA1822 // Mark members as static { // TODO: Inlining } @@ -1146,7 +1142,9 @@ private CorInfoInline canInline(CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHO } } +#pragma warning disable CA1822 // Mark members as static private void reportTailCallDecision(CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd, bool fIsTailPrefix, CorInfoTailCall tailCallResult, byte* reason) +#pragma warning restore CA1822 // Mark members as static { } @@ -1355,10 +1353,7 @@ static CORINFO_RESOLVED_TOKEN CreateResolvedTokenFromMethod(CorInfoImpl jitInter CORINFO_RESOLVED_TOKEN result = default(CORINFO_RESOLVED_TOKEN); MethodILScope scope = jitInterface._compilation.GetMethodIL(methodWithToken.Method); - if (scope == null) - { - scope = Internal.IL.EcmaMethodILScope.Create((EcmaMethod)methodWithToken.Method.GetTypicalMethodDefinition()); - } + scope ??= EcmaMethodILScope.Create((EcmaMethod)methodWithToken.Method.GetTypicalMethodDefinition()); result.tokenScope = jitInterface.ObjectToHandle(scope); result.tokenContext = jitInterface.contextFromMethod(method); #if READYTORUN @@ -1432,7 +1427,7 @@ private CorInfoCallConvExtension getUnmanagedCallConv(CORINFO_METHOD_STRUCT_* me return callConv; } } - private CorInfoCallConvExtension GetUnmanagedCallConv(MethodDesc methodDesc, out bool suppressGCTransition) + private static CorInfoCallConvExtension GetUnmanagedCallConv(MethodDesc methodDesc, out bool suppressGCTransition) { UnmanagedCallingConventions callingConventions; @@ -1456,12 +1451,12 @@ private CorInfoCallConvExtension GetUnmanagedCallConv(MethodDesc methodDesc, out return ToCorInfoCallConvExtension(callingConventions, out suppressGCTransition); } - private CorInfoCallConvExtension GetUnmanagedCallConv(MethodSignature signature, out bool suppressGCTransition) + private static CorInfoCallConvExtension GetUnmanagedCallConv(MethodSignature signature, out bool suppressGCTransition) { return ToCorInfoCallConvExtension(signature.GetStandaloneMethodSignatureCallingConventions(), out suppressGCTransition); } - private CorInfoCallConvExtension ToCorInfoCallConvExtension(UnmanagedCallingConventions callConvs, out bool suppressGCTransition) + private static CorInfoCallConvExtension ToCorInfoCallConvExtension(UnmanagedCallingConventions callConvs, out bool suppressGCTransition) { CorInfoCallConvExtension result; switch (callConvs & UnmanagedCallingConventions.CallingConventionMask) @@ -1509,7 +1504,9 @@ private void setPatchpointInfo(PatchpointInfo* patchpointInfo) private PatchpointInfo* getOSRInfo(ref uint ilOffset) { throw new NotImplementedException("getOSRInfo"); } +#pragma warning disable CA1822 // Mark members as static private void methodMustBeLoadedBeforeCodeIsRun(CORINFO_METHOD_STRUCT_* method) +#pragma warning restore CA1822 // Mark members as static { } @@ -1551,9 +1548,9 @@ private static object ResolveTokenInScope(MethodILScope methodIL, object typeOrM if (owningMethod != typeOrMethodContext && owningMethod.IsCanonicalMethod(CanonicalFormKind.Any)) { - Instantiation typeInst = default; Instantiation methodInst = default; + Instantiation typeInst; if (typeOrMethodContext is TypeDesc typeContext) { Debug.Assert(typeContext.HasSameTypeDefinition(owningMethod.OwningType) || typeContext.IsArray); @@ -1606,7 +1603,7 @@ private object GetRuntimeDeterminedObjectForToken(ref CORINFO_RESOLVED_TOKEN pRe return result; } - private object GetRuntimeDeterminedObjectForToken(MethodILScope methodIL, object typeOrMethodContext, mdToken token) + private static object GetRuntimeDeterminedObjectForToken(MethodILScope methodIL, object typeOrMethodContext, mdToken token) { object result = ResolveTokenInScope(methodIL, typeOrMethodContext, token); @@ -1795,7 +1792,7 @@ private void findCallSiteSig(CORINFO_MODULE_STRUCT_* module, uint methTOK, CORIN return ObjectToHandle(_compilation.TypeSystemContext.GetWellKnownType(result)); } - private CorInfoCanSkipVerificationResult canSkipVerification(CORINFO_MODULE_STRUCT_* module) + private static CorInfoCanSkipVerificationResult canSkipVerification(CORINFO_MODULE_STRUCT_* module) { return CorInfoCanSkipVerificationResult.CORINFO_VERIFICATION_CAN_SKIP; } @@ -1896,7 +1893,9 @@ private bool isValueClass(CORINFO_CLASS_STRUCT_* cls) return HandleToObject(cls).IsValueType; } +#pragma warning disable CA1822 // Mark members as static private CorInfoInlineTypeCheck canInlineTypeCheck(CORINFO_CLASS_STRUCT_* cls, CorInfoInlineTypeCheckSource source) +#pragma warning restore CA1822 // Mark members as static { // TODO: when we support multiple modules at runtime, this will need to do more work // NOTE: cls can be null @@ -1993,12 +1992,16 @@ private uint getClassAttribsInternal(TypeDesc type) private byte* getAssemblyName(CORINFO_ASSEMBLY_STRUCT_* assem) { throw new NotImplementedException("getAssemblyName"); } +#pragma warning disable CA1822 // Mark members as static private void* LongLifetimeMalloc(UIntPtr sz) +#pragma warning restore CA1822 // Mark members as static { return (void*)Marshal.AllocCoTaskMem((int)sz); } +#pragma warning disable CA1822 // Mark members as static private void LongLifetimeFree(void* obj) +#pragma warning restore CA1822 // Mark members as static { Marshal.FreeCoTaskMem((IntPtr)obj); } @@ -2093,12 +2096,12 @@ public static int GetClassAlignmentRequirementStatic(DefType type) // // Heuristic to determine if we should have instances of this class 8 byte aligned // - static bool ShouldAlign8(int dwR8Fields, int dwTotalFields) + private static bool ShouldAlign8(int dwR8Fields, int dwTotalFields) { return dwR8Fields*2>dwTotalFields && dwR8Fields>=2; } - static bool ShouldAlign8(DefType type) + private static bool ShouldAlign8(DefType type) { int instanceFields = 0; int doubleFields = 0; @@ -2691,7 +2694,9 @@ private CorInfoType getChildType(CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_CLASS_ST result = asCorInfoType(returnType, clsRet); } else +#pragma warning disable IDE0059 // Unnecessary assignment of a value clsRet = null; +#pragma warning restore IDE0059 // Unnecessary assignment of a value return result; } @@ -2746,7 +2751,9 @@ private CorInfoArrayIntrinsic getArrayIntrinsicID(CORINFO_METHOD_STRUCT_* ftn) return (void*)ObjectToHandle(_compilation.GetFieldRvaData(fd)); } +#pragma warning disable CA1822 // Mark members as static private CorInfoIsAccessAllowedResult canAccessClass(ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, ref CORINFO_HELPER_DESC pAccessHelper) +#pragma warning restore CA1822 // Mark members as static { // TODO: Access check return CorInfoIsAccessAllowedResult.CORINFO_ACCESS_ALLOWED; @@ -2800,7 +2807,7 @@ private uint getFieldOffset(CORINFO_FIELD_STRUCT_* field) return (uint)fieldDesc.Offset.AsInt; } - private CORINFO_FIELD_ACCESSOR getFieldIntrinsic(FieldDesc field) + private static CORINFO_FIELD_ACCESSOR getFieldIntrinsic(FieldDesc field) { Debug.Assert(field.IsIntrinsic); @@ -2848,23 +2855,31 @@ private void getVars(CORINFO_METHOD_STRUCT_* ftn, ref uint cVars, ILVarInfo** va extendOthers = true; } +#pragma warning disable CA1822 // Mark members as static private void reportRichMappings(InlineTreeNode* inlineTree, uint numInlineTree, RichOffsetMapping* mappings, uint numMappings) +#pragma warning restore CA1822 // Mark members as static { Marshal.FreeHGlobal((IntPtr)inlineTree); Marshal.FreeHGlobal((IntPtr)mappings); } +#pragma warning disable CA1822 // Mark members as static private void* allocateArray(UIntPtr cBytes) +#pragma warning restore CA1822 // Mark members as static { return (void*)Marshal.AllocHGlobal((IntPtr)(void*)cBytes); } +#pragma warning disable CA1822 // Mark members as static private void freeArray(void* array) +#pragma warning restore CA1822 // Mark members as static { Marshal.FreeHGlobal((IntPtr)array); } +#pragma warning disable CA1822 // Mark members as static private CORINFO_ARG_LIST_STRUCT_* getArgNext(CORINFO_ARG_LIST_STRUCT_* args) +#pragma warning restore CA1822 // Mark members as static { return (CORINFO_ARG_LIST_STRUCT_*)((int)args + 1); } @@ -2872,7 +2887,7 @@ private void freeArray(void* array) private CorInfoTypeWithMod getArgType(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args, CORINFO_CLASS_STRUCT_** vcTypeRet) { int index = (int)args; - Object sigObj = HandleToObject((IntPtr)sig->methodSignature); + object sigObj = HandleToObject((IntPtr)sig->methodSignature); MethodSignature methodSig = sigObj as MethodSignature; @@ -2897,7 +2912,7 @@ private CorInfoTypeWithMod getArgType(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_ST private CORINFO_CLASS_STRUCT_* getArgClass(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_STRUCT_* args) { int index = (int)args; - Object sigObj = HandleToObject((IntPtr)sig->methodSignature); + object sigObj = HandleToObject((IntPtr)sig->methodSignature); MethodSignature methodSig = sigObj as MethodSignature; if (methodSig != null) @@ -2933,7 +2948,9 @@ private HRESULT GetErrorHRESULT(_EXCEPTION_POINTERS* pExceptionPointers) private uint GetErrorMessage(char* buffer, uint bufferLength) { throw new NotImplementedException("GetErrorMessage"); } +#pragma warning disable CA1822 // Mark members as static private int FilterException(_EXCEPTION_POINTERS* pExceptionPointers) +#pragma warning restore CA1822 // Mark members as static { // This method is completely handled by the C++ wrapper to the JIT-EE interface, // and should never reach the managed implementation. @@ -2941,7 +2958,9 @@ private int FilterException(_EXCEPTION_POINTERS* pExceptionPointers) throw new NotSupportedException("FilterException"); } +#pragma warning disable CA1822 // Mark members as static private bool runWithErrorTrap(void* function, void* parameter) +#pragma warning restore CA1822 // Mark members as static { // This method is completely handled by the C++ wrapper to the JIT-EE interface, // and should never reach the managed implementation. @@ -2949,7 +2968,9 @@ private bool runWithErrorTrap(void* function, void* parameter) throw new NotSupportedException("runWithErrorTrap"); } +#pragma warning disable CA1822 // Mark members as static private bool runWithSPMIErrorTrap(void* function, void* parameter) +#pragma warning restore CA1822 // Mark members as static { // This method is completely handled by the C++ wrapper to the JIT-EE interface, // and should never reach the managed implementation. @@ -2970,7 +2991,7 @@ public static CORINFO_OS TargetToOs(TargetDetails target) private void getEEInfo(ref CORINFO_EE_INFO pEEInfoOut) { - pEEInfoOut = new CORINFO_EE_INFO(); + pEEInfoOut = default(CORINFO_EE_INFO); #if DEBUG // In debug, write some bogus data to the struct to ensure we have filled everything @@ -2997,7 +3018,9 @@ private void getEEInfo(ref CORINFO_EE_INFO pEEInfoOut) pEEInfoOut.osType = TargetToOs(_compilation.NodeFactory.Target); } +#pragma warning disable CA1822 // Mark members as static private char* getJitTimeLogFilename() +#pragma warning restore CA1822 // Mark members as static { return null; } @@ -3048,14 +3071,13 @@ private static byte[] StringToUTF8(string s) return (byte*)GetPin(StringToUTF8(method.Name)); } - private String getMethodNameFromMetadataImpl(MethodDesc method, out string className, out string namespaceName, out string enclosingClassName) + private static string getMethodNameFromMetadataImpl(MethodDesc method, out string className, out string namespaceName, out string enclosingClassName) { - string result = null; className = null; namespaceName = null; enclosingClassName = null; - result = method.Name; + string result = method.Name; MetadataType owningType = method.OwningType as MetadataType; if (owningType != null) @@ -3148,7 +3170,9 @@ private uint getThreadTLSIndex(ref void* ppIndirection) private void getFunctionFixedEntryPoint(CORINFO_METHOD_STRUCT_* ftn, bool isUnsafeFunctionPointer, ref CORINFO_CONST_LOOKUP pResult) { throw new NotImplementedException("getFunctionFixedEntryPoint"); } +#pragma warning disable CA1822 // Mark members as static private CorInfoHelpFunc getLazyStringLiteralHelper(CORINFO_MODULE_STRUCT_* handle) +#pragma warning restore CA1822 // Mark members as static { // TODO: Lazy string literal helper return CorInfoHelpFunc.CORINFO_HELP_UNDEF; @@ -3160,7 +3184,7 @@ private CorInfoHelpFunc getLazyStringLiteralHelper(CORINFO_MODULE_STRUCT_* handl private CORINFO_FIELD_STRUCT_* embedFieldHandle(CORINFO_FIELD_STRUCT_* handle, ref void* ppIndirection) { throw new NotImplementedException("embedFieldHandle"); } - private CORINFO_RUNTIME_LOOKUP_KIND GetGenericRuntimeLookupKind(MethodDesc method) + private static CORINFO_RUNTIME_LOOKUP_KIND GetGenericRuntimeLookupKind(MethodDesc method) { if (method.RequiresInstMethodDescArg()) return CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_METHODPARAM; @@ -3191,7 +3215,9 @@ private void getLocationOfThisType(CORINFO_METHOD_STRUCT_* context, ref CORINFO_ private void* GetCookieForPInvokeCalliSig(CORINFO_SIG_INFO* szMetaSig, ref void* ppIndirection) { throw new NotImplementedException("GetCookieForPInvokeCalliSig"); } +#pragma warning disable CA1822 // Mark members as static private CORINFO_JUST_MY_CODE_HANDLE_* getJustMyCodeHandle(CORINFO_METHOD_STRUCT_* method, ref CORINFO_JUST_MY_CODE_HANDLE_* ppIndirection) +#pragma warning restore CA1822 // Mark members as static { ppIndirection = null; return null; @@ -3204,7 +3230,7 @@ private void GetProfilingHandle(ref bool pbHookFunction, ref void* pProfilerHand /// private CORINFO_CONST_LOOKUP CreateConstLookupToSymbol(ISymbolNode symbol) { - CORINFO_CONST_LOOKUP constLookup = new CORINFO_CONST_LOOKUP(); + CORINFO_CONST_LOOKUP constLookup = default(CORINFO_CONST_LOOKUP); constLookup.addr = (void*)ObjectToHandle(symbol); constLookup.accessType = symbol.RepresentsIndirectionCell ? InfoAccessType.IAT_PVALUE : InfoAccessType.IAT_VALUE; return constLookup; @@ -3263,7 +3289,9 @@ private void addActiveDependency(CORINFO_MODULE_STRUCT_* moduleFrom, CORINFO_MOD private void MethodCompileComplete(CORINFO_METHOD_STRUCT_* methHnd) { throw new NotImplementedException("MethodCompileComplete"); } +#pragma warning disable CA1822 // Mark members as static private bool getTailCallHelpers(ref CORINFO_RESOLVED_TOKEN callToken, CORINFO_SIG_INFO* sig, CORINFO_GET_TAILCALL_HELPERS_FLAGS flags, ref CORINFO_TAILCALL_HELPERS pResult) +#pragma warning restore CA1822 // Mark members as static { // Slow tailcalls are not supported yet // https://github.com/dotnet/runtime/issues/35423 @@ -3385,7 +3413,9 @@ private void allocUnwindInfo(byte* pHotCode, byte* pColdCode, uint startOffset, return (void*)GetPin(_gcInfo); } +#pragma warning disable CA1822 // Mark members as static private bool logMsg(uint level, byte* fmt, IntPtr args) +#pragma warning restore CA1822 // Mark members as static { // Console.WriteLine(Marshal.PtrToStringUTF8((IntPtr)fmt)); return false; @@ -3399,13 +3429,17 @@ private int doAssert(byte* szFile, int iLine, byte* szExpr) return 1; } +#pragma warning disable CA1822 // Mark members as static private void reportFatalError(CorJitResult result) +#pragma warning restore CA1822 // Mark members as static { // We could add some logging here, but for now it's unnecessary. // CompileMethod is going to fail with this CorJitResult anyway. } +#pragma warning disable CA1822 // Mark members as static private void recordCallSite(uint instrOffset, CORINFO_SIG_INFO* callSig, CORINFO_METHOD_STRUCT_* methodHandle) +#pragma warning restore CA1822 // Mark members as static { } @@ -3607,13 +3641,13 @@ private ushort getRelocTypeHint(void* target) switch (_compilation.TypeSystemContext.Target.Architecture) { case TargetArchitecture.X64: - return (ushort)ILCompiler.DependencyAnalysis.RelocType.IMAGE_REL_BASED_REL32; + return (ushort)RelocType.IMAGE_REL_BASED_REL32; case TargetArchitecture.ARM: - return (ushort)ILCompiler.DependencyAnalysis.RelocType.IMAGE_REL_BASED_THUMB_BRANCH24; + return (ushort)RelocType.IMAGE_REL_BASED_THUMB_BRANCH24; default: - return UInt16.MaxValue; + return ushort.MaxValue; } } @@ -3851,11 +3885,13 @@ private HRESULT getPgoInstrumentationResults(CORINFO_METHOD_STRUCT_* ftnHnd, ref } else { +#pragma warning disable SA1001, SA1113, SA1115 // Commas should be spaced correctly ComputeJitPgoInstrumentationSchema(ObjectToHandle, pgoResultsSchemas, out var nativeSchemas, out var instrumentationData #if !READYTORUN , _compilation.CanConstructType #endif ); +#pragma warning restore SA1001, SA1113, SA1115 // Commas should be spaced correctly pgoResults.pInstrumentationData = (byte*)GetPin(instrumentationData); pgoResults.countSchemaItems = (uint)nativeSchemas.Length; diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoInstructionSet.cs b/src/coreclr/tools/Common/JitInterface/CorInfoInstructionSet.cs index d903e7d6faf060..78eec3e1297590 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoInstructionSet.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoInstructionSet.cs @@ -5,11 +5,9 @@ // FROM /src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetDesc.txt // using /src/coreclr/tools/Common/JitInterface/ThunkGenerator/gen.bat -using System; using System.Collections; using System.Collections.Generic; using System.Linq; -using System.Runtime.InteropServices; using Internal.TypeSystem; namespace Internal.JitInterface @@ -338,7 +336,7 @@ IEnumerator IEnumerable.GetEnumerator() public IEnumerator GetEnumerator() { - for (int i = 1; i < (int)InstructionSet.NONE; i ++) + for (int i = 1; i < (int)InstructionSet.NONE; i++) { InstructionSet instructionSet = (InstructionSet)i; if (HasInstructionSet(instructionSet)) @@ -384,12 +382,12 @@ public static InstructionSet ConvertToImpliedInstructionSetForVectorInstructionS public static InstructionSetFlags ExpandInstructionSetByImplicationHelper(TargetArchitecture architecture, InstructionSetFlags input) { - InstructionSetFlags oldflags = input; + InstructionSetFlags oldflags; InstructionSetFlags resultflags = input; do { oldflags = resultflags; - switch(architecture) + switch (architecture) { case TargetArchitecture.ARM64: @@ -619,7 +617,7 @@ public void ExpandInstructionSetByReverseImplication(TargetArchitecture architec private static InstructionSetFlags ExpandInstructionSetByReverseImplicationHelper(TargetArchitecture architecture, InstructionSetFlags input) { - InstructionSetFlags oldflags = input; + InstructionSetFlags oldflags; InstructionSetFlags resultflags = input; do { diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoTypes.VarInfo.cs b/src/coreclr/tools/Common/JitInterface/CorInfoTypes.VarInfo.cs index ff85f537803fe9..cd6d82f8f511e8 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoTypes.VarInfo.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoTypes.VarInfo.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Diagnostics; using System.Runtime.InteropServices; // diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoTypes.cs b/src/coreclr/tools/Common/JitInterface/CorInfoTypes.cs index 4d054a1074494e..66fac586cb31ae 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoTypes.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoTypes.cs @@ -5,7 +5,6 @@ using System.Diagnostics; using System.Runtime.InteropServices; using Internal.Pgo; -using Internal.TypeSystem; namespace Internal.JitInterface { @@ -889,10 +888,10 @@ public enum CORINFO_TAILCALL_HELPERS_FLAGS [StructLayout(LayoutKind.Sequential)] public unsafe struct CORINFO_TAILCALL_HELPERS { - CORINFO_TAILCALL_HELPERS_FLAGS flags; - CORINFO_METHOD_STRUCT_* hStoreArgs; - CORINFO_METHOD_STRUCT_* hCallTarget; - CORINFO_METHOD_STRUCT_* hDispatcher; + private CORINFO_TAILCALL_HELPERS_FLAGS flags; + private CORINFO_METHOD_STRUCT_* hStoreArgs; + private CORINFO_METHOD_STRUCT_* hCallTarget; + private CORINFO_METHOD_STRUCT_* hDispatcher; }; public enum CORINFO_THIS_TRANSFORM @@ -1432,7 +1431,7 @@ public enum CorJitFlag : uint public struct CORJIT_FLAGS { - private UInt64 _corJitFlags; + private ulong _corJitFlags; public InstructionSetFlags InstructionSetFlags; public void Reset() diff --git a/src/coreclr/tools/Common/JitInterface/JitConfigProvider.cs b/src/coreclr/tools/Common/JitInterface/JitConfigProvider.cs index 898ec59e5a5d38..2605d5489dea46 100644 --- a/src/coreclr/tools/Common/JitInterface/JitConfigProvider.cs +++ b/src/coreclr/tools/Common/JitInterface/JitConfigProvider.cs @@ -6,7 +6,6 @@ using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; -using ILCompiler; using Internal.TypeSystem; using NumberStyles = System.Globalization.NumberStyles; @@ -79,7 +78,7 @@ public IntPtr UnmanagedInstance /// A collection of parameter name/value pairs. public JitConfigProvider(IEnumerable jitFlags, IEnumerable> parameters) { - ArrayBuilder jitFlagBuilder = new ArrayBuilder(); + ArrayBuilder jitFlagBuilder = default(ArrayBuilder); foreach (CorJitFlag jitFlag in jitFlags) { jitFlagBuilder.Add(jitFlag); @@ -110,7 +109,7 @@ public int GetIntConfigValue(string name, int defaultValue) string stringValue; int intValue; if (_config.TryGetValue(name, out stringValue) && - Int32.TryParse(stringValue, NumberStyles.AllowHexSpecifier, null, out intValue)) + int.TryParse(stringValue, NumberStyles.AllowHexSpecifier, null, out intValue)) { return intValue; } @@ -126,7 +125,7 @@ public string GetStringConfigValue(string name) return stringValue; } - return String.Empty; + return string.Empty; } private static string GetTargetSpec(TargetDetails target) diff --git a/src/coreclr/tools/Common/JitInterface/LoongArch64PassStructInRegister.cs b/src/coreclr/tools/Common/JitInterface/LoongArch64PassStructInRegister.cs index 0a164d23ebee15..88125fe5bad7f4 100644 --- a/src/coreclr/tools/Common/JitInterface/LoongArch64PassStructInRegister.cs +++ b/src/coreclr/tools/Common/JitInterface/LoongArch64PassStructInRegister.cs @@ -1,9 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections.Generic; using System.Diagnostics; -using ILCompiler; using Internal.TypeSystem; namespace Internal.JitInterface @@ -20,10 +18,7 @@ public static uint GetLoongArch64PassStructInRegisterFlags(TypeDesc typeDesc) { if (!field.IsStatic) { - if (firstField == null) - { - firstField = field; - } + firstField ??= field; numIntroducedFields++; } } @@ -95,7 +90,7 @@ public static uint GetLoongArch64PassStructInRegisterFlags(TypeDesc typeDesc) } else if ((floatFieldFlags & (uint)StructFloatFieldInfoFlags.STRUCT_FLOAT_FIELD_FIRST) != 0) { - floatFieldFlags = floatFieldFlags ^ (uint)StructFloatFieldInfoFlags.STRUCT_MERGE_FIRST_SECOND_8; + floatFieldFlags ^= (uint)StructFloatFieldInfoFlags.STRUCT_MERGE_FIRST_SECOND_8; } else { diff --git a/src/coreclr/tools/Common/JitInterface/MemoryHelper.cs b/src/coreclr/tools/Common/JitInterface/MemoryHelper.cs index ce7edb1e56be38..ac009bcd17da11 100644 --- a/src/coreclr/tools/Common/JitInterface/MemoryHelper.cs +++ b/src/coreclr/tools/Common/JitInterface/MemoryHelper.cs @@ -1,8 +1,6 @@ // 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 Internal.JitInterface { internal static unsafe class MemoryHelper diff --git a/src/coreclr/tools/Common/JitInterface/SystemVStructClassificator.cs b/src/coreclr/tools/Common/JitInterface/SystemVStructClassificator.cs index 1237cdb3dd34e3..e8c1a01f86022c 100644 --- a/src/coreclr/tools/Common/JitInterface/SystemVStructClassificator.cs +++ b/src/coreclr/tools/Common/JitInterface/SystemVStructClassificator.cs @@ -5,12 +5,11 @@ using System.Diagnostics; using ILCompiler; using Internal.TypeSystem; +using static Internal.JitInterface.SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR; +using static Internal.JitInterface.SystemVClassificationType; namespace Internal.JitInterface { - using static SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR; - using static SystemVClassificationType; - internal static class SystemVStructClassificator { private struct SystemVStructRegisterPassingHelper @@ -65,7 +64,7 @@ internal SystemVStructRegisterPassingHelper(int totalStructSize) public int[] FieldOffsets; }; - private class FieldEnumerator + private static class FieldEnumerator { internal static IEnumerable GetInstanceFields(TypeDesc typeDesc, bool isFixedBuffer, int numIntroducedFields) { @@ -167,7 +166,7 @@ private static SystemVClassificationType TypeDef2SystemVClassification(TypeDesc // If we have a field classification already, but there is a union, we must merge the classification type of the field. Returns the // new, merged classification type. - static SystemVClassificationType ReClassifyField(SystemVClassificationType originalClassification, SystemVClassificationType newFieldClassification) + private static SystemVClassificationType ReClassifyField(SystemVClassificationType originalClassification, SystemVClassificationType newFieldClassification) { Debug.Assert((newFieldClassification == SystemVClassificationTypeInteger) || (newFieldClassification == SystemVClassificationTypeIntegerReference) || @@ -226,10 +225,7 @@ private static bool ClassifyEightBytes(TypeDesc typeDesc, { if (!field.IsStatic) { - if (firstField == null) - { - firstField = field; - } + firstField ??= field; numIntroducedFields++; } } diff --git a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetGenerator.cs b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetGenerator.cs index fb97127666eb17..97c4feb5cfb049 100644 --- a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetGenerator.cs +++ b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetGenerator.cs @@ -375,11 +375,9 @@ public void WriteManagedJitInstructionSet(TextWriter tr) // FROM /src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetDesc.txt // using /src/coreclr/tools/Common/JitInterface/ThunkGenerator/gen.bat -using System; using System.Collections; using System.Collections.Generic; using System.Linq; -using System.Runtime.InteropServices; using Internal.TypeSystem; namespace Internal.JitInterface @@ -522,7 +520,7 @@ IEnumerator IEnumerable.GetEnumerator() public IEnumerator GetEnumerator() { - for (int i = 1; i < (int)InstructionSet.NONE; i ++) + for (int i = 1; i < (int)InstructionSet.NONE; i++) { InstructionSet instructionSet = (InstructionSet)i; if (HasInstructionSet(instructionSet)) @@ -581,12 +579,12 @@ public static InstructionSet ConvertToImpliedInstructionSetForVectorInstructionS public static InstructionSetFlags ExpandInstructionSetByImplicationHelper(TargetArchitecture architecture, InstructionSetFlags input) { - InstructionSetFlags oldflags = input; + InstructionSetFlags oldflags; InstructionSetFlags resultflags = input; do { oldflags = resultflags; - switch(architecture) + switch (architecture) { "); foreach (string architecture in _architectures) @@ -624,7 +622,7 @@ public void ExpandInstructionSetByReverseImplication(TargetArchitecture architec private static InstructionSetFlags ExpandInstructionSetByReverseImplicationHelper(TargetArchitecture architecture, InstructionSetFlags input) { - InstructionSetFlags oldflags = input; + InstructionSetFlags oldflags; InstructionSetFlags resultflags = input; do { diff --git a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/Program.cs b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/Program.cs index 5cd8cb6e66c316..b0d12f06cdc12c 100644 --- a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/Program.cs +++ b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/Program.cs @@ -279,14 +279,14 @@ static void WriteManagedThunkInterface(TextWriter tw, IEnumerable namespace Internal.JitInterface { - unsafe partial class CorInfoImpl + internal unsafe partial class CorInfoImpl { "); foreach (FunctionDecl decl in functionData) { tw.WriteLine(" [UnmanagedCallersOnly]"); - tw.Write($" static {decl.ReturnType.UnmanagedTypeName} _{decl.FunctionName}(IntPtr thisHandle, IntPtr* ppException"); + tw.Write($" private static {decl.ReturnType.UnmanagedTypeName} _{decl.FunctionName}(IntPtr thisHandle, IntPtr* ppException"); foreach (Parameter param in decl.Parameters) { tw.Write($", {param.Type.UnmanagedTypeName} {param.Name}"); @@ -344,7 +344,7 @@ unsafe partial class CorInfoImpl int total = functionData.Count(); tw.WriteLine(@" - static IntPtr GetUnmanagedCallbacks() + private static IntPtr GetUnmanagedCallbacks() { void** callbacks = (void**)Marshal.AllocCoTaskMem(sizeof(IntPtr) * " + total + @"); "); diff --git a/src/coreclr/tools/Common/JitInterface/TypeString.cs b/src/coreclr/tools/Common/JitInterface/TypeString.cs index db60084315132f..7bdb02e08107f8 100644 --- a/src/coreclr/tools/Common/JitInterface/TypeString.cs +++ b/src/coreclr/tools/Common/JitInterface/TypeString.cs @@ -10,7 +10,7 @@ namespace Internal.JitInterface // This is a very rough equivalent of typestring.cpp in the CLR. // There's way more rules to capture. Hopefully, we'll only ever need this in the code to recognize SIMD intrisics // and we won't need to replicate all the details around escaping and such. - internal class TypeString : TypeNameFormatter + internal sealed class TypeString : TypeNameFormatter { public static TypeString Instance { get; } = new TypeString(); @@ -29,7 +29,7 @@ public override void AppendName(StringBuilder sb, GenericParameterDesc type) public override void AppendName(StringBuilder sb, SignatureTypeVariable type) { - sb.Append("!"); + sb.Append('!'); sb.Append(type.Index); } @@ -59,7 +59,7 @@ public override void AppendName(StringBuilder sb, FunctionPointerType type) public override void AppendName(StringBuilder sb, ByRefType type) { AppendName(sb, type.ParameterType); - sb.Append("&"); + sb.Append('&'); } public override void AppendName(StringBuilder sb, ArrayType type) diff --git a/src/coreclr/tools/Common/JitInterface/UnboxingMethodDesc.cs b/src/coreclr/tools/Common/JitInterface/UnboxingMethodDesc.cs index 0db82ff37eb0f9..e21794718c8b2e 100644 --- a/src/coreclr/tools/Common/JitInterface/UnboxingMethodDesc.cs +++ b/src/coreclr/tools/Common/JitInterface/UnboxingMethodDesc.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections.Generic; using System.Diagnostics; using Internal.TypeSystem; @@ -13,7 +12,7 @@ namespace Internal.JitInterface /// This class is for internal purposes within the JitInterface. It's not expected /// for it to escape the JitInterface. /// - internal class UnboxingMethodDesc : MethodDelegator + internal sealed class UnboxingMethodDesc : MethodDelegator { private readonly UnboxingMethodDescFactory _factory; diff --git a/src/coreclr/tools/Common/JitInterface/UnboxingMethodDescFactory.cs b/src/coreclr/tools/Common/JitInterface/UnboxingMethodDescFactory.cs index 4f38998f5cb5f0..457f2fa87259ac 100644 --- a/src/coreclr/tools/Common/JitInterface/UnboxingMethodDescFactory.cs +++ b/src/coreclr/tools/Common/JitInterface/UnboxingMethodDescFactory.cs @@ -1,14 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Generic; -using System.Diagnostics; using Internal.TypeSystem; namespace Internal.JitInterface { - internal class UnboxingMethodDescFactory : Dictionary + internal sealed class UnboxingMethodDescFactory : Dictionary { public UnboxingMethodDesc GetUnboxingMethod(MethodDesc method) { diff --git a/src/coreclr/tools/Common/Pgo/PgoFormat.cs b/src/coreclr/tools/Common/Pgo/PgoFormat.cs index 5dc847b34810b0..fa4fe3c1a31809 100644 --- a/src/coreclr/tools/Common/Pgo/PgoFormat.cs +++ b/src/coreclr/tools/Common/Pgo/PgoFormat.cs @@ -5,8 +5,6 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Text.RegularExpressions; -using ILCompiler; namespace Internal.Pgo { @@ -113,8 +111,8 @@ private enum InstrumentationDataProcessingState public class PgoEncodedCompressedIntParser : IEnumerable, IEnumerator { - long _current; - byte[] _bytes; + private long _current; + private byte[] _bytes; public PgoEncodedCompressedIntParser(byte[] bytes, int startOffset) { @@ -319,7 +317,7 @@ public static IEnumerable ParsePgoData(IPgoSchema else curSchema.ILOffset = checked((int)value); - processingState = processingState & ~InstrumentationDataProcessingState.ILOffset; + processingState &= ~InstrumentationDataProcessingState.ILOffset; } else if ((processingState & InstrumentationDataProcessingState.Type) == InstrumentationDataProcessingState.Type) { @@ -328,7 +326,7 @@ public static IEnumerable ParsePgoData(IPgoSchema else curSchema.InstrumentationKind = (PgoInstrumentationKind)value; - processingState = processingState & ~InstrumentationDataProcessingState.Type; + processingState &= ~InstrumentationDataProcessingState.Type; } else if ((processingState & InstrumentationDataProcessingState.Count) == InstrumentationDataProcessingState.Count) { @@ -336,7 +334,7 @@ public static IEnumerable ParsePgoData(IPgoSchema curSchema.Count = checked((int)(value + (long)curSchema.Count)); else curSchema.Count = checked((int)value); - processingState = processingState & ~InstrumentationDataProcessingState.Count; + processingState &= ~InstrumentationDataProcessingState.Count; } else if ((processingState & InstrumentationDataProcessingState.Other) == InstrumentationDataProcessingState.Other) { @@ -344,7 +342,7 @@ public static IEnumerable ParsePgoData(IPgoSchema curSchema.Other = checked((int)(value + (long)curSchema.Other)); else curSchema.Other = checked((int)value); - processingState = processingState & ~InstrumentationDataProcessingState.Other; + processingState &= ~InstrumentationDataProcessingState.Other; } if (processingState == InstrumentationDataProcessingState.Done) @@ -412,13 +410,13 @@ public static void EncodePgoData(IEnumerable sche if (!emitAllElementsUnconditionally) { if (ilOffsetDiff != 0) - modifyMask = modifyMask | InstrumentationDataProcessingState.ILOffset; + modifyMask |= InstrumentationDataProcessingState.ILOffset; if (TypeDiff != 0) - modifyMask = modifyMask | InstrumentationDataProcessingState.Type; + modifyMask |= InstrumentationDataProcessingState.Type; if (CountDiff != 0) - modifyMask = modifyMask | InstrumentationDataProcessingState.Count; + modifyMask |= InstrumentationDataProcessingState.Count; if (OtherDiff != 0) - modifyMask = modifyMask | InstrumentationDataProcessingState.Other; + modifyMask |= InstrumentationDataProcessingState.Other; } else { @@ -511,7 +509,7 @@ public static void EncodePgoData(IEnumerable sche } - private class PgoSchemaMergeComparer : IComparer, IEqualityComparer + private sealed class PgoSchemaMergeComparer : IComparer, IEqualityComparer { public static PgoSchemaMergeComparer Singleton = new PgoSchemaMergeComparer(); @@ -563,7 +561,7 @@ public static PgoSchemaElem[] Merge(ReadOnlySpan(ReadOnlySpan dataMerger, PgoSchemaElem schema) + static void MergeInSchemaElem(Dictionary dataMerger, PgoSchemaElem schema) { if (dataMerger.TryGetValue(schema, out var existingSchemaItem)) { @@ -648,7 +646,7 @@ void MergeInSchemaElem(Dictionary dataMerger, PgoS } Debug.Assert(PgoSchemaMergeComparer.Singleton.Compare(schema, mergedElem) == 0); - Debug.Assert(PgoSchemaMergeComparer.Singleton.Equals(schema, mergedElem) == true); + Debug.Assert(PgoSchemaMergeComparer.Singleton.Equals(schema, mergedElem)); dataMerger[mergedElem] = mergedElem; } else diff --git a/src/coreclr/tools/Common/Pgo/TypeSystemEntityOrUnknown.cs b/src/coreclr/tools/Common/Pgo/TypeSystemEntityOrUnknown.cs index 6eabe55cf7cc52..2a064ebf032091 100644 --- a/src/coreclr/tools/Common/Pgo/TypeSystemEntityOrUnknown.cs +++ b/src/coreclr/tools/Common/Pgo/TypeSystemEntityOrUnknown.cs @@ -23,7 +23,7 @@ public TypeSystemEntityOrUnknown(MethodDesc method) _data = method; } - readonly object _data; + private readonly object _data; public TypeDesc AsType => _data as TypeDesc; public MethodDesc AsMethod => _data as MethodDesc; public FieldDesc AsField => _data as FieldDesc; @@ -39,7 +39,7 @@ public bool Equals(TypeSystemEntityOrUnknown other) } else { - return object.ReferenceEquals(_data, other._data); + return ReferenceEquals(_data, other._data); } } diff --git a/src/coreclr/tools/Common/Sorting/ISortableDataStructureAccessor.cs b/src/coreclr/tools/Common/Sorting/ISortableDataStructureAccessor.cs index e6699d4d0febba..c2ec9f24b84f96 100644 --- a/src/coreclr/tools/Common/Sorting/ISortableDataStructureAccessor.cs +++ b/src/coreclr/tools/Common/Sorting/ISortableDataStructureAccessor.cs @@ -1,10 +1,6 @@ // 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.Threading.Tasks; - namespace ILCompiler { internal interface ISortableDataStructureAccessor diff --git a/src/coreclr/tools/Common/Sorting/ListAccessor.cs b/src/coreclr/tools/Common/Sorting/ListAccessor.cs index 962bd3f38a0087..f26f1ff5acaa8b 100644 --- a/src/coreclr/tools/Common/Sorting/ListAccessor.cs +++ b/src/coreclr/tools/Common/Sorting/ListAccessor.cs @@ -1,7 +1,6 @@ // 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; namespace ILCompiler.Sorting.Implementation diff --git a/src/coreclr/tools/Common/Sorting/MergeSort.cs b/src/coreclr/tools/Common/Sorting/MergeSort.cs index cbf5d1da814b02..7faf01aeafb5b8 100644 --- a/src/coreclr/tools/Common/Sorting/MergeSort.cs +++ b/src/coreclr/tools/Common/Sorting/MergeSort.cs @@ -61,7 +61,7 @@ public static void MergeSortAllowDuplicates(this T[] arrayToSort, IComparer delegates instead of IComparer instances private struct ComparisonWrapper : IComparer { - Comparison _comparison; + private Comparison _comparison; public ComparisonWrapper(Comparison comparison) { _comparison = comparison; diff --git a/src/coreclr/tools/Common/Sorting/MergeSortCore.cs b/src/coreclr/tools/Common/Sorting/MergeSortCore.cs index 6998c99737916b..b69e733d3aa700 100644 --- a/src/coreclr/tools/Common/Sorting/MergeSortCore.cs +++ b/src/coreclr/tools/Common/Sorting/MergeSortCore.cs @@ -1,7 +1,6 @@ // 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.Threading.Tasks; @@ -44,8 +43,8 @@ private static async Task ParallelSort(TDataStructure arrayToSort, int index, in T[] localCopyOfHalfOfArray = new T[halfLen]; accessor.Copy(arrayToSort, index, localCopyOfHalfOfArray, 0, halfLen); - await MergeSortCore, TComparer, TCompareAsEqualAction>.ParallelSort(localCopyOfHalfOfArray, 0, halfLen, comparer); - await rightSortTask; + await MergeSortCore, TComparer, TCompareAsEqualAction>.ParallelSort(localCopyOfHalfOfArray, 0, halfLen, comparer).ConfigureAwait(true); + await rightSortTask.ConfigureAwait(true); Merge(localCopyOfHalfOfArray, arrayToSort, index, halfLen, length, comparer); } } diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/ArrayType.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/ArrayType.Canon.cs index 7deba06d193c27..5689f6101853df 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/ArrayType.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/ArrayType.Canon.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Implements canonicalization for arrays - partial class ArrayType + public partial class ArrayType { protected override TypeDesc ConvertToCanonFormImpl(CanonicalFormKind kind) { @@ -21,7 +21,7 @@ protected override TypeDesc ConvertToCanonFormImpl(CanonicalFormKind kind) } // Implements canonicalization for array methods - partial class ArrayMethod + public partial class ArrayMethod { public override bool IsCanonicalMethod(CanonicalFormKind policy) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/ByRefType.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/ByRefType.Canon.cs index 97513cb08e4bd1..53c01d00bbe114 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/ByRefType.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/ByRefType.Canon.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Implements canonicalizing ByRefs - partial class ByRefType + public partial class ByRefType { protected override TypeDesc ConvertToCanonFormImpl(CanonicalFormKind kind) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/CanonTypes.Diagnostic.cs b/src/coreclr/tools/Common/TypeSystem/Canon/CanonTypes.Diagnostic.cs index d8906a8a7dfb17..2a6843397b6022 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/CanonTypes.Diagnostic.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/CanonTypes.Diagnostic.cs @@ -1,13 +1,6 @@ // 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 Internal.NativeFormat; - -using Debug = System.Diagnostics.Debug; - namespace Internal.TypeSystem { internal sealed partial class CanonType diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/CanonTypes.Interop.cs b/src/coreclr/tools/Common/TypeSystem/Canon/CanonTypes.Interop.cs index c5e1e39bc977a8..6897279ac030a5 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/CanonTypes.Interop.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/CanonTypes.Interop.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class CanonBaseType + public partial class CanonBaseType { public override PInvokeStringFormat PInvokeStringFormat => default(PInvokeStringFormat); } diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/CanonTypes.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Canon/CanonTypes.Sorting.cs index 8646ad432b4464..32e4db3bab9e1e 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/CanonTypes.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/CanonTypes.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types - partial class CanonBaseType + public partial class CanonBaseType { protected internal sealed override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) { @@ -16,12 +16,12 @@ protected internal sealed override int CompareToImpl(TypeDesc other, TypeSystemC } } - partial class CanonType + internal partial class CanonType { protected internal override int ClassCode => 46114331; } - partial class UniversalCanonType + internal partial class UniversalCanonType { protected internal override int ClassCode => 1687626054; } diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/DefType.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/DefType.Canon.cs index 3d783352c1809a..7c959d1c3a6cd4 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/DefType.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/DefType.Canon.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Implements canonicalization handling for TypeDefs - partial class DefType + public partial class DefType { protected override TypeDesc ConvertToCanonFormImpl(CanonicalFormKind kind) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/FunctionPointerType.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/FunctionPointerType.Canon.cs index 8ff4c2ee544d35..ce0f96f7990bda 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/FunctionPointerType.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/FunctionPointerType.Canon.cs @@ -1,12 +1,10 @@ // 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 Internal.TypeSystem { // Holds code for canonicalizing a function pointer type - partial class FunctionPointerType + public partial class FunctionPointerType { public override bool IsCanonicalSubtype(CanonicalFormKind policy) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/InstantiatedMethod.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/InstantiatedMethod.Canon.cs index 263615253fa0c3..a5cb3efa1cb21c 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/InstantiatedMethod.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/InstantiatedMethod.Canon.cs @@ -6,14 +6,14 @@ namespace Internal.TypeSystem { // Implements generic method canonicalization - partial class InstantiatedMethod + public partial class InstantiatedMethod { /// /// Stores a cached version of the canonicalized form of this method since /// calculating it is a recursive operation /// - InstantiatedMethod _specificCanonCache; - InstantiatedMethod _universalCanonCache; + private InstantiatedMethod _specificCanonCache; + private InstantiatedMethod _universalCanonCache; /// /// Returns the result of canonicalizing this method over the given kind of Canon @@ -52,7 +52,7 @@ public override MethodDesc GetCanonMethodTarget(CanonicalFormKind kind) return canonicalMethodResult; } - InstantiatedMethod GetCachedCanonValue(CanonicalFormKind kind) + private InstantiatedMethod GetCachedCanonValue(CanonicalFormKind kind) { switch (kind) { @@ -68,7 +68,7 @@ InstantiatedMethod GetCachedCanonValue(CanonicalFormKind kind) } } - void SetCachedCanonValue(CanonicalFormKind kind, InstantiatedMethod value) + private void SetCachedCanonValue(CanonicalFormKind kind, InstantiatedMethod value) { switch (kind) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/InstantiatedType.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/InstantiatedType.Canon.cs index 5bbbffc42f9252..d57b2e19f9b9fb 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/InstantiatedType.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/InstantiatedType.Canon.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Implements canonicalization for generic instantiations - partial class InstantiatedType + public partial class InstantiatedType { public override bool IsCanonicalSubtype(CanonicalFormKind policy) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/MetadataType.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/MetadataType.Canon.cs index 2d9d4d45e10698..77637916470405 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/MetadataType.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/MetadataType.Canon.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Holds code for canonicalization of metadata types - partial class MetadataType + public partial class MetadataType { public override bool IsCanonicalSubtype(CanonicalFormKind policy) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/MethodDelegator.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/MethodDelegator.Canon.cs index 9b89c40353e0cd..e4e5211d08a951 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/MethodDelegator.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/MethodDelegator.Canon.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class MethodDelegator + public partial class MethodDelegator { public override bool IsCanonicalMethod(CanonicalFormKind policy) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/MethodDesc.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/MethodDesc.Canon.cs index 0189311657e55a..00e0d6859ffd8f 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/MethodDesc.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/MethodDesc.Canon.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Implements method canonicalization - partial class MethodDesc + public partial class MethodDesc { public virtual bool IsCanonicalMethod(CanonicalFormKind policy) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/MethodForInstantiatedType.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/MethodForInstantiatedType.Canon.cs index ec81730a0a8785..2125dd63c19947 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/MethodForInstantiatedType.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/MethodForInstantiatedType.Canon.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Implements canonicalization for methods on instantiated types - partial class MethodForInstantiatedType + public partial class MethodForInstantiatedType { public override bool IsCanonicalMethod(CanonicalFormKind policy) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/ParameterizedType.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/ParameterizedType.Canon.cs index a66eeb39d88fe9..774c1ce60f2dd6 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/ParameterizedType.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/ParameterizedType.Canon.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Holds code for canonicalizing a parameterized type - partial class ParameterizedType + public partial class ParameterizedType { public sealed override bool IsCanonicalSubtype(CanonicalFormKind policy) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/PointerType.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/PointerType.Canon.cs index 28e35a96a2c785..f3dee20511c336 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/PointerType.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/PointerType.Canon.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Holds code for canonicalizing pointers - partial class PointerType + public partial class PointerType { protected override TypeDesc ConvertToCanonFormImpl(CanonicalFormKind kind) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/SignatureVariable.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/SignatureVariable.Canon.cs index 2e76e9eed0677f..d6675b5d4f796d 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/SignatureVariable.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/SignatureVariable.Canon.cs @@ -6,7 +6,7 @@ namespace Internal.TypeSystem { // Implements canonicalization of generic type parameters - partial class SignatureTypeVariable + public partial class SignatureTypeVariable { public override bool IsCanonicalSubtype(CanonicalFormKind policy) { @@ -22,7 +22,7 @@ protected override TypeDesc ConvertToCanonFormImpl(CanonicalFormKind kind) } // Implements canonicalization of generic method parameters - partial class SignatureMethodVariable + public partial class SignatureMethodVariable { public override bool IsCanonicalSubtype(CanonicalFormKind policy) { diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/TypeDesc.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/TypeDesc.Canon.cs index c0ce80263aad8c..0fbd5ecbbbb50e 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/TypeDesc.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/TypeDesc.Canon.cs @@ -6,15 +6,16 @@ namespace Internal.TypeSystem { // Implements canonicalization for types - partial class TypeDesc + public partial class TypeDesc { /// /// Stores a cached version of the canonicalized form of this type since /// calculating it is a recursive operation /// - TypeDesc _specificCanonCache; - TypeDesc _universalCanonCache; - TypeDesc GetCachedCanonValue(CanonicalFormKind kind) + private TypeDesc _specificCanonCache; + private TypeDesc _universalCanonCache; + + private TypeDesc GetCachedCanonValue(CanonicalFormKind kind) { switch (kind) { @@ -30,7 +31,7 @@ TypeDesc GetCachedCanonValue(CanonicalFormKind kind) } } - void SetCachedCanonValue(CanonicalFormKind kind, TypeDesc value) + private void SetCachedCanonValue(CanonicalFormKind kind, TypeDesc value) { switch (kind) { diff --git a/src/coreclr/tools/Common/TypeSystem/CodeGen/FieldDesc.CodeGen.cs b/src/coreclr/tools/Common/TypeSystem/CodeGen/FieldDesc.CodeGen.cs index 43f05e4d85f22d..fa4f3bf017c2a6 100644 --- a/src/coreclr/tools/Common/TypeSystem/CodeGen/FieldDesc.CodeGen.cs +++ b/src/coreclr/tools/Common/TypeSystem/CodeGen/FieldDesc.CodeGen.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Additional members of FieldDesc related to code generation. - partial class FieldDesc + public partial class FieldDesc { /// /// Gets a value indicating whether this is a field that needs to be treated @@ -19,7 +19,7 @@ public virtual bool IsIntrinsic } } - partial class FieldForInstantiatedType + public partial class FieldForInstantiatedType { public override bool IsIntrinsic { diff --git a/src/coreclr/tools/Common/TypeSystem/CodeGen/MethodDelegator.CodeGen.cs b/src/coreclr/tools/Common/TypeSystem/CodeGen/MethodDelegator.CodeGen.cs index 41425033e5bc6b..0e1734043ddd7e 100644 --- a/src/coreclr/tools/Common/TypeSystem/CodeGen/MethodDelegator.CodeGen.cs +++ b/src/coreclr/tools/Common/TypeSystem/CodeGen/MethodDelegator.CodeGen.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class MethodDelegator + public partial class MethodDelegator { public override bool IsIntrinsic { diff --git a/src/coreclr/tools/Common/TypeSystem/CodeGen/NativeStructType.CodeGen.cs b/src/coreclr/tools/Common/TypeSystem/CodeGen/NativeStructType.CodeGen.cs index 320b8de11b09fc..0e4d9286735236 100644 --- a/src/coreclr/tools/Common/TypeSystem/CodeGen/NativeStructType.CodeGen.cs +++ b/src/coreclr/tools/Common/TypeSystem/CodeGen/NativeStructType.CodeGen.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem.Interop { // Implements INonEmittableType - partial class NativeStructType : INonEmittableType + public partial class NativeStructType : INonEmittableType { } } diff --git a/src/coreclr/tools/Common/TypeSystem/CodeGen/TargetDetails.CodeGen.cs b/src/coreclr/tools/Common/TypeSystem/CodeGen/TargetDetails.CodeGen.cs index f24974c811b78e..353399eb78b7fb 100644 --- a/src/coreclr/tools/Common/TypeSystem/CodeGen/TargetDetails.CodeGen.cs +++ b/src/coreclr/tools/Common/TypeSystem/CodeGen/TargetDetails.CodeGen.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Extension to TargetDetails related to code generation - partial class TargetDetails + public partial class TargetDetails { public TargetDetails(TargetArchitecture architecture, TargetOS targetOS, TargetAbi abi, SimdVectorLength simdVectorLength) : this(architecture, targetOS, abi) diff --git a/src/coreclr/tools/Common/TypeSystem/CodeGen/TypeDesc.CodeGen.cs b/src/coreclr/tools/Common/TypeSystem/CodeGen/TypeDesc.CodeGen.cs index eb15a3681d5a41..860285c10f2341 100644 --- a/src/coreclr/tools/Common/TypeSystem/CodeGen/TypeDesc.CodeGen.cs +++ b/src/coreclr/tools/Common/TypeSystem/CodeGen/TypeDesc.CodeGen.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class TypeDesc + public partial class TypeDesc { /// /// Gets a value indicating whether this is a type that needs to be treated @@ -18,7 +18,7 @@ public bool IsIntrinsic } } - partial class InstantiatedType + public partial class InstantiatedType { partial void AddComputedIntrinsicFlag(ref TypeFlags flags) { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/ArrayOfTRuntimeInterfacesAlgorithm.cs b/src/coreclr/tools/Common/TypeSystem/Common/ArrayOfTRuntimeInterfacesAlgorithm.cs index 0e6328904c7ee6..26aca2534517aa 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/ArrayOfTRuntimeInterfacesAlgorithm.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/ArrayOfTRuntimeInterfacesAlgorithm.cs @@ -1,7 +1,6 @@ // 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 Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem diff --git a/src/coreclr/tools/Common/TypeSystem/Common/ArrayType.cs b/src/coreclr/tools/Common/TypeSystem/Common/ArrayType.cs index c21ba9342e1980..dc1fc9667faa92 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/ArrayType.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/ArrayType.cs @@ -1,7 +1,6 @@ // 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.Threading; diff --git a/src/coreclr/tools/Common/TypeSystem/Common/BaseTypeRuntimeInterfacesAlgorithm.cs b/src/coreclr/tools/Common/TypeSystem/Common/BaseTypeRuntimeInterfacesAlgorithm.cs index 41ff1102a8ed6d..0835048af5f962 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/BaseTypeRuntimeInterfacesAlgorithm.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/BaseTypeRuntimeInterfacesAlgorithm.cs @@ -1,9 +1,6 @@ // 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 Debug = System.Diagnostics.Debug; - namespace Internal.TypeSystem { /// diff --git a/src/coreclr/tools/Common/TypeSystem/Common/CastingHelper.cs b/src/coreclr/tools/Common/TypeSystem/Common/CastingHelper.cs index 51ed0327c3424d..d0f32078e97df6 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/CastingHelper.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/CastingHelper.cs @@ -1,8 +1,6 @@ // 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 Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem @@ -535,7 +533,7 @@ private static bool IsBoxedAndCanCastTo(this TypeDesc thisType, TypeDesc otherTy return false; } - private class StackOverflowProtect + private sealed class StackOverflowProtect { private CastingPair _value; private StackOverflowProtect _previous; diff --git a/src/coreclr/tools/Common/TypeSystem/Common/ConstructedTypeRewritingHelpers.cs b/src/coreclr/tools/Common/TypeSystem/Common/ConstructedTypeRewritingHelpers.cs index 42011765c379d3..41e119bae681d3 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/ConstructedTypeRewritingHelpers.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/ConstructedTypeRewritingHelpers.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections.Generic; using System.Diagnostics; namespace Internal.TypeSystem diff --git a/src/coreclr/tools/Common/TypeSystem/Common/DefType.Diagnostic.cs b/src/coreclr/tools/Common/TypeSystem/Common/DefType.Diagnostic.cs index 26685ff43b2f3f..d1dc3c659ee325 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/DefType.Diagnostic.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/DefType.Diagnostic.cs @@ -1,15 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - namespace Internal.TypeSystem { /// /// Type with metadata available that is equivalent to a TypeDef record in an ECMA 335 metadata stream. /// A class, an interface, or a value type. /// - abstract partial class DefType + public abstract partial class DefType { /// /// Gets the Name of a type. This must not throw diff --git a/src/coreclr/tools/Common/TypeSystem/Common/DefType.FieldLayout.cs b/src/coreclr/tools/Common/TypeSystem/Common/DefType.FieldLayout.cs index 4c3555c198af66..99305804f53519 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/DefType.FieldLayout.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/DefType.FieldLayout.cs @@ -75,7 +75,7 @@ private static class FieldLayoutFlags public const int IsInt128OrHasInt128Fields = 0x800; } - private class StaticBlockInfo + private sealed class StaticBlockInfo { public StaticsBlock NonGcStatics; public StaticsBlock GcStatics; @@ -83,17 +83,15 @@ private class StaticBlockInfo public StaticsBlock ThreadGcStatics; } - ThreadSafeFlags _fieldLayoutFlags; - - LayoutInt _instanceFieldSize; - LayoutInt _instanceFieldAlignment; - LayoutInt _instanceByteCountUnaligned; - LayoutInt _instanceByteAlignment; + private ThreadSafeFlags _fieldLayoutFlags; + private LayoutInt _instanceFieldSize; + private LayoutInt _instanceFieldAlignment; + private LayoutInt _instanceByteCountUnaligned; + private LayoutInt _instanceByteAlignment; // Information about various static blocks is rare, so we keep it out of line. - StaticBlockInfo _staticBlockInfo; - - ValueTypeShapeCharacteristics _valueTypeShapeCharacteristics; + private StaticBlockInfo _staticBlockInfo; + private ValueTypeShapeCharacteristics _valueTypeShapeCharacteristics; /// /// Does a type transitively have any fields which are GC object pointers diff --git a/src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.FieldLayout.cs b/src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.FieldLayout.cs index 2d8daed2caf118..e7b5e6d21478dc 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.FieldLayout.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.FieldLayout.cs @@ -1,7 +1,6 @@ // 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; namespace Internal.TypeSystem diff --git a/src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.ToString.cs b/src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.ToString.cs index cde79093f286b3..6d52f349f24c0e 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.ToString.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.ToString.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class FieldDesc + public partial class FieldDesc { public override string ToString() { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.cs b/src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.cs index 23bd5ba923a54d..a18221761429df 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Runtime.CompilerServices; using Debug = System.Diagnostics.Debug; @@ -23,8 +22,8 @@ public override int GetHashCode() public override bool Equals(object o) { // Its only valid to compare two FieldDescs in the same context - Debug.Assert(o is not FieldDesc || object.ReferenceEquals(((FieldDesc)o).Context, this.Context)); - return object.ReferenceEquals(this, o); + Debug.Assert(o is not FieldDesc || ReferenceEquals(((FieldDesc)o).Context, this.Context)); + return ReferenceEquals(this, o); } public virtual string Name diff --git a/src/coreclr/tools/Common/TypeSystem/Common/FieldForInstantiatedType.cs b/src/coreclr/tools/Common/TypeSystem/Common/FieldForInstantiatedType.cs index fbc456a830639c..692e4db2a0aa9b 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/FieldForInstantiatedType.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/FieldForInstantiatedType.cs @@ -1,8 +1,6 @@ // 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 Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem @@ -47,7 +45,7 @@ public override TypeDesc FieldType { get { - return _fieldDef.FieldType.InstantiateSignature(_instantiatedType.Instantiation, new Instantiation()); + return _fieldDef.FieldType.InstantiateSignature(_instantiatedType.Instantiation, default(Instantiation)); } } diff --git a/src/coreclr/tools/Common/TypeSystem/Common/FunctionPointerType.cs b/src/coreclr/tools/Common/TypeSystem/Common/FunctionPointerType.cs index 1328e3c040d4da..1a0c881ca376d9 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/FunctionPointerType.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/FunctionPointerType.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Text; - namespace Internal.TypeSystem { /// diff --git a/src/coreclr/tools/Common/TypeSystem/Common/GenericParameterDesc.Diagnostic.cs b/src/coreclr/tools/Common/TypeSystem/Common/GenericParameterDesc.Diagnostic.cs index 7e8df4304dfd5c..00f6772b608e94 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/GenericParameterDesc.Diagnostic.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/GenericParameterDesc.Diagnostic.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections.Generic; namespace Internal.TypeSystem { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/GenericParameterDesc.cs b/src/coreclr/tools/Common/TypeSystem/Common/GenericParameterDesc.cs index a6ca019dcabdc7..85f438e736412b 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/GenericParameterDesc.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/GenericParameterDesc.cs @@ -116,7 +116,7 @@ public virtual IEnumerable TypeConstraints { get { - return TypeDesc.EmptyTypes; + return EmptyTypes; } } diff --git a/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedMethod.cs b/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedMethod.cs index 9105c566534c7c..dce30dadc53d47 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedMethod.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedMethod.cs @@ -1,9 +1,7 @@ // 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.Text; using Internal.NativeFormat; namespace Internal.TypeSystem @@ -56,7 +54,7 @@ public override TypeDesc OwningType private TypeDesc Instantiate(TypeDesc type) { - return type.InstantiateSignature(new Instantiation(), _instantiation); + return type.InstantiateSignature(default(Instantiation), _instantiation); } public override MethodSignature Signature diff --git a/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedType.Interfaces.cs b/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedType.Interfaces.cs index 9e4cae52234701..265aef7029d4da 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedType.Interfaces.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedType.Interfaces.cs @@ -1,9 +1,6 @@ // 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 Debug = System.Diagnostics.Debug; - namespace Internal.TypeSystem { // Implementation for Instantiated type specific interface logic @@ -15,7 +12,7 @@ public sealed partial class InstantiatedType : MetadataType private DefType[] InitializeImplementedInterfaces() { // TODO Add duplicate detection - return (_implementedInterfaces = InstantiateTypeArray(_typeDef.ExplicitlyImplementedInterfaces, _instantiation, new Instantiation())); + return (_implementedInterfaces = InstantiateTypeArray(_typeDef.ExplicitlyImplementedInterfaces, _instantiation, default(Instantiation))); } /// diff --git a/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedType.MethodImpls.cs b/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedType.MethodImpls.cs index 6002edbdb23dba..c8d4f91ad5d4ca 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedType.MethodImpls.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedType.MethodImpls.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem { // Implementation of MethodImpl api surface implemented without metadata access. @@ -24,7 +22,7 @@ private MethodImplRecord[] InstantiateMethodImpls(MethodImplRecord[] uninstMetho { MethodDesc decl; - var implTypeInstantiated = uninstMethodImpls[i].Decl.OwningType.InstantiateSignature(this.Instantiation, new Instantiation()); + var implTypeInstantiated = uninstMethodImpls[i].Decl.OwningType.InstantiateSignature(this.Instantiation, default(Instantiation)); if (implTypeInstantiated is InstantiatedType) { decl = _typeDef.Context.GetMethodForInstantiatedType(uninstMethodImpls[i].Decl.GetTypicalMethodDefinition(), (InstantiatedType)implTypeInstantiated); diff --git a/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedType.cs b/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedType.cs index bed4e2388e92ae..2b9e2774324ba0 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedType.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/InstantiatedType.cs @@ -1,9 +1,7 @@ // 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.Text; using System.Diagnostics; namespace Internal.TypeSystem @@ -55,7 +53,7 @@ private MetadataType InitializeBaseType() { var uninst = _typeDef.MetadataBaseType; - return (_baseType = (uninst != null) ? (MetadataType)uninst.InstantiateSignature(_instantiation, new Instantiation()) : null); + return (_baseType = (uninst != null) ? (MetadataType)uninst.InstantiateSignature(_instantiation, default(Instantiation)) : null); } public override DefType BaseType diff --git a/src/coreclr/tools/Common/TypeSystem/Common/LayoutInt.cs b/src/coreclr/tools/Common/TypeSystem/Common/LayoutInt.cs index c794377bf19712..a2067d042252cd 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/LayoutInt.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/LayoutInt.cs @@ -26,7 +26,7 @@ public LayoutInt(int input) { if (input < 0) { - throw new ArgumentException(); + throw new ArgumentOutOfRangeException(nameof(input)); } else { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/LinqPoison.cs b/src/coreclr/tools/Common/TypeSystem/Common/LinqPoison.cs index ce2675fa2b1dce..2473b14397cab2 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/LinqPoison.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/LinqPoison.cs @@ -16,5 +16,5 @@ namespace System // "using System.Linq" from your file. Do not modify this file or // remove it from the project. // - internal class Linq { } + internal sealed class Linq { } } diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MetadataFieldLayoutAlgorithm.cs b/src/coreclr/tools/Common/TypeSystem/Common/MetadataFieldLayoutAlgorithm.cs index 5ff6417e52e411..62d40846951fb7 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MetadataFieldLayoutAlgorithm.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MetadataFieldLayoutAlgorithm.cs @@ -53,7 +53,7 @@ public override ComputedInstanceFieldLayout ComputeInstanceLayout(DefType defTyp } // Global types do not do the rest of instance field layout. - ComputedInstanceFieldLayout result = new ComputedInstanceFieldLayout(); + ComputedInstanceFieldLayout result = default(ComputedInstanceFieldLayout); result.Offsets = Array.Empty(); return result; } @@ -180,10 +180,10 @@ public override ComputedStaticFieldLayout ComputeStaticFieldLayout(DefType defTy } ComputedStaticFieldLayout result; - result.GcStatics = new StaticsBlock(); - result.NonGcStatics = new StaticsBlock(); - result.ThreadGcStatics = new StaticsBlock(); - result.ThreadNonGcStatics = new StaticsBlock(); + result.GcStatics = default(StaticsBlock); + result.NonGcStatics = default(StaticsBlock); + result.ThreadGcStatics = default(StaticsBlock); + result.ThreadNonGcStatics = default(StaticsBlock); if (numStaticFields == 0) { @@ -216,7 +216,7 @@ public override ComputedStaticFieldLayout ComputeStaticFieldLayout(DefType defTy block.Size = LayoutInt.AlignUp(block.Size, sizeAndAlignment.Alignment, context.Target); result.Offsets[index] = new FieldAndOffset(field, block.Size); - block.Size = block.Size + sizeAndAlignment.Size; + block.Size += sizeAndAlignment.Size; block.LargestAlignment = LayoutInt.Max(block.LargestAlignment, sizeAndAlignment.Alignment); @@ -228,7 +228,7 @@ public override ComputedStaticFieldLayout ComputeStaticFieldLayout(DefType defTy return result; } - private ref StaticsBlock GetStaticsBlockForField(ref ComputedStaticFieldLayout layout, FieldDesc field) + private static ref StaticsBlock GetStaticsBlockForField(ref ComputedStaticFieldLayout layout, FieldDesc field) { if (field.IsThreadStatic) { @@ -453,7 +453,6 @@ protected ComputedInstanceFieldLayout ComputeAutoFieldLayout(MetadataType type, TypeSystemContext context = type.Context; bool hasLayout = type.HasLayout(); - var layoutMetadata = type.GetClassLayout(); // Auto-layout in CoreCLR does not respect packing size. int packingSize = type.Context.Target.MaximumAlignment; @@ -793,7 +792,7 @@ private static int CalculateLog2(int size) int log2size; for (log2size = 0; size > 1; log2size++) { - size = size >> 1; + size >>= 1; } return log2size; @@ -945,7 +944,7 @@ public override ValueTypeShapeCharacteristics ComputeValueTypeShapeCharacteristi return ComputeHomogeneousAggregateCharacteristic(type); } - private ValueTypeShapeCharacteristics ComputeHomogeneousAggregateCharacteristic(DefType type) + private static ValueTypeShapeCharacteristics ComputeHomogeneousAggregateCharacteristic(DefType type) { // Use this constant to make the code below more laconic const ValueTypeShapeCharacteristics NotHA = ValueTypeShapeCharacteristics.None; diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MetadataRuntimeInterfacesAlgorithm.cs b/src/coreclr/tools/Common/TypeSystem/Common/MetadataRuntimeInterfacesAlgorithm.cs index 02b94121e52e07..fa3f125019860c 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MetadataRuntimeInterfacesAlgorithm.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MetadataRuntimeInterfacesAlgorithm.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem { @@ -37,13 +36,11 @@ public override DefType[] ComputeRuntimeInterfaces(TypeDesc _type) /// so the algorithm works by computing the uninstantiated form, and then /// specializing each interface as needed. /// - private DefType[] ComputeRuntimeInterfacesForInstantiatedType(InstantiatedType instantiatedType) + private static DefType[] ComputeRuntimeInterfacesForInstantiatedType(InstantiatedType instantiatedType) { MetadataType uninstantiatedType = (MetadataType)instantiatedType.GetTypeDefinition(); - DefType[] genericTypeDefinitionInterfaces = uninstantiatedType.RuntimeInterfaces; - - return InstantiatedType.InstantiateTypeArray(uninstantiatedType.RuntimeInterfaces, instantiatedType.Instantiation, new Instantiation()); + return InstantiatedType.InstantiateTypeArray(uninstantiatedType.RuntimeInterfaces, instantiatedType.Instantiation, default(Instantiation)); } /// @@ -58,7 +55,7 @@ private DefType[] ComputeRuntimeInterfacesForNonInstantiatedMetadataType(Metadat if (explicitInterfaces.Length == 0) return baseTypeInterfaces; - ArrayBuilder interfacesArray = new ArrayBuilder(); + ArrayBuilder interfacesArray = default(ArrayBuilder); interfacesArray.Append(baseTypeInterfaces); foreach (DefType iface in explicitInterfaces) diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MetadataType.Interfaces.cs b/src/coreclr/tools/Common/TypeSystem/Common/MetadataType.Interfaces.cs index 011a16b301a0b9..3744352723f377 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MetadataType.Interfaces.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MetadataType.Interfaces.cs @@ -1,9 +1,6 @@ // 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 Debug = System.Diagnostics.Debug; - namespace Internal.TypeSystem { // Api surface definition for interfaces that all MetadataTypes must implement diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MetadataType.MethodImpls.cs b/src/coreclr/tools/Common/TypeSystem/Common/MetadataType.MethodImpls.cs index faea42eea60ea4..17871fee717515 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MetadataType.MethodImpls.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MetadataType.MethodImpls.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem { public struct MethodImplRecord diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MetadataTypeSystemContext.cs b/src/coreclr/tools/Common/TypeSystem/Common/MetadataTypeSystemContext.cs index 97b6e62acb5920..2e04cfb85c8edf 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MetadataTypeSystemContext.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MetadataTypeSystemContext.cs @@ -1,7 +1,6 @@ // 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 Debug = System.Diagnostics.Debug; diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MetadataVirtualMethodAlgorithm.cs b/src/coreclr/tools/Common/TypeSystem/Common/MetadataVirtualMethodAlgorithm.cs index b3ef2048747b8a..8b0112184f92c1 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MetadataVirtualMethodAlgorithm.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MetadataVirtualMethodAlgorithm.cs @@ -9,7 +9,7 @@ namespace Internal.TypeSystem { public class MetadataVirtualMethodAlgorithm : VirtualMethodAlgorithm { - private class MethodDescHashtable : LockFreeReaderHashtable + private sealed class MethodDescHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(MethodDesc key) { @@ -24,13 +24,13 @@ protected override int GetValueHashCode(MethodDesc value) protected override bool CompareKeyToValue(MethodDesc key, MethodDesc value) { Debug.Assert(key.Context == value.Context); - return object.ReferenceEquals(key, value); + return ReferenceEquals(key, value); } protected override bool CompareValueToValue(MethodDesc value1, MethodDesc value2) { Debug.Assert(value1.Context == value2.Context); - return object.ReferenceEquals(value1, value2); + return ReferenceEquals(value1, value2); } protected override MethodDesc CreateValueFromKey(MethodDesc key) @@ -39,7 +39,7 @@ protected override MethodDesc CreateValueFromKey(MethodDesc key) } } - private class UnificationGroup + private sealed class UnificationGroup { private MethodDesc[] _members = MethodDesc.EmptyMethods; private int _memberCount; @@ -467,8 +467,7 @@ private static void FindBaseUnificationGroup(MetadataType currentType, Unificati MethodDesc nameSigMatchMemberMethod = FindMatchingVirtualMethodOnTypeByNameAndSigWithSlotCheck(memberMethod, currentType, reverseMethodSearch: true); if (nameSigMatchMemberMethod != null && nameSigMatchMemberMethod != memberMethod) { - if (separatedMethods == null) - separatedMethods = new MethodDescHashtable(); + separatedMethods ??= new MethodDescHashtable(); separatedMethods.AddOrGetExisting(memberMethod); } } @@ -491,8 +490,7 @@ private static void FindBaseUnificationGroup(MetadataType currentType, Unificati { unificationGroup.RemoveFromGroup(declSlot); - if (separatedMethods == null) - separatedMethods = new MethodDescHashtable(); + separatedMethods ??= new MethodDescHashtable(); separatedMethods.AddOrGetExisting(declSlot); if (unificationGroup.RequiresSlotUnification(declSlot) || implSlot.RequiresSlotUnification()) @@ -907,8 +905,6 @@ public static IEnumerable EnumAllVirtualSlots(MetadataType type) /// MethodDesc of the resolved virtual static method, null when not found (runtime lookup must be used) public static MethodDesc ResolveInterfaceMethodToStaticVirtualMethodOnType(MethodDesc interfaceMethod, MetadataType currentType) { - TypeDesc interfaceType = interfaceMethod.OwningType; - // Search for match on a per-level in the type hierarchy for (MetadataType typeToCheck = currentType; typeToCheck != null; typeToCheck = typeToCheck.MetadataBaseType) { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MethodDelegator.Diagnostic.cs b/src/coreclr/tools/Common/TypeSystem/Common/MethodDelegator.Diagnostic.cs index 4290daf473654f..dd1f7c6442fe3b 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MethodDelegator.Diagnostic.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MethodDelegator.Diagnostic.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class MethodDelegator + public partial class MethodDelegator { public override string DiagnosticName => _wrappedMethod.DiagnosticName; } diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.Diagnostic.cs b/src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.Diagnostic.cs index 99784da0a3478a..f86297f1a2a20c 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.Diagnostic.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.Diagnostic.cs @@ -1,11 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Text; - namespace Internal.TypeSystem { - partial class MethodDesc + public partial class MethodDesc { public abstract string DiagnosticName { get; } } diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.ToString.cs b/src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.ToString.cs index 485f28c809f483..e53daaab2d1ac5 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.ToString.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.ToString.cs @@ -5,7 +5,7 @@ namespace Internal.TypeSystem { - partial class MethodSignature + public partial class MethodSignature { public override string ToString() { @@ -39,7 +39,7 @@ public string ToString(bool includeReturnType) } } - partial class MethodDesc + public partial class MethodDesc { public override string ToString() { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.cs b/src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.cs index f2abb6fedfa5d7..33af7a32f68b4c 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.cs @@ -60,7 +60,7 @@ public static string GetIndexOfCustomModifierOnPointedAtTypeByParameterIndex(int } // Provide a means to create a MethodSignature which ignores EmbeddedSignature data in the MethodSignatures it is compared to - public static EmbeddedSignatureData[] EmbeddedSignatureMismatchPermittedFlag = new EmbeddedSignatureData[0]; + public static EmbeddedSignatureData[] EmbeddedSignatureMismatchPermittedFlag = Array.Empty(); public MethodSignature(MethodSignatureFlags flags, int genericParameterCount, TypeDesc returnType, TypeDesc[] parameters, EmbeddedSignatureData[] embeddedSignatureData = null) { @@ -445,8 +445,8 @@ protected virtual int ComputeHashCode() public override bool Equals(object o) { // Its only valid to compare two MethodDescs in the same context - Debug.Assert(o is not MethodDesc || object.ReferenceEquals(((MethodDesc)o).Context, this.Context)); - return object.ReferenceEquals(this, o); + Debug.Assert(o is not MethodDesc || ReferenceEquals(((MethodDesc)o).Context, this.Context)); + return ReferenceEquals(this, o); } /// diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MethodForInstantiatedType.cs b/src/coreclr/tools/Common/TypeSystem/Common/MethodForInstantiatedType.cs index 1691d5624ae386..30c3fe8a1e1889 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MethodForInstantiatedType.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MethodForInstantiatedType.cs @@ -1,8 +1,6 @@ // 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 Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem @@ -48,7 +46,7 @@ public override TypeDesc OwningType private TypeDesc Instantiate(TypeDesc type) { - return type.InstantiateSignature(_instantiatedType.Instantiation, new Instantiation()); + return type.InstantiateSignature(_instantiatedType.Instantiation, default(Instantiation)); } public override MethodSignature Signature diff --git a/src/coreclr/tools/Common/TypeSystem/Common/ModuleDesc.cs b/src/coreclr/tools/Common/TypeSystem/Common/ModuleDesc.cs index 9a7ac0a97c856a..87fa16a5819446 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/ModuleDesc.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/ModuleDesc.cs @@ -1,7 +1,6 @@ // 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; namespace Internal.TypeSystem diff --git a/src/coreclr/tools/Common/TypeSystem/Common/ParameterizedType.cs b/src/coreclr/tools/Common/TypeSystem/Common/ParameterizedType.cs index 6ec0fbd352bff5..ba0f5720c03357 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/ParameterizedType.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/ParameterizedType.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem { public abstract partial class ParameterizedType : TypeDesc diff --git a/src/coreclr/tools/Common/TypeSystem/Common/SignatureVariable.cs b/src/coreclr/tools/Common/TypeSystem/Common/SignatureVariable.cs index 0bfcf24dc7c533..4a26cb619d57bc 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/SignatureVariable.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/SignatureVariable.cs @@ -1,12 +1,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; - using Internal.NativeFormat; -using Debug = System.Diagnostics.Debug; - namespace Internal.TypeSystem { public abstract partial class SignatureVariable : TypeDesc diff --git a/src/coreclr/tools/Common/TypeSystem/Common/TargetArchitecture.cs b/src/coreclr/tools/Common/TypeSystem/Common/TargetArchitecture.cs index 160ff674f8d71a..928e3018b06725 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/TargetArchitecture.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/TargetArchitecture.cs @@ -1,9 +1,6 @@ // 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 Debug = System.Diagnostics.Debug; - namespace Internal.TypeSystem { /// diff --git a/src/coreclr/tools/Common/TypeSystem/Common/TargetDetails.ToString.cs b/src/coreclr/tools/Common/TypeSystem/Common/TargetDetails.ToString.cs index 413f789853edd1..37a065260d08a5 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/TargetDetails.ToString.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/TargetDetails.ToString.cs @@ -1,12 +1,9 @@ // 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 Debug = System.Diagnostics.Debug; - namespace Internal.TypeSystem { - partial class TargetDetails + public partial class TargetDetails { public override string ToString() { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/ThrowHelper.Common.cs b/src/coreclr/tools/Common/TypeSystem/Common/ThrowHelper.Common.cs index cf644ad14d4c95..58114db36dfc86 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/ThrowHelper.Common.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/ThrowHelper.Common.cs @@ -1,7 +1,6 @@ // 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.Text; using Debug = System.Diagnostics.Debug; diff --git a/src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.Interfaces.cs b/src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.Interfaces.cs index ce778fa590e790..5d4349ec6c14d4 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.Interfaces.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.Interfaces.cs @@ -3,7 +3,6 @@ using System; using System.Threading; -using Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.ToString.cs b/src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.ToString.cs index 4b63e28d4303ef..4995be92c54540 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.ToString.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.ToString.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class TypeDesc + public partial class TypeDesc { public override string ToString() { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.cs b/src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.cs index 905a9bbca5b2b8..b85c803cec078f 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/TypeDesc.cs @@ -24,23 +24,23 @@ public abstract partial class TypeDesc : TypeSystemEntity public override bool Equals(object o) { // Its only valid to compare two TypeDescs in the same context - Debug.Assert(o is not TypeDesc || object.ReferenceEquals(((TypeDesc)o).Context, this.Context)); - return object.ReferenceEquals(this, o); + Debug.Assert(o is not TypeDesc || ReferenceEquals(((TypeDesc)o).Context, this.Context)); + return ReferenceEquals(this, o); } #if DEBUG public static bool operator ==(TypeDesc left, TypeDesc right) { // Its only valid to compare two TypeDescs in the same context - Debug.Assert(left is null || right is null || object.ReferenceEquals(left.Context, right.Context)); - return object.ReferenceEquals(left, right); + Debug.Assert(left is null || right is null || ReferenceEquals(left.Context, right.Context)); + return ReferenceEquals(left, right); } public static bool operator !=(TypeDesc left, TypeDesc right) { // Its only valid to compare two TypeDescs in the same context - Debug.Assert(left is null || right is null || object.ReferenceEquals(left.Context, right.Context)); - return !object.ReferenceEquals(left, right); + Debug.Assert(left is null || right is null || ReferenceEquals(left.Context, right.Context)); + return !ReferenceEquals(left, right); } #endif diff --git a/src/coreclr/tools/Common/TypeSystem/Common/TypeHashingAlgorithms.cs b/src/coreclr/tools/Common/TypeSystem/Common/TypeHashingAlgorithms.cs index 5904397c4a0152..1b9692037fe94e 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/TypeHashingAlgorithms.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/TypeHashingAlgorithms.cs @@ -5,7 +5,6 @@ // Generic functions to compute the hashcode value of types // --------------------------------------------------------------------------- -using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; diff --git a/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemConstraintsHelpers.cs b/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemConstraintsHelpers.cs index d749946a72a3d0..acd8e291cebd40 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemConstraintsHelpers.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemConstraintsHelpers.cs @@ -53,7 +53,7 @@ private static bool VerifyGenericParamConstraint(InstantiationContext genericPar if (instantiationParam.IsByRefLike && (constraints & GenericConstraints.AcceptByRefLike) == 0) return false; - var instantiatedConstraints = new ArrayBuilder(); + var instantiatedConstraints = default(ArrayBuilder); GetInstantiatedConstraintsRecursive(instantiationParamContext, instantiationParam, ref instantiatedConstraints); foreach (var constraintType in genericParam.TypeConstraints) diff --git a/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemContext.cs b/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemContext.cs index fcb47f42d3c92d..af5beb8a738750 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemContext.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemContext.cs @@ -117,7 +117,7 @@ public int Rank } } - public class ArrayTypeKeyHashtable : LockFreeReaderHashtable + public sealed class ArrayTypeKeyHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(ArrayTypeKey key) { @@ -304,7 +304,7 @@ public Instantiation Instantiation } } - public class InstantiatedTypeKeyHashtable : LockFreeReaderHashtable + public sealed class InstantiatedTypeKeyHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(InstantiatedTypeKey key) { @@ -403,7 +403,7 @@ public Instantiation Instantiation } } - public class InstantiatedMethodKeyHashtable : LockFreeReaderHashtable + public sealed class InstantiatedMethodKeyHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(InstantiatedMethodKey key) { @@ -502,7 +502,7 @@ public InstantiatedType InstantiatedType } } - public class MethodForInstantiatedTypeKeyHashtable : LockFreeReaderHashtable + public sealed class MethodForInstantiatedTypeKeyHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(MethodForInstantiatedTypeKey key) { @@ -575,7 +575,7 @@ public InstantiatedType InstantiatedType } } - public class FieldForInstantiatedTypeKeyHashtable : LockFreeReaderHashtable + public sealed class FieldForInstantiatedTypeKeyHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(FieldForInstantiatedTypeKey key) { @@ -617,7 +617,7 @@ public FieldDesc GetFieldForInstantiatedType(FieldDesc fieldDef, InstantiatedTyp // // Signature variables // - private class SignatureVariableHashtable : LockFreeReaderHashtable + private sealed class SignatureVariableHashtable : LockFreeReaderHashtable { private TypeSystemContext _context; public SignatureVariableHashtable(TypeSystemContext context) diff --git a/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemException.Resources.cs b/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemException.Resources.cs index bf5a3b97b292f4..056c0aa6e5a6bb 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemException.Resources.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemException.Resources.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections.Generic; using System.Globalization; using System.Resources; using System.Reflection; @@ -11,7 +10,7 @@ // need to support accessing these strings via the ResourceManager namespace Internal.TypeSystem { - partial class TypeSystemException : Exception + public partial class TypeSystemException : Exception { private static Lazy s_stringResourceManager = new Lazy(() => new ResourceManager("Internal.TypeSystem.Strings", typeof(TypeSystemException).GetTypeInfo().Assembly)); diff --git a/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemException.cs b/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemException.cs index 39015e807d94c8..6c8cd66654af31 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemException.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemException.cs @@ -50,12 +50,12 @@ private static string GetExceptionString(ExceptionStringID id, string[] args) { if (formatString != null) { - return String.Format(formatString, (object[])args); + return string.Format(formatString, (object[])args); } } catch {} - - return "[TEMPORARY EXCEPTION MESSAGE] " + id.ToString() + ": " + String.Join(", ", args); + + return "[TEMPORARY EXCEPTION MESSAGE] " + id.ToString() + ": " + string.Join(", ", args); } /// diff --git a/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemHelpers.cs b/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemHelpers.cs index 7c841444f15b0a..749136b698b209 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemHelpers.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemHelpers.cs @@ -363,7 +363,7 @@ public static bool ContainsSignatureVariables(this TypeDesc thisType, bool treat // It is generally a bug to have instantiations over generic parameters // in the system. Typical instantiations are represented as instantiations // over own formals - so these should be signature variables instead. - throw new ArgumentException(); + throw new InvalidOperationException(); default: Debug.Assert(thisType is DefType); diff --git a/src/coreclr/tools/Common/TypeSystem/Common/UniversalCanonLayoutAlgorithm.cs b/src/coreclr/tools/Common/TypeSystem/Common/UniversalCanonLayoutAlgorithm.cs index 196aef8c7e41c6..36987f950946fd 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/UniversalCanonLayoutAlgorithm.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/UniversalCanonLayoutAlgorithm.cs @@ -3,10 +3,6 @@ using System; -using Internal.NativeFormat; - -using Debug = System.Diagnostics.Debug; - namespace Internal.TypeSystem { public class UniversalCanonLayoutAlgorithm : FieldLayoutAlgorithm diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameFormatter.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameFormatter.cs index 94a9caa2ad1ffb..67ee949b835402 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameFormatter.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameFormatter.cs @@ -165,7 +165,7 @@ protected override IAssemblyDesc AppendNameForNestedType(StringBuilder sb, DefTy } private static char[] s_escapedChars = new char[] { ',', '=', '"', ']', '[', '*', '&', '+', '\\' }; - private void AppendEscapedIdentifier(StringBuilder sb, string identifier) + private static void AppendEscapedIdentifier(StringBuilder sb, string identifier) { if (identifier.IndexOfAny(s_escapedChars) < 0) { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameParser.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameParser.cs index 1b901f5e623ed2..8089f6585d4980 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameParser.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/CustomAttributeTypeNameParser.cs @@ -78,7 +78,7 @@ public static TypeDesc GetTypeByCustomAttributeTypeName(this ModuleDesc module, if (typeDef == null) return null; - ArrayBuilder genericArgs = new ArrayBuilder(); + ArrayBuilder genericArgs = default(ArrayBuilder); // Followed by generic instantiation parameters (but check for the array case) if (ch < nameEnd && ch.Current == '[' && (ch + 1) < nameEnd && (ch + 1).Current != ']' && (ch + 1).Current != ',') @@ -184,7 +184,9 @@ public static TypeDesc GetTypeByCustomAttributeTypeName(this ModuleDesc module, if (ch.Current == '&') { loadedType = loadedType.MakeByRefType(); +#pragma warning disable IDE0059 // Unnecessary assignment of a value ch++; +#pragma warning restore IDE0059 // Unnecessary assignment of a value } } @@ -232,7 +234,7 @@ public static MetadataType ResolveCustomAttributeTypeDefinitionName(string name, { if (throwIfNotFound) ThrowHelper.ThrowTypeLoadException(typeName.ToString(), outerType.Module); - + return null; } } @@ -374,7 +376,7 @@ private static StringIterator End(this string s) return new StringIterator(s, s.Length); } - struct StringIterator + private struct StringIterator : IEquatable { private string _string; private int _index; @@ -396,46 +398,46 @@ public StringIterator(string s, int index) public static string Substring(StringIterator it1, StringIterator it2) { - Debug.Assert(Object.ReferenceEquals(it1._string, it2._string)); + Debug.Assert(ReferenceEquals(it1._string, it2._string)); return it1._string.Substring(it1._index, it2._index - it1._index); } - public static StringIterator operator++(StringIterator it) + public static StringIterator operator ++(StringIterator it) { return new StringIterator(it._string, ++it._index); } public static bool operator <(StringIterator it1, StringIterator it2) { - Debug.Assert(Object.ReferenceEquals(it1._string, it2._string)); + Debug.Assert(ReferenceEquals(it1._string, it2._string)); return it1._index < it2._index; } public static bool operator >(StringIterator it1, StringIterator it2) { - Debug.Assert(Object.ReferenceEquals(it1._string, it2._string)); + Debug.Assert(ReferenceEquals(it1._string, it2._string)); return it1._index > it2._index; } - public static StringIterator operator+(StringIterator it, int val) + public static StringIterator operator +(StringIterator it, int val) { return new StringIterator(it._string, it._index + val); } - public static StringIterator operator-(StringIterator it, int val) + public static StringIterator operator -(StringIterator it, int val) { return new StringIterator(it._string, it._index - val); } - public static bool operator==(StringIterator it1, StringIterator it2) + public static bool operator ==(StringIterator it1, StringIterator it2) { - Debug.Assert(Object.ReferenceEquals(it1._string, it2._string)); + Debug.Assert(ReferenceEquals(it1._string, it2._string)); return it1._index == it2._index; } public static bool operator !=(StringIterator it1, StringIterator it2) { - Debug.Assert(Object.ReferenceEquals(it1._string, it2._string)); + Debug.Assert(ReferenceEquals(it1._string, it2._string)); return it1._index != it2._index; } @@ -448,6 +450,11 @@ public override int GetHashCode() { throw new NotImplementedException(); } + + public bool Equals(StringIterator other) + { + throw new NotImplementedException(); + } } #endregion } diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/DebugNameFormatter.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/DebugNameFormatter.cs index 607287e45f6dca..8c6c3a00fa7cb9 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/DebugNameFormatter.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/DebugNameFormatter.cs @@ -4,8 +4,6 @@ using System; using System.Text; -using Debug = System.Diagnostics.Debug; - namespace Internal.TypeSystem { public partial class DebugNameFormatter : TypeNameFormatter diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/ExceptionTypeNameFormatter.Metadata.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/ExceptionTypeNameFormatter.Metadata.cs index 92d3319a0c15f9..79a6da8f59a456 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/ExceptionTypeNameFormatter.Metadata.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/ExceptionTypeNameFormatter.Metadata.cs @@ -4,14 +4,14 @@ namespace Internal.TypeSystem { // Type name formatting functionality that relies on metadata. - partial class ExceptionTypeNameFormatter + public partial class ExceptionTypeNameFormatter { - private string GetTypeName(DefType type) + private static string GetTypeName(DefType type) { return type.Name; } - private string GetTypeNamespace(DefType type) + private static string GetTypeNamespace(DefType type) { return type.Namespace; } diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.Algorithm.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.Algorithm.cs index b4fc577fb7bb6a..eca01c4b3a4587 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.Algorithm.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.Algorithm.cs @@ -5,7 +5,7 @@ namespace Internal.TypeSystem { - partial struct GCPointerMap + public partial struct GCPointerMap { /// /// Computes the GC pointer map for the instance fields of . diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.cs index 7f2d2195f3c8b9..0e2bacf49bfe80 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/GCPointerMap.cs @@ -129,7 +129,7 @@ public override string ToString() sb.Append(bit ? '1' : '0'); return sb.ToString(); } - + public int CompareTo(GCPointerMap other) { if (_numCells != other._numCells) diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtable.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtable.cs index 77e777d3c0d502..ad43bf9090434a 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtable.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtable.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; -using System.Threading.Tasks; using Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem @@ -245,7 +244,7 @@ private TValue WaitForSentinelInHashtableToDisappear(TValue[] hashtable, int tab if (sentinel == null) return null; - var sw = new SpinWait(); + var sw = default(SpinWait); while (true) { TValue value = Volatile.Read(ref hashtable[tableIndex]); @@ -594,7 +593,7 @@ public bool Contains(TKey key) public TValue GetValueIfExists(TValue value) { if (value == null) - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(value)); TValue[] hashTableLocal = GetCurrentHashtable(); Debug.Assert(hashTableLocal.Length > 0); diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/TypeNameFormatter.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/TypeNameFormatter.cs index 11ad86d7874e70..4dc7e6020d9732 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/TypeNameFormatter.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/TypeNameFormatter.cs @@ -1,7 +1,6 @@ // 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.Text; using Debug = System.Diagnostics.Debug; diff --git a/src/coreclr/tools/Common/TypeSystem/Common/WellKnownType.cs b/src/coreclr/tools/Common/TypeSystem/Common/WellKnownType.cs index b16257f21697e2..c726b3f719f38c 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/WellKnownType.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/WellKnownType.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem { // The following enum is required for interop with the VS Debugger diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/CachingMetadataStringDecoder.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/CachingMetadataStringDecoder.cs index 7a1ccfadb8bc13..cd0e77453ccdc3 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/CachingMetadataStringDecoder.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/CachingMetadataStringDecoder.cs @@ -1,9 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Reflection.Metadata; -using System.Runtime.CompilerServices; using Debug = System.Diagnostics.Debug; using Internal.NativeFormat; @@ -173,7 +171,7 @@ public string Lookup(string s) return Add(hashCode, s); } - public unsafe override string GetString(byte* bytes, int byteCount) + public override unsafe string GetString(byte* bytes, int byteCount) { bool isAscii; int hashCode = TypeHashingAlgorithms.ComputeASCIINameHashCode(bytes, byteCount, out isAscii); diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaAssembly.Symbols.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaAssembly.Symbols.cs index 0ca7305763cae1..90ad54f4456e66 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaAssembly.Symbols.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaAssembly.Symbols.cs @@ -7,7 +7,7 @@ namespace Internal.TypeSystem.Ecma { // Pluggable file that adds PDB handling functionality to EcmaAssembly - partial class EcmaAssembly + public partial class EcmaAssembly { internal EcmaAssembly(TypeSystemContext context, PEReader peReader, MetadataReader metadataReader, PdbSymbolReader pdbReader, IModuleResolver customModuleResolver) : base(context, peReader, metadataReader, containingAssembly: null, pdbReader, customModuleResolver) diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.CodeGen.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.CodeGen.cs index 2f76289e4ab2e6..963ee08762c275 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.CodeGen.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.CodeGen.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem.Ecma { - partial class EcmaField + public partial class EcmaField { public override bool IsIntrinsic { diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.Serialization.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.Serialization.cs index 52a7a474dbf008..f2767d459156d9 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.Serialization.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.Serialization.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem.Ecma { - partial class EcmaField + public partial class EcmaField { public override bool IsNotSerialized { diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.Sorting.cs index 9151b571936b7a..5b3dd3200f1ba4 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaField.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.TypeSystem.Ecma { // Functionality related to deterministic ordering of types and members - partial class EcmaField + public partial class EcmaField { protected internal override int ClassCode => 44626835; diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaGenericParameter.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaGenericParameter.Sorting.cs index cc74c3ba5e6c45..730abcce7f0b7d 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaGenericParameter.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaGenericParameter.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.TypeSystem.Ecma { // Functionality related to deterministic ordering of types - partial class EcmaGenericParameter + public partial class EcmaGenericParameter { protected internal override int ClassCode => -1548417824; diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaGenericParameter.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaGenericParameter.cs index 7451c0a9fb432c..0ecf1c409be814 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaGenericParameter.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaGenericParameter.cs @@ -1,10 +1,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; using System.Collections.Generic; using System.Reflection.Metadata; -using Internal.NativeFormat; using Debug = System.Diagnostics.Debug; using GenericParameterAttributes = System.Reflection.GenericParameterAttributes; @@ -108,7 +106,7 @@ public override GenericConstraints Constraints return (GenericConstraints)(parameter.Attributes & GenericParameterAttributes.SpecialConstraintMask); } } - + public override IEnumerable TypeConstraints { get @@ -119,7 +117,7 @@ public override IEnumerable TypeConstraints GenericParameterConstraintHandleCollection constraintHandles = parameter.GetConstraints(); if (constraintHandles.Count == 0) - return TypeDesc.EmptyTypes; + return EmptyTypes; TypeDesc[] constraintTypes = new TypeDesc[constraintHandles.Count]; diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaMethod.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaMethod.Sorting.cs index 09ea200aa065a4..3ad587d76bb6ac 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaMethod.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaMethod.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.TypeSystem.Ecma { // Functionality related to deterministic ordering of types - partial class EcmaMethod + public partial class EcmaMethod { protected internal override int ClassCode => 1419431046; diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaMethod.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaMethod.cs index 182a87c56765f4..63eb97c3726f2e 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaMethod.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaMethod.cs @@ -362,7 +362,7 @@ public override bool IsDefaultConstructor get { MethodAttributes attributes = Attributes; - return attributes.IsRuntimeSpecialName() + return attributes.IsRuntimeSpecialName() && attributes.IsPublic() && Signature.Length == 0 && Name == ".ctor" @@ -546,7 +546,7 @@ private MethodImportAttributes GetImportAttributesFromBestFitMappingAttribute(Cu public override ParameterMetadata[] GetParameterMetadata() { MetadataReader metadataReader = MetadataReader; - + // Spot check the enums match Debug.Assert((int)ParameterAttributes.In == (int)ParameterMetadataAttributes.In); Debug.Assert((int)ParameterAttributes.Out == (int)ParameterMetadataAttributes.Out); diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.Sorting.cs index a86c4f030d5395..86ec5968907381 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.Sorting.cs @@ -7,7 +7,7 @@ namespace Internal.TypeSystem.Ecma { - partial class EcmaModule + public partial class EcmaModule { public int CompareTo(EcmaModule other) { diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.Symbols.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.Symbols.cs index 821f8643ea3498..30d0d180b9ec7b 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.Symbols.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.Symbols.cs @@ -7,7 +7,7 @@ namespace Internal.TypeSystem.Ecma { // Pluggable file that adds PDB handling functionality to EcmaModule - partial class EcmaModule + public partial class EcmaModule { public PdbSymbolReader PdbReader { diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.cs index 35634b46d1e699..7140a8b0333fc8 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.cs @@ -51,7 +51,7 @@ public object Object } } - internal class EcmaObjectLookupHashtable : LockFreeReaderHashtable + internal sealed class EcmaObjectLookupHashtable : LockFreeReaderHashtable { private EcmaModule _module; @@ -77,7 +77,7 @@ protected override bool CompareKeyToValue(EntityHandle key, IEntityHandleObject protected override bool CompareValueToValue(IEntityHandleObject value1, IEntityHandleObject value2) { - if (Object.ReferenceEquals(value1, value2)) + if (ReferenceEquals(value1, value2)) return true; else return value1.Handle.Equals(value2.Handle); @@ -177,7 +177,7 @@ private object ResolveModuleReference(ModuleReferenceHandle handle) } private LockFreeReaderHashtable _resolvedTokens; - IModuleResolver _moduleResolver; + private IModuleResolver _moduleResolver; internal EcmaModule(TypeSystemContext context, PEReader peReader, MetadataReader metadataReader, IAssemblyDesc containingAssembly, IModuleResolver customModuleResolver) : base(context, containingAssembly) @@ -185,7 +185,7 @@ internal EcmaModule(TypeSystemContext context, PEReader peReader, MetadataReader _peReader = peReader; _metadataReader = metadataReader; _resolvedTokens = new EcmaObjectLookupHashtable(this); - _moduleResolver = customModuleResolver != null ? customModuleResolver : context; + _moduleResolver = customModuleResolver ?? context; } public static EcmaModule Create(TypeSystemContext context, PEReader peReader, IAssemblyDesc containingAssembly, IModuleResolver customModuleResolver = null) @@ -208,7 +208,7 @@ private static MetadataReader CreateMetadataReader(TypeSystemContext context, PE var stringDecoderProvider = context as IMetadataStringDecoderProvider; MetadataReader metadataReader = peReader.GetMetadataReader(MetadataReaderOptions.None /* MetadataReaderOptions.ApplyWindowsRuntimeProjections */, - (stringDecoderProvider != null) ? stringDecoderProvider.GetMetadataStringDecoder() : null); + stringDecoderProvider?.GetMetadataStringDecoder()); return metadataReader; } @@ -353,7 +353,7 @@ public TypeDesc GetType(EntityHandle handle) { TypeDesc type = GetObject(handle, NotFoundBehavior.Throw) as TypeDesc; if (type == null) - ThrowHelper.ThrowBadImageFormatException($"type expected for handle {handle.ToString()}"); + ThrowHelper.ThrowBadImageFormatException($"type expected for handle {handle}"); return type; } @@ -361,7 +361,7 @@ public MethodDesc GetMethod(EntityHandle handle) { MethodDesc method = GetObject(handle, NotFoundBehavior.Throw) as MethodDesc; if (method == null) - ThrowHelper.ThrowBadImageFormatException($"method expected for handle {handle.ToString()}"); + ThrowHelper.ThrowBadImageFormatException($"method expected for handle {handle}"); return method; } @@ -369,11 +369,11 @@ public FieldDesc GetField(EntityHandle handle) { FieldDesc field = GetObject(handle, NotFoundBehavior.Throw) as FieldDesc; if (field == null) - ThrowHelper.ThrowBadImageFormatException($"field expected for handle {handle.ToString()}"); + ThrowHelper.ThrowBadImageFormatException($"field expected for handle {handle}"); return field; } - public Object GetObject(EntityHandle handle, NotFoundBehavior notFoundBehavior = NotFoundBehavior.Throw) + public object GetObject(EntityHandle handle, NotFoundBehavior notFoundBehavior = NotFoundBehavior.Throw) { IEntityHandleObject obj = _resolvedTokens.GetOrCreateValue(handle); if (obj is EcmaObjectLookupWrapper) @@ -394,7 +394,7 @@ public Object GetObject(EntityHandle handle, NotFoundBehavior notFoundBehavior = } } - private Object ResolveMethodSpecification(MethodSpecificationHandle handle) + private object ResolveMethodSpecification(MethodSpecificationHandle handle) { MethodSpecification methodSpecification = _metadataReader.GetMethodSpecification(handle); @@ -404,7 +404,7 @@ private Object ResolveMethodSpecification(MethodSpecificationHandle handle) MethodDesc methodDef = resolvedMethod as MethodDesc; if (methodDef == null) - ThrowHelper.ThrowBadImageFormatException($"method expected for handle {handle.ToString()}"); + ThrowHelper.ThrowBadImageFormatException($"method expected for handle {handle}"); BlobReader signatureReader = _metadataReader.GetBlobReader(methodSpecification.Signature); EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader, NotFoundBehavior.ReturnResolutionFailure); @@ -417,7 +417,7 @@ private Object ResolveMethodSpecification(MethodSpecificationHandle handle) return Context.GetInstantiatedMethod(methodDef, new Instantiation(instantiation)); } - private Object ResolveStandaloneSignature(StandaloneSignatureHandle handle) + private object ResolveStandaloneSignature(StandaloneSignatureHandle handle) { StandaloneSignature signature = _metadataReader.GetStandaloneSignature(handle); BlobReader signatureReader = _metadataReader.GetBlobReader(signature.Signature); @@ -429,7 +429,7 @@ private Object ResolveStandaloneSignature(StandaloneSignatureHandle handle) return methodSig; } - private Object ResolveTypeSpecification(TypeSpecificationHandle handle) + private object ResolveTypeSpecification(TypeSpecificationHandle handle) { TypeSpecification typeSpecification = _metadataReader.GetTypeSpecification(handle); @@ -443,11 +443,11 @@ private Object ResolveTypeSpecification(TypeSpecificationHandle handle) return parsedType; } - private Object ResolveMemberReference(MemberReferenceHandle handle) + private object ResolveMemberReference(MemberReferenceHandle handle) { MemberReference memberReference = _metadataReader.GetMemberReference(handle); - Object parent = GetObject(memberReference.Parent, NotFoundBehavior.ReturnResolutionFailure); + object parent = GetObject(memberReference.Parent, NotFoundBehavior.ReturnResolutionFailure); if (parent is ResolutionFailure) return parent; @@ -533,11 +533,11 @@ private Object ResolveMemberReference(MemberReferenceHandle handle) return null; } - private Object ResolveTypeReference(TypeReferenceHandle handle) + private object ResolveTypeReference(TypeReferenceHandle handle) { TypeReference typeReference = _metadataReader.GetTypeReference(handle); - Object resolutionScope = GetObject(typeReference.ResolutionScope, NotFoundBehavior.ReturnResolutionFailure); + object resolutionScope = GetObject(typeReference.ResolutionScope, NotFoundBehavior.ReturnResolutionFailure); if (resolutionScope is ResolutionFailure) { return resolutionScope; @@ -564,7 +564,7 @@ private Object ResolveTypeReference(TypeReferenceHandle handle) throw new NotImplementedException(); } - private Object ResolveAssemblyReference(AssemblyReferenceHandle handle) + private object ResolveAssemblyReference(AssemblyReferenceHandle handle) { AssemblyReference assemblyReference = _metadataReader.GetAssemblyReference(handle); @@ -592,22 +592,20 @@ private Object ResolveAssemblyReference(AssemblyReferenceHandle handle) return assembly; } - private Object ResolveExportedType(ExportedTypeHandle handle) + private object ResolveExportedType(ExportedTypeHandle handle) { ExportedType exportedType = _metadataReader.GetExportedType(handle); var implementation = GetObject(exportedType.Implementation, NotFoundBehavior.ReturnResolutionFailure); - if (implementation is ModuleDesc) + if (implementation is ModuleDesc module) { - var module = (ModuleDesc)implementation; string nameSpace = _metadataReader.GetString(exportedType.Namespace); string name = _metadataReader.GetString(exportedType.Name); return module.GetType(nameSpace, name, NotFoundBehavior.ReturnResolutionFailure); } else - if (implementation is MetadataType) + if (implementation is MetadataType type) { - var type = (MetadataType)implementation; string name = _metadataReader.GetString(exportedType.Name); var nestedType = type.GetNestedType(name); if (nestedType == null) diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureEncoder.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureEncoder.cs index 68110e076d3cea..275cbcb6058d44 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureEncoder.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureEncoder.cs @@ -3,12 +3,9 @@ using System; using System.Collections.Immutable; -using System.Reflection; using System.Reflection.Metadata.Ecma335; using System.Reflection.Metadata; -using Internal.TypeSystem; - namespace Internal.TypeSystem.Ecma { public interface IEntityHandleProvider @@ -20,7 +17,7 @@ public interface IEntityHandleProvider public class EcmaSignatureEncoder where TEntityHandleProvider : IEntityHandleProvider { - TEntityHandleProvider _entityHandleProvider; + private TEntityHandleProvider _entityHandleProvider; public EcmaSignatureEncoder(TEntityHandleProvider entityHandleProvider) { diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureParser.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureParser.cs index f2530ec8b19d7c..4df655766af0ee 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureParser.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureParser.cs @@ -3,11 +3,8 @@ using System; using System.Reflection.Metadata; -using System.Runtime.InteropServices; using System.Diagnostics; using System.Text; - -using Internal.TypeSystem; using System.Collections.Generic; namespace Internal.TypeSystem.Ecma @@ -49,10 +46,9 @@ public EcmaSignatureParser(EcmaModule ecmaModule, BlobReader reader, NotFoundBeh _resolutionFailure = null; } - void SetResolutionFailure(ResolutionFailure failure) + private void SetResolutionFailure(ResolutionFailure failure) { - if (_resolutionFailure == null) - _resolutionFailure = failure; + _resolutionFailure ??= failure; } public ResolutionFailure ResolutionFailure => _resolutionFailure; @@ -100,10 +96,7 @@ private TypeDesc ParseType(SignatureTypeCode typeCode) _indexStack.Push(0); } TypeDesc result = ParseTypeImpl(typeCode); - if (_indexStack != null) - { - _indexStack.Pop(); - } + _indexStack?.Pop(); return result; } @@ -270,10 +263,7 @@ private SignatureTypeCode ParseTypeCode(bool skipPinned = true) _indexStack.Push(0); } SignatureTypeCode result = ParseTypeCodeImpl(skipPinned); - if (_indexStack != null) - { - _indexStack.Pop(); - } + _indexStack?.Pop(); return result; } @@ -286,20 +276,14 @@ private SignatureTypeCode ParseTypeCodeImpl(bool skipPinned = true) if (typeCode == SignatureTypeCode.RequiredModifier) { EntityHandle typeHandle = _reader.ReadTypeHandle(); - if (_embeddedSignatureDataList != null) - { - _embeddedSignatureDataList.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack), kind = EmbeddedSignatureDataKind.RequiredCustomModifier, type = ResolveHandle(typeHandle) }); - } + _embeddedSignatureDataList?.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack), kind = EmbeddedSignatureDataKind.RequiredCustomModifier, type = ResolveHandle(typeHandle) }); continue; } if (typeCode == SignatureTypeCode.OptionalModifier) { EntityHandle typeHandle = _reader.ReadTypeHandle(); - if (_embeddedSignatureDataList != null) - { - _embeddedSignatureDataList.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack), kind = EmbeddedSignatureDataKind.OptionalCustomModifier, type = ResolveHandle(typeHandle) }); - } + _embeddedSignatureDataList?.Add(new EmbeddedSignatureData { index = string.Join(".", _indexStack), kind = EmbeddedSignatureDataKind.OptionalCustomModifier, type = ResolveHandle(typeHandle) }); continue; } @@ -323,10 +307,7 @@ public TypeDesc ParseType() _indexStack.Push(0); } TypeDesc result = ParseTypeImpl(); - if (_indexStack != null) - { - _indexStack.Pop(); - } + _indexStack?.Pop(); return result; } @@ -370,10 +351,7 @@ private MethodSignature ParseMethodSignatureInternal(bool skipEmbeddedSignatureD _indexStack.Push(0); } MethodSignature result = ParseMethodSignatureImpl(skipEmbeddedSignatureData); - if (_indexStack != null) - { - _indexStack.Pop(); - } + _indexStack?.Pop(); return result; } diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureTranslator.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureTranslator.cs index dd7e01fec9e4af..4ef47c3fe457a0 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureTranslator.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaSignatureTranslator.cs @@ -9,10 +9,10 @@ namespace Internal.TypeSystem.Ecma { public struct EcmaSignatureTranslator { - BlobReader _input; - BlobBuilder _output; + private BlobReader _input; + private BlobBuilder _output; - Func _getAlternateStreamToken; + private Func _getAlternateStreamToken; public EcmaSignatureTranslator(BlobReader input, BlobBuilder output, Func getAlternateStreamToken) { @@ -23,31 +23,31 @@ public EcmaSignatureTranslator(BlobReader input, BlobBuilder output, Func foundRecords = new ArrayBuilder(); + ArrayBuilder foundRecords = default(ArrayBuilder); foreach (var methodImplHandle in _typeDefinition.GetMethodImplementations()) { @@ -79,7 +74,7 @@ public override MethodImplRecord[] FindMethodsImplWithMatchingDeclName(string de protected override MethodImplRecord[] ComputeVirtualMethodImplsForType() { - ArrayBuilder records = new ArrayBuilder(); + ArrayBuilder records = default(ArrayBuilder); MetadataReader metadataReader = _module.MetadataReader; @@ -90,8 +85,8 @@ protected override MethodImplRecord[] ComputeVirtualMethodImplsForType() EntityHandle methodDeclCheckHandle = methodImpl.MethodDeclaration; HandleKind methodDeclHandleKind = methodDeclCheckHandle.Kind; - // We want to check that the type is not an interface matches before actually getting the MethodDesc. - // For MethodSpecifications we need to dereference that handle to the underlying member reference to + // We want to check that the type is not an interface matches before actually getting the MethodDesc. + // For MethodSpecifications we need to dereference that handle to the underlying member reference to // look at the owning type. if (methodDeclHandleKind == HandleKind.MethodSpecification) { diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.Serialization.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.Serialization.cs index 0f826f68936bc6..9cfd879b023ac2 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.Serialization.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.Serialization.cs @@ -5,7 +5,7 @@ namespace Internal.TypeSystem.Ecma { - partial class EcmaType + public partial class EcmaType { public override bool IsSerializable { diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.Sorting.cs index 2f0aefcab743bc..f8443196adf2d6 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.TypeSystem.Ecma { // Functionality related to deterministic ordering of types - partial class EcmaType + public partial class EcmaType { protected internal override int ClassCode => 1340416537; diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.cs index fe041b71b6ae2b..245c51458a453a 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.cs @@ -7,7 +7,6 @@ using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; -using Debug = System.Diagnostics.Debug; using Internal.NativeFormat; @@ -106,7 +105,7 @@ private void ComputeGenericParameters() } else { - _genericParameters = TypeDesc.EmptyTypes; + _genericParameters = EmptyTypes; } } diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/IEcmaModule.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/IEcmaModule.cs index 816906f7cb9add..4aee7b4ac009aa 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/IEcmaModule.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/IEcmaModule.cs @@ -1,12 +1,7 @@ // 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.Reflection; using System.Reflection.Metadata; -using System.Reflection.Metadata.Ecma335; -using System.Reflection.PortableExecutable; using Internal.TypeSystem.Ecma; @@ -48,7 +43,7 @@ public interface IEcmaModule { MetadataReader MetadataReader { get; } TypeDesc GetType(EntityHandle handle); - Object GetObject(EntityHandle handle, NotFoundBehavior notFoundBehavior = NotFoundBehavior.Throw); + object GetObject(EntityHandle handle, NotFoundBehavior notFoundBehavior = NotFoundBehavior.Throw); int CompareTo(IEcmaModule other); int ModuleTypeSort { get; } diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/IMetadataStringDecoderProvider.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/IMetadataStringDecoderProvider.cs index b37bec733a588f..2dccf664c5f173 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/IMetadataStringDecoderProvider.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/IMetadataStringDecoderProvider.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Reflection.Metadata; namespace Internal.TypeSystem.Ecma diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/MetadataExtensions.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/MetadataExtensions.cs index d021fb01be2be1..640a70efa7ce67 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/MetadataExtensions.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/MetadataExtensions.cs @@ -122,7 +122,7 @@ public static CustomAttributeHandle GetCustomAttributeHandle(this MetadataReader return default(CustomAttributeHandle); } - private static bool IsEqualCustomAttributeName(CustomAttributeHandle attributeHandle, MetadataReader metadataReader, + private static bool IsEqualCustomAttributeName(CustomAttributeHandle attributeHandle, MetadataReader metadataReader, string attributeNamespace, string attributeName) { StringHandle namespaceHandle, nameHandle; @@ -136,8 +136,8 @@ private static bool IsEqualCustomAttributeName(CustomAttributeHandle attributeHa public static bool GetAttributeNamespaceAndName(this MetadataReader metadataReader, CustomAttributeHandle attributeHandle, out StringHandle namespaceHandle, out StringHandle nameHandle) { - EntityHandle attributeType, attributeCtor; - if (!GetAttributeTypeAndConstructor(metadataReader, attributeHandle, out attributeType, out attributeCtor)) + EntityHandle attributeType; + if (!GetAttributeTypeAndConstructor(metadataReader, attributeHandle, out attributeType, out _)) { namespaceHandle = default(StringHandle); nameHandle = default(StringHandle); @@ -211,7 +211,7 @@ public static bool GetAttributeTypeNamespaceAndName(this MetadataReader metadata public static PInvokeFlags GetDelegatePInvokeFlags(this EcmaType type) { PInvokeFlags flags = new PInvokeFlags(PInvokeAttributes.PreserveSig); - + if (!type.IsDelegate) { return flags; diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/SymbolReader/PortablePdbSymbolReader.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/SymbolReader/PortablePdbSymbolReader.cs index 4baae1590cff78..17cee6d38cc8c3 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/SymbolReader/PortablePdbSymbolReader.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/SymbolReader/PortablePdbSymbolReader.cs @@ -1,7 +1,6 @@ // 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.IO; using System.IO.MemoryMappedFiles; @@ -105,8 +104,7 @@ private PortablePdbSymbolReader(MetadataReader reader, MemoryMappedViewAccessor public override void Dispose() { - if (_mappedViewAccessor != null) - _mappedViewAccessor.Dispose(); + _mappedViewAccessor?.Dispose(); } public override int GetStateMachineKickoffMethod(int methodToken) diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/SymbolReader/UnmanagedPdbSymbolReader.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/SymbolReader/UnmanagedPdbSymbolReader.cs index d4b6f3686be999..40979241487ab0 100644 --- a/src/coreclr/tools/Common/TypeSystem/Ecma/SymbolReader/UnmanagedPdbSymbolReader.cs +++ b/src/coreclr/tools/Common/TypeSystem/Ecma/SymbolReader/UnmanagedPdbSymbolReader.cs @@ -8,7 +8,6 @@ using System.Runtime.InteropServices; using System.Collections; using System.Diagnostics; -using System.Runtime.InteropServices.ComTypes; using System.Runtime.CompilerServices; #if !DISABLE_UNMANAGED_PDB_SYMBOLS @@ -48,7 +47,7 @@ private static int CLRCreateInstance(ref Guid clsid, ref Guid riid, out ClrMetaH static extern int CLRCreateInstance(ref Guid clsid, ref Guid riid, out IntPtr ptr); } - interface ICLRMetaHost + private interface ICLRMetaHost { public static readonly Guid IID = new Guid("d332db9e-b9b3-4125-8207-a14884f53216"); @@ -78,7 +77,7 @@ protected override object CreateObject(IntPtr externalComObject, CreateObjectFla protected override void ReleaseObjects(IEnumerable objects) => throw new NotImplementedException(); - public unsafe class ClrMetaHostRcw : ICLRMetaHost, IDisposable + public sealed unsafe class ClrMetaHostRcw : ICLRMetaHost, IDisposable { private bool _disposed; private readonly IntPtr _inst; @@ -125,7 +124,7 @@ private void DisposeInternal() } } - interface ICLRRuntimeInfo + private interface ICLRRuntimeInfo { int GetInterface(ref Guid rclsid, ref Guid riid, out MetaDataDispenserWrapperCache.MetaDataDispenserRcw? ppUnk); @@ -134,7 +133,7 @@ interface ICLRRuntimeInfo // Don't need any other methods. } - private class CLRRuntimeInfoWrapperCache : ComWrappers + private sealed class CLRRuntimeInfoWrapperCache : ComWrappers { public static readonly CLRRuntimeInfoWrapperCache Instance = new CLRRuntimeInfoWrapperCache(); private CLRRuntimeInfoWrapperCache() { } @@ -159,7 +158,7 @@ private enum VtableOffset BindAsLegacyV2Runtime = 13 } - private bool _disposed = false; + private bool _disposed; public int GetInterface(ref Guid rclsid, ref Guid riid, out MetaDataDispenserWrapperCache.MetaDataDispenserRcw? ppUnk) { @@ -230,7 +229,7 @@ protected override object CreateObject(IntPtr externalComObject, CreateObjectFla public sealed unsafe record MetaDataDispenserRcw(IntPtr Inst) : IMetaDataDispenser, IDisposable { - private bool _disposed = false; + private bool _disposed; /// /// is simply a boxed IntPtr, because we don't need an RCW. @@ -293,9 +292,9 @@ private CoCreateWrapperCache() { } } protected override void ReleaseObjects(IEnumerable objects) => throw new NotImplementedException(); - public unsafe record SymUnmanagedBinderRcw(IntPtr Inst) : ISymUnmanagedBinder + public sealed unsafe record SymUnmanagedBinderRcw(IntPtr Inst) : ISymUnmanagedBinder { - private bool _disposed = false; + private bool _disposed; public int GetReaderForFile(MetadataImportRcw metadataImporter, string fileName, string searchPath, out SymUnmanagedReaderWrapperCache.SymUnmanagedReaderRcw? reader) { @@ -343,7 +342,7 @@ private void DisposeInternal() /// private sealed record MetadataImportRcw(IntPtr Ptr) : IDisposable { - private bool _disposed = false; + private bool _disposed; public void Dispose() { @@ -363,7 +362,7 @@ private void DisposeInternal() } } - interface ISymUnmanagedReader + private interface ISymUnmanagedReader { int GetMethod(int methodToken, out ISymUnmanagedMethod? method); // No more members are used @@ -383,7 +382,7 @@ private sealed class SymUnmanagedNamespaceWrapperCache : ComWrappers public sealed unsafe record SymUnmanagedNamespaceRcw(IntPtr Inst) : ISymUnmanagedNamespace { - private bool _disposed = false; + private bool _disposed; public int GetName(int bufferLength, out int count, char[] name) { @@ -418,7 +417,7 @@ public int GetNamespaces(int bufferLength, out int count, ISymUnmanagedNamespace { for (int i = 0; i < count; i++) { - namespaces[i] = (SymUnmanagedNamespaceWrapperCache.SymUnmanagedNamespaceRcw)SymUnmanagedNamespaceWrapperCache.Instance.GetOrCreateObjectForComInstance(intermediate[i], CreateObjectFlags.UniqueInstance); + namespaces[i] = (SymUnmanagedNamespaceWrapperCache.SymUnmanagedNamespaceRcw)Instance.GetOrCreateObjectForComInstance(intermediate[i], CreateObjectFlags.UniqueInstance); } } } @@ -496,7 +495,7 @@ private sealed class SymUnmanagedVariableWrapperCache : ComWrappers public sealed unsafe record SymUnmanagedVariableRcw(IntPtr Inst) : ISymUnmanagedVariable { - private bool _disposed = false; + private bool _disposed; public int GetName(int bufferLength, out int count, char[] name) { @@ -580,7 +579,7 @@ private sealed class SymUnmanagedScopeWrapperCache : ComWrappers public sealed unsafe record SymUnmanagedScopeRcw(IntPtr Inst) : ISymUnmanagedScope { - private bool _disposed = false; + private bool _disposed; public int GetMethod(out ISymUnmanagedMethod? method) { @@ -599,7 +598,7 @@ public int GetParent(out ISymUnmanagedScope? scope) IntPtr scopePtr; int hr = func(Inst, &scopePtr); scope = hr == 0 - ? (SymUnmanagedScopeWrapperCache.SymUnmanagedScopeRcw)SymUnmanagedScopeWrapperCache.Instance.GetOrCreateObjectForComInstance(scopePtr, CreateObjectFlags.UniqueInstance) + ? (SymUnmanagedScopeWrapperCache.SymUnmanagedScopeRcw)Instance.GetOrCreateObjectForComInstance(scopePtr, CreateObjectFlags.UniqueInstance) : null; return hr; } @@ -627,7 +626,7 @@ public int GetChildren(int bufferLength, out int count, ISymUnmanagedScope[] chi { for (int i = 0; i < count; i++) { - children[i] = (SymUnmanagedScopeWrapperCache.SymUnmanagedScopeRcw)SymUnmanagedScopeWrapperCache.Instance.GetOrCreateObjectForComInstance(intermediate[i], CreateObjectFlags.UniqueInstance); + children[i] = (SymUnmanagedScopeWrapperCache.SymUnmanagedScopeRcw)Instance.GetOrCreateObjectForComInstance(intermediate[i], CreateObjectFlags.UniqueInstance); } } } @@ -751,9 +750,9 @@ private sealed class SymUnmanagedDocumentWrapperCache : ComWrappers } protected override void ReleaseObjects(IEnumerable objects) => throw new NotImplementedException(); - public unsafe record SymUnmanagedDocumentRcw(IntPtr Inst) : ISymUnmanagedDocument + public sealed unsafe record SymUnmanagedDocumentRcw(IntPtr Inst) : ISymUnmanagedDocument { - private bool _disposed = false; + private bool _disposed; public int GetUrl(int bufferLength, out int count, char[] url) { @@ -864,7 +863,7 @@ private sealed class SymUnmanagedMethodWrapperCache : ComWrappers public sealed unsafe record SymUnmanagedMethodRcw(IntPtr Inst) : ISymUnmanagedMethod { - private bool _disposed = false; + private bool _disposed; public int GetToken(out int methodToken) { @@ -1080,7 +1079,7 @@ protected override object CreateObject(IntPtr externalComObject, CreateObjectFla /// public sealed record SymUnmanagedReaderRcw(IntPtr Inst) : ISymUnmanagedReader { - private bool _disposed = false; + private bool _disposed; public unsafe int GetMethod(int methodToken, out ISymUnmanagedMethod? method) { @@ -1127,7 +1126,7 @@ int GetReaderForFile( } private static int CoCreateInstance(ref Guid rclsid, IntPtr pUnkOuter, - Int32 dwClsContext, + int dwClsContext, ref Guid riid, out CoCreateWrapperCache.SymUnmanagedBinderRcw? ppv) { @@ -1140,19 +1139,21 @@ private static int CoCreateInstance(ref Guid rclsid, IntPtr pUnkOuter, [DllImport("ole32.dll")] static extern int CoCreateInstance(ref Guid rclsid, IntPtr pUnkOuter, - Int32 dwClsContext, + int dwClsContext, ref Guid riid, out IntPtr ppv); } - private void ThrowExceptionForHR(int hr) + private static void ThrowExceptionForHR(int hr) { Marshal.ThrowExceptionForHR(hr, new IntPtr(-1)); } private static readonly Guid SymBinderIID = new Guid(0x0a29ff9e, 0x7f9c, 0x4437, 0x8b, 0x11, 0xf4, 0x24, 0x49, 0x1e, 0x39, 0x31); +#pragma warning disable CA1810 // Initialize reference type static fields inline static UnmanagedPdbSymbolReader() +#pragma warning restore CA1810 // Initialize reference type static fields inline { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { @@ -1202,8 +1203,8 @@ static UnmanagedPdbSymbolReader() } } - private readonly static MetaDataDispenserWrapperCache.MetaDataDispenserRcw? s_metadataDispenser; - private readonly static CoCreateWrapperCache.SymUnmanagedBinderRcw? s_symBinder; + private static readonly MetaDataDispenserWrapperCache.MetaDataDispenserRcw? s_metadataDispenser; + private static readonly CoCreateWrapperCache.SymUnmanagedBinderRcw? s_symBinder; public static PdbSymbolReader? TryOpenSymbolReaderForMetadataFile(string metadataFileName, string searchPath) { @@ -1252,8 +1253,7 @@ private string GetUrl(ISymUnmanagedDocument doc) { lock (this) { - if (_urlCache == null) - _urlCache = new Dictionary(); + _urlCache ??= new Dictionary(); if (_urlCache.TryGetValue(doc, out var url)) return url; @@ -1323,7 +1323,7 @@ private void ProbeScopeForLocals(List variables, ISymUnmanagedS int attributes; ThrowExceptionForHR(local.GetAttributes(out attributes)); - variables.Add(new ILLocalVariable(slot, new String(nameBuffer, 0, nameLength - 1), (attributes & 0x1) != 0)); + variables.Add(new ILLocalVariable(slot, new string(nameBuffer, 0, nameLength - 1), (attributes & 0x1) != 0)); } int childrenCount; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/DelegateInfo.cs b/src/coreclr/tools/Common/TypeSystem/IL/DelegateInfo.cs index 1edcea55169753..11c803cf7617d6 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/DelegateInfo.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/DelegateInfo.cs @@ -71,10 +71,7 @@ public MethodSignature Signature { get { - if (_signature == null) - { - _signature = _delegateType.GetKnownMethod("Invoke", null).Signature; - } + _signature ??= _delegateType.GetKnownMethod("Invoke", null).Signature; return _signature; } } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/EcmaMethodIL.Symbols.cs b/src/coreclr/tools/Common/TypeSystem/IL/EcmaMethodIL.Symbols.cs index ade8a64726cee3..46c30699408abc 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/EcmaMethodIL.Symbols.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/EcmaMethodIL.Symbols.cs @@ -12,7 +12,7 @@ namespace Internal.IL { // Pluggable file that adds PDB handling functionality to EcmaMethodIL - partial class EcmaMethodIL + public partial class EcmaMethodIL { public override MethodDebugInformation GetDebugInfo() { diff --git a/src/coreclr/tools/Common/TypeSystem/IL/HelperExtensions.cs b/src/coreclr/tools/Common/TypeSystem/IL/HelperExtensions.cs index 66344ff698d162..4ccaff2d6dd9f0 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/HelperExtensions.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/HelperExtensions.cs @@ -69,7 +69,7 @@ public static MethodDesc GetKnownMethod(this TypeDesc type, string name, MethodS MethodDesc method = type.GetMethod(name, signature); if (method == null) { - throw new InvalidOperationException(String.Format("Expected method '{0}' not found on type '{1}'", name, type)); + throw new InvalidOperationException(string.Format("Expected method '{0}' not found on type '{1}'", name, type)); } return method; @@ -84,7 +84,7 @@ public static FieldDesc GetKnownField(this TypeDesc type, string name) FieldDesc field = type.GetField(name); if (field == null) { - throw new InvalidOperationException(String.Format("Expected field '{0}' not found on type '{1}'", name, type)); + throw new InvalidOperationException(string.Format("Expected field '{0}' not found on type '{1}'", name, type)); } return field; @@ -99,7 +99,7 @@ public static MetadataType GetKnownNestedType(this MetadataType type, string nam MetadataType nestedType = type.GetNestedType(name); if (nestedType == null) { - throw new InvalidOperationException(String.Format("Expected type '{0}' not found on type '{1}'", name, type)); + throw new InvalidOperationException(string.Format("Expected type '{0}' not found on type '{1}'", name, type)); } return nestedType; @@ -115,8 +115,8 @@ public static MetadataType GetKnownType(this ModuleDesc module, string @namespac if (type == null) { throw new InvalidOperationException( - String.Format("Expected type '{0}' not found in module '{1}'", - @namespace.Length > 0 ? String.Concat(@namespace, ".", name) : name, + string.Format("Expected type '{0}' not found in module '{1}'", + @namespace.Length > 0 ? string.Concat(@namespace, ".", name) : name, module)); } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/ILDisassembler.cs b/src/coreclr/tools/Common/TypeSystem/IL/ILDisassembler.cs index f11ed8cf5db8e1..864850ecc9cc26 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/ILDisassembler.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/ILDisassembler.cs @@ -143,7 +143,7 @@ private void AppendFieldSignature(StringBuilder sb, FieldDesc field) sb.Append(field.Name); } - private void AppendStringLiteral(StringBuilder sb, string s) + private static void AppendStringLiteral(StringBuilder sb, string s) { sb.Append('"'); for (int i = 0; i < s.Length; i++) @@ -187,20 +187,21 @@ private byte ReadILByte() return _ilBytes[_currentOffset++]; } - private UInt16 ReadILUInt16() + private ushort ReadILUInt16() { - UInt16 val = (UInt16)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8)); + ushort val = (ushort)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8)); _currentOffset += 2; return val; } - private UInt32 ReadILUInt32() + private uint ReadILUInt32() { - UInt32 val = (UInt32)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24)); + uint val = (uint)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24)); _currentOffset += 4; return val; } + private int ReadILToken() { return (int)ReadILUInt32(); @@ -418,7 +419,7 @@ public string GetNextInstruction() int delta = (int)ReadILUInt32(); AppendOffset(decodedInstruction, jmpBase + delta); } - decodedInstruction.Append(")"); + decodedInstruction.Append(')'); return decodedInstruction.ToString(); } @@ -493,7 +494,7 @@ public override void AppendName(StringBuilder sb, SignatureMethodVariable type) public override void AppendName(StringBuilder sb, SignatureTypeVariable type) { - sb.Append("!"); + sb.Append('!'); sb.Append(type.Index.ToStringInvariant()); } @@ -514,7 +515,7 @@ protected override void AppendNameForInstantiatedType(StringBuilder sb, DefType if (i > 0) sb.Append(", "); AppendNameWithValueClassPrefix(sb, type.Instantiation[i]); - } + } sb.Append('>'); } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/ILImporter.cs b/src/coreclr/tools/Common/TypeSystem/IL/ILImporter.cs index 8f4cb7440c71ac..1ac634591cd12c 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/ILImporter.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/ILImporter.cs @@ -1,14 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; - using Internal.TypeSystem; -using Internal.IL; namespace Internal.IL { - internal partial class ILImporter + internal sealed partial class ILImporter { private BasicBlock[] _basicBlocks; // Maps IL offset to basic block @@ -29,22 +26,22 @@ private byte ReadILByte() return _ilBytes[_currentOffset++]; } - private UInt16 ReadILUInt16() + private ushort ReadILUInt16() { if (_currentOffset + 1 >= _ilBytes.Length) ReportMethodEndInsideInstruction(); - UInt16 val = (UInt16)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8)); + ushort val = (ushort)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8)); _currentOffset += 2; return val; } - private UInt32 ReadILUInt32() + private uint ReadILUInt32() { if (_currentOffset + 3 >= _ilBytes.Length) ReportMethodEndInsideInstruction(); - UInt32 val = (UInt32)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24)); + uint val = (uint)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24)); _currentOffset += 4; return val; } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/ILOpcode.cs b/src/coreclr/tools/Common/TypeSystem/IL/ILOpcode.cs index f3a11e0074dc86..3a332e23463982 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/ILOpcode.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/ILOpcode.cs @@ -1,8 +1,6 @@ // 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 Internal.IL { /// diff --git a/src/coreclr/tools/Common/TypeSystem/IL/ILReader.cs b/src/coreclr/tools/Common/TypeSystem/IL/ILReader.cs index d722b2e1712891..d0022a5bad78be 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/ILReader.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/ILReader.cs @@ -1,7 +1,6 @@ // 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 Internal.TypeSystem; using Debug = System.Diagnostics.Debug; @@ -55,22 +54,22 @@ public byte ReadILByte() return _ilBytes[_currentOffset++]; } - public UInt16 ReadILUInt16() + public ushort ReadILUInt16() { if (_currentOffset + 2 > _ilBytes.Length) ThrowHelper.ThrowInvalidProgramException(); - UInt16 val = (UInt16)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8)); + ushort val = (ushort)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8)); _currentOffset += 2; return val; } - public UInt32 ReadILUInt32() + public uint ReadILUInt32() { if (_currentOffset + 4 > _ilBytes.Length) ThrowHelper.ThrowInvalidProgramException(); - UInt32 val = (UInt32)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24)); + uint val = (uint)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24)); _currentOffset += 4; return val; } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/ILStackHelper.cs b/src/coreclr/tools/Common/TypeSystem/IL/ILStackHelper.cs index 19c643256b4b03..1204f1b6655f34 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/ILStackHelper.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/ILStackHelper.cs @@ -24,7 +24,7 @@ public static void CheckStackBalance(this MethodIL methodIL) /// public static int ComputeMaxStack(this MethodIL methodIL) { - const int StackHeightNotSet = Int32.MinValue; + const int StackHeightNotSet = int.MinValue; byte[] ilbytes = methodIL.GetILBytes(); int currentOffset = 0; @@ -278,7 +278,7 @@ public static int ComputeMaxStack(this MethodIL methodIL) stackHeight = StackHeightNotSet; } break; - + case ILOpcode.call: case ILOpcode.calli: case ILOpcode.callvirt: diff --git a/src/coreclr/tools/Common/TypeSystem/IL/ILTokenReplacer.cs b/src/coreclr/tools/Common/TypeSystem/IL/ILTokenReplacer.cs index cc6dca8ef20d7c..63c2a7fe4cbab8 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/ILTokenReplacer.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/ILTokenReplacer.cs @@ -29,7 +29,7 @@ public static void Replace(byte[] ilStream, Func tokenReplaceFunc) // Replace token in IL stream with a new token provided by the tokenReplaceFunc // // This is used by the StandaloneMethodMetadata logic to create method local tokens - // and by the IL provider used for cross module inlining to create tokens which are + // and by the IL provider used for cross module inlining to create tokens which are // stable and contained within the R2R module instead of being in a module separated // by a version boundary. int token = BinaryPrimitives.ReadInt32LittleEndian(tokenSpan); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/InstantiatedMethodIL.cs b/src/coreclr/tools/Common/TypeSystem/IL/InstantiatedMethodIL.cs index 9def3ed499b8be..5d4fb39c953a11 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/InstantiatedMethodIL.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/InstantiatedMethodIL.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem; using Debug = System.Diagnostics.Debug; @@ -21,7 +19,7 @@ public InstantiatedMethodIL(MethodDesc owningMethod, MethodIL methodIL) Debug.Assert(methodIL.GetMethodILDefinition() == methodIL); Debug.Assert(owningMethod.HasInstantiation || owningMethod.OwningType.HasInstantiation); Debug.Assert(owningMethod.GetTypicalMethodDefinition() == methodIL.OwningMethod); - + _methodIL = methodIL; _method = owningMethod; @@ -86,12 +84,12 @@ public override LocalVariableDefinition[] GetLocals() } } - return (clone == null) ? locals : clone; + return clone ?? locals; } - public override Object GetObject(int token, NotFoundBehavior notFoundBehavior) + public override object GetObject(int token, NotFoundBehavior notFoundBehavior) { - Object o = _methodIL.GetObject(token, notFoundBehavior); + object o = _methodIL.GetObject(token, notFoundBehavior); if (o is MethodDesc) { @@ -105,9 +103,8 @@ public override Object GetObject(int token, NotFoundBehavior notFoundBehavior) { o = ((FieldDesc)o).InstantiateSignature(_typeInstantiation, _methodInstantiation); } - else if (o is MethodSignature) + else if (o is MethodSignature template) { - MethodSignature template = (MethodSignature)o; MethodSignatureBuilder builder = new MethodSignatureBuilder(template); builder.ReturnType = template.ReturnType.InstantiateSignature(_typeInstantiation, _methodInstantiation); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/MethodIL.Symbols.cs b/src/coreclr/tools/Common/TypeSystem/IL/MethodIL.Symbols.cs index 849db1a5df10a3..58990200f3775c 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/MethodIL.Symbols.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/MethodIL.Symbols.cs @@ -4,11 +4,9 @@ using System; using System.Collections.Generic; -using Internal.TypeSystem; - namespace Internal.IL { - partial class MethodIL + public partial class MethodIL { public virtual MethodDebugInformation GetDebugInfo() { @@ -16,7 +14,7 @@ public virtual MethodDebugInformation GetDebugInfo() } } - partial class InstantiatedMethodIL + public partial class InstantiatedMethodIL { public override MethodDebugInformation GetDebugInfo() { diff --git a/src/coreclr/tools/Common/TypeSystem/IL/MethodIL.cs b/src/coreclr/tools/Common/TypeSystem/IL/MethodIL.cs index 2f8b54249197e2..13aee813f36af3 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/MethodIL.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/MethodIL.cs @@ -1,14 +1,12 @@ // 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 Internal.TypeSystem; namespace Internal.IL { // - // This duplicates types from System.Reflection.Metadata to avoid layering issues, and + // This duplicates types from System.Reflection.Metadata to avoid layering issues, and // because of the System.Reflection.Metadata constructors are not public anyway. // @@ -73,7 +71,7 @@ public virtual MethodILScope GetMethodILScopeDefinition() /// (typically a , , , /// or ). /// - public abstract Object GetObject(int token, NotFoundBehavior notFoundBehavior = NotFoundBehavior.Throw); + public abstract object GetObject(int token, NotFoundBehavior notFoundBehavior = NotFoundBehavior.Throw); public override string ToString() { @@ -113,7 +111,7 @@ public abstract partial class MethodIL : MethodILScope /// public abstract ILExceptionRegion[] GetExceptionRegions(); - public override sealed MethodILScope GetMethodILScopeDefinition() + public sealed override MethodILScope GetMethodILScopeDefinition() { return GetMethodILDefinition(); } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/MethodILDebugView.cs b/src/coreclr/tools/Common/TypeSystem/IL/MethodILDebugView.cs index 03fc460d2582c4..28b9818c3af1ef 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/MethodILDebugView.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/MethodILDebugView.cs @@ -33,20 +33,20 @@ public string Disassembly if (!owningMethod.Signature.IsStatic) sb.Append("instance "); disasm.AppendType(sb, owningMethod.Signature.ReturnType); - sb.Append(" "); + sb.Append(' '); sb.Append(owningMethod.Name); if (owningMethod.HasInstantiation) { - sb.Append("<"); + sb.Append('<'); for (int i = 0; i < owningMethod.Instantiation.Length; i++) { if (i != 0) sb.Append(", "); disasm.AppendType(sb, owningMethod.Instantiation[i]); } - sb.Append(">"); + sb.Append('>'); } - sb.Append("("); + sb.Append('('); for (int i = 0; i < owningMethod.Signature.Length; i++) { if (i != 0) @@ -71,7 +71,7 @@ public string Disassembly if (_methodIL.IsInitLocals) sb.Append("init "); - sb.Append("("); + sb.Append('('); for (int i = 0; i < locals.Length; i++) { @@ -81,7 +81,7 @@ public string Disassembly sb.Append(' ', 6); } disasm.AppendType(sb, locals[i].Type); - sb.Append(" "); + sb.Append(' '); if (locals[i].IsPinned) sb.Append("pinned "); sb.Append("V_"); @@ -101,7 +101,7 @@ public string Disassembly ILDisassembler.AppendOffset(sb, region.TryOffset); sb.Append(" to "); ILDisassembler.AppendOffset(sb, region.TryOffset + region.TryLength); - + switch (region.Kind) { case ILExceptionRegionKind.Catch: diff --git a/src/coreclr/tools/Common/TypeSystem/IL/NativeAotILProvider.cs b/src/coreclr/tools/Common/TypeSystem/IL/NativeAotILProvider.cs index 5e3f6e62ec84f7..2de9aa4f8c0fba 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/NativeAotILProvider.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/NativeAotILProvider.cs @@ -14,7 +14,7 @@ namespace Internal.IL { public sealed class NativeAotILProvider : ILProvider { - private MethodIL TryGetRuntimeImplementedMethodIL(MethodDesc method) + private static MethodIL TryGetRuntimeImplementedMethodIL(MethodDesc method) { // Provides method bodies for runtime implemented methods. It can return null for // methods that are treated specially by the codegen. @@ -36,7 +36,7 @@ private MethodIL TryGetRuntimeImplementedMethodIL(MethodDesc method) /// It can return null if it's not an intrinsic recognized by the compiler, /// but an intrinsic e.g. recognized by codegen. /// - private MethodIL TryGetIntrinsicMethodIL(MethodDesc method) + private static MethodIL TryGetIntrinsicMethodIL(MethodDesc method) { Debug.Assert(method.IsIntrinsic); @@ -108,7 +108,7 @@ private MethodIL TryGetIntrinsicMethodIL(MethodDesc method) /// are specialized per instantiation. It can return null if the intrinsic /// is not recognized. /// - private MethodIL TryGetPerInstantiationIntrinsicMethodIL(MethodDesc method) + private static MethodIL TryGetPerInstantiationIntrinsicMethodIL(MethodDesc method) { Debug.Assert(method.IsIntrinsic); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ArrayMethodILEmitter.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ArrayMethodILEmitter.cs index 6a57b848dfdb6e..0c81ec32862007 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ArrayMethodILEmitter.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ArrayMethodILEmitter.cs @@ -30,7 +30,7 @@ private ArrayMethodILEmitter(ArrayMethod method) _emitter = new ILEmitter(); // This helper field is needed to generate proper GC tracking. There is no direct way - // to create interior pointer. + // to create interior pointer. _helperFieldToken = _emitter.NewToken(_method.Context.GetWellKnownType(WellKnownType.Object).GetKnownField("m_pEEType")); } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AssemblyGetExecutingAssemblyMethodThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AssemblyGetExecutingAssemblyMethodThunk.Sorting.cs index 004388db62c15a..fb12ea795a79d6 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AssemblyGetExecutingAssemblyMethodThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AssemblyGetExecutingAssemblyMethodThunk.Sorting.cs @@ -7,7 +7,7 @@ namespace Internal.IL.Stubs { // Functionality related to deterministic ordering of types - partial class AssemblyGetExecutingAssemblyMethodThunk + internal partial class AssemblyGetExecutingAssemblyMethodThunk { protected override int ClassCode => 1459986716; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AssemblyGetExecutingAssemblyMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AssemblyGetExecutingAssemblyMethodThunk.cs index ce1d69716a7b97..78386fbe55cb4f 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AssemblyGetExecutingAssemblyMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AssemblyGetExecutingAssemblyMethodThunk.cs @@ -10,7 +10,7 @@ namespace Internal.IL.Stubs /// is to load something that will let us identify the current assembly and call a class library /// helper that will let us get the Assembly. /// - internal partial class AssemblyGetExecutingAssemblyMethodThunk : ILStubMethod + internal sealed partial class AssemblyGetExecutingAssemblyMethodThunk : ILStubMethod { public AssemblyGetExecutingAssemblyMethodThunk(TypeDesc owningType, IAssemblyDesc executingAssembly) { @@ -81,7 +81,7 @@ public override MethodIL EmitIL() } } - internal class AssemblyGetExecutingAssemblyMethodThunkCache + internal sealed class AssemblyGetExecutingAssemblyMethodThunkCache { private TypeDesc _owningTypeForThunks; private Unifier _cache; @@ -97,7 +97,7 @@ public MethodDesc GetHelper(IAssemblyDesc executingAssembly) return _cache.GetOrCreateValue(executingAssembly); } - private class Unifier : LockFreeReaderHashtable + private sealed class Unifier : LockFreeReaderHashtable { private AssemblyGetExecutingAssemblyMethodThunkCache _parent; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Mangling.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Mangling.cs index 95beb89a11add2..fa3f8608f5032c 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Mangling.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Mangling.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Diagnostics; using Internal.TypeSystem; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs index cd6e620aa86074..86bd6fce3f81ea 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.IL.Stubs { // Functionality related to deterministic ordering of methods - partial class CalliMarshallingMethodThunk + public partial class CalliMarshallingMethodThunk { protected override int ClassCode => 1594107963; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs index d0d397bafdf388..23721ea8e1c4c5 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs @@ -1,11 +1,7 @@ // 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 Internal.TypeSystem; -using Internal.TypeSystem.Interop; -using Debug = System.Diagnostics.Debug; -using Internal.TypeSystem.Ecma; namespace Internal.IL.Stubs { diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ComparerIntrinsics.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ComparerIntrinsics.cs index 91856de2d880d5..8f6cd67f9a6040 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ComparerIntrinsics.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ComparerIntrinsics.cs @@ -1,7 +1,6 @@ // 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 Internal.TypeSystem; @@ -165,7 +164,7 @@ private static TypeDesc[] GetPotentialComparersForTypeCommon(TypeDesc type, stri { // This can be any of the comparers we have. - ArrayBuilder universalComparers = new ArrayBuilder(); + ArrayBuilder universalComparers = default(ArrayBuilder); universalComparers.Add(context.SystemModule.GetKnownType("System.Collections.Generic", $"Nullable{flavor}`1") .MakeInstantiatedType(type)); @@ -182,7 +181,7 @@ private static TypeDesc[] GetPotentialComparersForTypeCommon(TypeDesc type, stri return universalComparers.ToArray(); } - + // This mirrors exactly what GetUnknownEquatableComparer and GetUnknownComparer (in the class library) // will need at runtime. This is the general purpose code path that can be used to compare // anything. @@ -203,7 +202,7 @@ private static TypeDesc[] GetPotentialComparersForTypeCommon(TypeDesc type, stri .MakeInstantiatedType(type), }; } - + return new TypeDesc[] { context.SystemModule.GetKnownType("System.Collections.Generic", $"Generic{flavor}`1") @@ -226,8 +225,7 @@ private static bool ImplementsInterfaceOfSelf(TypeDesc type, string interfaceNam if (interfaceInstantiation.Length == 1 && interfaceInstantiation[0] == type) { - if (interfaceType == null) - interfaceType = type.Context.SystemModule.GetKnownType("System", interfaceName); + interfaceType ??= interfaceType = type.Context.SystemModule.GetKnownType("System", interfaceName); if (implementedInterface.GetTypeDefinition() == interfaceType) return true; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Mangling.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Mangling.cs index 0f8d28eb9e8f27..27dbb90c06c859 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Mangling.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Mangling.cs @@ -1,7 +1,6 @@ // 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 Internal.TypeSystem; namespace Internal.IL.Stubs diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Sorting.cs index b38cd1fda8e540..43d1c94a721099 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.IL.Stubs { // Functionality related to deterministic ordering of methods - partial class DelegateMarshallingMethodThunk + public partial class DelegateMarshallingMethodThunk { protected override int ClassCode => 1018037605; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.cs index 5b098630690204..368f19a79a74c2 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.cs @@ -101,7 +101,7 @@ public MetadataType DelegateType } } - private TypeDesc GetNativeMethodParameterType(TypeDesc managedType, MarshalAsDescriptor marshalAs, InteropStateManager interopStateManager, bool isReturn, bool isAnsi) + private static TypeDesc GetNativeMethodParameterType(TypeDesc managedType, MarshalAsDescriptor marshalAs, InteropStateManager interopStateManager, bool isReturn, bool isAnsi) { TypeDesc nativeType; try @@ -156,7 +156,7 @@ public override MethodSignature Signature marshalAs = parameterMetadataArray[parameterIndex++].MarshalAsDescriptor; } - TypeDesc nativeReturnType = GetNativeMethodParameterType(delegateSignature.ReturnType, + TypeDesc nativeReturnType = GetNativeMethodParameterType(delegateSignature.ReturnType, marshalAs, _interopStateManager, isReturn:true, @@ -180,7 +180,7 @@ public override MethodSignature Signature var managedType = isByRefType ? delegateSignature[i].GetParameterType() : delegateSignature[i]; - var nativeType = GetNativeMethodParameterType(managedType, + var nativeType = GetNativeMethodParameterType(managedType, marshalAs, _interopStateManager, isReturn:false, @@ -231,8 +231,8 @@ private string NamePrefix case DelegateMarshallingMethodThunkKind.ForwardNativeFunctionWrapper: return "ForwardNativeFunctionWrapper"; default: - System.Diagnostics.Debug.Fail("Unexpected DelegateMarshallingMethodThunkKind."); - return String.Empty; + Debug.Fail("Unexpected DelegateMarshallingMethodThunkKind."); + return string.Empty; } } } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.Sorting.cs index 1126e01d4020ba..fabf0153399ec0 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.IL.Stubs { // Functionality related to deterministic ordering of types - partial class DelegateThunk + public partial class DelegateThunk { protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) { @@ -15,7 +15,7 @@ protected override int CompareToImpl(MethodDesc other, TypeSystemComparer compar } } - partial class DelegateInvokeOpenStaticThunk + public partial class DelegateInvokeOpenStaticThunk { protected override int ClassCode => 386356101; } @@ -25,27 +25,27 @@ public sealed partial class DelegateInvokeOpenInstanceThunk protected override int ClassCode => -1787190244; } - partial class DelegateInvokeClosedStaticThunk + public partial class DelegateInvokeClosedStaticThunk { protected override int ClassCode => 28195375; } - partial class DelegateInvokeMulticastThunk + public partial class DelegateInvokeMulticastThunk { protected override int ClassCode => 639863471; } - partial class DelegateInvokeInstanceClosedOverGenericMethodThunk + public partial class DelegateInvokeInstanceClosedOverGenericMethodThunk { protected override int ClassCode => -354480633; } - partial class DelegateInvokeObjectArrayThunk + public partial class DelegateInvokeObjectArrayThunk { protected override int ClassCode => 1993292344; } - partial class DelegateGetThunkMethodOverride + public partial class DelegateGetThunkMethodOverride { protected override int ClassCode => -321263379; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.cs index 55037d70fe8100..99834d7cb23632 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateThunks.cs @@ -207,7 +207,7 @@ public override MethodIL EmitIL() codeStream.Emit(ILOpcode.box, emitter.NewToken(boxThisType)); } } - + codeStream.Emit(ILOpcode.call, emitter.NewToken(SystemDelegateType.GetKnownMethod("GetActualTargetFunctionPointer", null))); MethodSignature targetSignature = new MethodSignature(0, 0, Signature.ReturnType, parameters); @@ -346,7 +346,7 @@ public override MethodIL EmitIL() codeStream.EmitLdc(0); codeStream.EmitStLoc(iteratorLocal); - // Loop across every element of the array. + // Loop across every element of the array. ILCodeLabel startOfLoopLabel = emitter.NewCodeLabel(); codeStream.EmitLabel(startOfLoopLabel); @@ -494,7 +494,7 @@ internal DelegateInvokeObjectArrayThunk(DelegateInfo delegateInfo) public override MethodIL EmitIL() { // We will generate the following code: - // + // // object ret; // object[] args = new object[parameterCount]; // args[0] = param0; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Mangling.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Mangling.cs index 1c03c18928c7ee..012da765943ac0 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Mangling.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Mangling.cs @@ -1,7 +1,6 @@ // 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 Internal.TypeSystem; namespace Internal.IL.Stubs diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Sorting.cs index 3e67c728c743b8..0102dfc03b8554 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.Sorting.cs @@ -1,15 +1,12 @@ // 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 Internal.TypeSystem; -using Debug = System.Diagnostics.Debug; - namespace Internal.IL.Stubs { // Functionality related to deterministic ordering of types - partial class DynamicInvokeMethodThunk + public partial class DynamicInvokeMethodThunk { protected override int ClassCode => -1980933220; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.cs index 50b446fabc35d0..ee50cc4f0565ff 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DynamicInvokeMethodThunk.cs @@ -1,15 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Reflection.Emit; -using System.Reflection; -using System.Text; - using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; -using Interlocked = System.Threading.Interlocked; namespace Internal.IL.Stubs { diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.Sorting.cs index 33b07a8e86f109..b8b935da92f1d8 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.IL.Stubs { // Functionality related to deterministic ordering of types - partial class EnumGetHashCodeThunk + internal partial class EnumGetHashCodeThunk { protected override int ClassCode => 261739662; @@ -17,7 +17,7 @@ protected override int CompareToImpl(MethodDesc other, TypeSystemComparer compar } } - partial class EnumEqualsThunk + internal partial class EnumEqualsThunk { protected override int ClassCode => -1774524780; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.cs index dc8fba49876afc..f1eb89c48d5215 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/EnumThunks.cs @@ -12,7 +12,7 @@ namespace Internal.IL.Stubs /// This method prevents boxing of 'this' that would be required before a call to /// the System.Enum's default implementation. /// - internal partial class EnumGetHashCodeThunk : ILStubMethod + internal sealed partial class EnumGetHashCodeThunk : ILStubMethod { private TypeDesc _owningType; private MethodSignature _signature; @@ -103,7 +103,7 @@ public override MethodIL EmitIL() /// This method prevents boxing of 'this' that would be required before a call to /// the System.Enum's default implementation. /// - internal partial class EnumEqualsThunk : ILStubMethod + internal sealed partial class EnumEqualsThunk : ILStubMethod { private TypeDesc _owningType; private MethodSignature _signature; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.Sorting.cs index 66d5142caa2878..8a1411a2624428 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.IL.Stubs { // Functionality related to deterministic ordering of types - partial class ForwardDelegateCreationThunk + public partial class ForwardDelegateCreationThunk { protected override int ClassCode => 1026039617; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.cs index fd1e907f844031..3dd0616af51eb2 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ForwardDelegateCreationThunk.cs @@ -1,11 +1,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; using Internal.TypeSystem; using Internal.TypeSystem.Interop; -using Debug = System.Diagnostics.Debug; -using Internal.TypeSystem.Ecma; namespace Internal.IL.Stubs { @@ -18,7 +15,7 @@ public partial class ForwardDelegateCreationThunk : ILStubMethod private readonly MetadataType _delegateType; private readonly InteropStateManager _interopStateManager; private MethodSignature _signature; - + public ForwardDelegateCreationThunk(MetadataType delegateType, TypeDesc owningType, InteropStateManager interopStateManager) { @@ -55,14 +52,11 @@ public override MethodSignature Signature { get { - if (_signature == null) - { - _signature = new MethodSignature(MethodSignatureFlags.Static, 0, + _signature ??= new MethodSignature(MethodSignatureFlags.Static, 0, DelegateType, new TypeDesc[] { Context.GetWellKnownType(WellKnownType.IntPtr) }); - } return _signature; } } @@ -87,7 +81,7 @@ public override string DiagnosticName /// This thunk creates a delegate from a native function pointer /// by first creating a PInvokeDelegateWrapper from the function pointer /// and then creating the delegate from the Invoke method of the wrapper - /// + /// /// Generated IL: /// ldarg 0 /// newobj PInvokeDelegateWrapper.ctor @@ -95,8 +89,8 @@ public override string DiagnosticName /// ldvirtftn PInvokeDelegateWrapper.Invoke /// newobj DelegateType.ctor /// ret - /// - /// Equivalent C# + /// + /// Equivalent C# /// return new DelegateType(new PInvokeDelegateWrapper(functionPointer).Invoke) /// public override MethodIL EmitIL() @@ -116,8 +110,8 @@ public override MethodIL EmitIL() .GetPInvokeDelegateWrapperMethod(PInvokeDelegateWrapperMethodKind.Invoke))); codeStream.Emit(ILOpcode.newobj, emitter.NewToken( - _delegateType.GetMethod(".ctor", - new MethodSignature(MethodSignatureFlags.None, + _delegateType.GetMethod(".ctor", + new MethodSignature(MethodSignatureFlags.None, genericParameterCount: 0, returnType: Context.GetWellKnownType(WellKnownType.Void), parameters: new TypeDesc[] { Context.GetWellKnownType(WellKnownType.Object), diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/GetCanonTypeIntrinsic.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/GetCanonTypeIntrinsic.cs index 5989185359f412..9c44adad0d5fe1 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/GetCanonTypeIntrinsic.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/GetCanonTypeIntrinsic.cs @@ -1,8 +1,6 @@ // 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 Internal.Runtime; using Internal.TypeSystem; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ILEmitter.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ILEmitter.cs index bc6985c43e6b64..b6f31e130142e5 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ILEmitter.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ILEmitter.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; -using Internal.IL; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; @@ -521,7 +520,7 @@ internal ILExceptionRegionBuilder() internal int TryLength => _endTryStream.RelativeToAbsoluteOffset(_endTryOffset) - TryOffset; internal int HandlerOffset => _beginHandlerStream.RelativeToAbsoluteOffset(_beginHandlerOffset); internal int HandlerLength => _endHandlerStream.RelativeToAbsoluteOffset(_endHandlerOffset) - HandlerOffset; - + internal bool IsDefined => _beginTryStream != null && _endTryStream != null && _beginHandlerStream != null && _endHandlerStream != null; @@ -542,7 +541,7 @@ public class ILStubMethodIL : MethodIL { private readonly byte[] _ilBytes; private readonly LocalVariableDefinition[] _locals; - private readonly Object[] _tokens; + private readonly object[] _tokens; private readonly MethodDesc _method; private readonly ILExceptionRegion[] _exceptionRegions; private readonly MethodDebugInformation _debugInformation; @@ -550,7 +549,7 @@ public class ILStubMethodIL : MethodIL private const int MaxStackNotSet = -1; private int _maxStack; - public ILStubMethodIL(MethodDesc owningMethod, byte[] ilBytes, LocalVariableDefinition[] locals, Object[] tokens, ILExceptionRegion[] exceptionRegions = null, MethodDebugInformation debugInfo = null) + public ILStubMethodIL(MethodDesc owningMethod, byte[] ilBytes, LocalVariableDefinition[] locals, object[] tokens, ILExceptionRegion[] exceptionRegions = null, MethodDebugInformation debugInfo = null) { _ilBytes = ilBytes; _locals = locals; @@ -558,12 +557,10 @@ public ILStubMethodIL(MethodDesc owningMethod, byte[] ilBytes, LocalVariableDefi _method = owningMethod; _maxStack = MaxStackNotSet; - if (exceptionRegions == null) - exceptionRegions = Array.Empty(); + exceptionRegions ??= Array.Empty(); _exceptionRegions = exceptionRegions; - if (debugInfo == null) - debugInfo = MethodDebugInformation.None; + debugInfo ??= MethodDebugInformation.None; _debugInformation = debugInfo; } @@ -622,7 +619,7 @@ public override LocalVariableDefinition[] GetLocals() { return _locals; } - public override Object GetObject(int token, NotFoundBehavior notFoundBehavior) + public override object GetObject(int token, NotFoundBehavior notFoundBehavior) { return _tokens[(token & 0xFFFFFF) - 1]; } @@ -666,7 +663,7 @@ public class ILEmitter { private ArrayBuilder _codeStreams; private ArrayBuilder _locals; - private ArrayBuilder _tokens; + private ArrayBuilder _tokens; private ArrayBuilder _finallyRegions; public ILEmitter() @@ -680,7 +677,7 @@ public ILCodeStream NewCodeStream() return stream; } - private ILToken NewToken(Object value, int tokenType) + private ILToken NewToken(object value, int tokenType) { Debug.Assert(value != null); _tokens.Add(value); @@ -802,7 +799,7 @@ public MethodIL Link(MethodDesc owningMethod) return result; } - private class EmittedMethodDebugInformation : MethodDebugInformation + private sealed class EmittedMethodDebugInformation : MethodDebugInformation { private readonly ILSequencePoint[] _sequencePoints; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/InterlockedIntrinsics.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/InterlockedIntrinsics.cs index 25523f68b100f4..7f0a8d2f191a49 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/InterlockedIntrinsics.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/InterlockedIntrinsics.cs @@ -1,7 +1,6 @@ // 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 Internal.TypeSystem; using Debug = System.Diagnostics.Debug; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MemoryMarshalIntrinsics.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MemoryMarshalIntrinsics.cs index de2c2712827c5a..aaa56db0888c74 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MemoryMarshalIntrinsics.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MemoryMarshalIntrinsics.cs @@ -1,7 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. - +#if READYTORUN using ILCompiler; +#endif using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.Mangling.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.Mangling.cs index 868ffc7c7596f5..1aeb7468376e69 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.Mangling.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.Mangling.cs @@ -5,7 +5,7 @@ namespace Internal.IL.Stubs { - partial class MethodBaseGetCurrentMethodThunk : IPrefixMangledMethod + internal partial class MethodBaseGetCurrentMethodThunk : IPrefixMangledMethod { MethodDesc IPrefixMangledMethod.BaseMethod { diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.Sorting.cs index d3afe93c396600..072225e04798d7 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.IL.Stubs { // Functionality related to deterministic ordering of types - partial class MethodBaseGetCurrentMethodThunk + internal partial class MethodBaseGetCurrentMethodThunk { protected override int ClassCode => 1889524798; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.cs index 82a729dc3eb2db..eaed268049d42c 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/MethodBaseGetCurrentMethodThunk.cs @@ -12,7 +12,7 @@ namespace Internal.IL.Stubs /// is to LDTOKEN the method considered "current method" and call into the class library to /// retrieve the associated MethodBase object instance. /// - internal partial class MethodBaseGetCurrentMethodThunk : ILStubMethod + internal sealed partial class MethodBaseGetCurrentMethodThunk : ILStubMethod { public MethodBaseGetCurrentMethodThunk(MethodDesc method) { @@ -90,7 +90,7 @@ public override MethodIL EmitIL() } } - internal class MethodBaseGetCurrentMethodThunkCache + internal sealed class MethodBaseGetCurrentMethodThunkCache { private Unifier _cache; @@ -104,7 +104,7 @@ public MethodDesc GetHelper(MethodDesc currentMethod) return _cache.GetOrCreateValue(currentMethod.GetTypicalMethodDefinition()); } - private class Unifier : LockFreeReaderHashtable + private sealed class Unifier : LockFreeReaderHashtable { protected override int GetKeyHashCode(MethodDesc key) { diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeILCodeStreams.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeILCodeStreams.cs index 1ad547dbb468b2..2a8aa221ce2170 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeILCodeStreams.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeILCodeStreams.cs @@ -22,9 +22,9 @@ public PInvokeILCodeStreams() // store that into the local // - CallsiteSetupCodeStream is used to used to load each previously generated local // and call the actual target native method. - // - ReturnValueMarshallingCodeStream is used to convert the native return value + // - ReturnValueMarshallingCodeStream is used to convert the native return value // to managed one. - // - UnmarshallingCodestream is used to propagate [out] native arguments values to + // - UnmarshallingCodestream is used to propagate [out] native arguments values to // managed ones. // - CleanupCodestream is used to perform a guaranteed cleanup FunctionPointerLoadStream = Emitter.NewCodeStream(); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeILEmitter.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeILEmitter.cs index 9d89ea53146943..42c25c1eee9650 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeILEmitter.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeILEmitter.cs @@ -444,7 +444,7 @@ public static MethodIL EmitIL(MethodDesc method, } catch (InvalidProgramException ex) { - Debug.Assert(!String.IsNullOrEmpty(ex.Message)); + Debug.Assert(!string.IsNullOrEmpty(ex.Message)); return MarshalHelpers.EmitExceptionBody(ex.Message, method); } } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeLazyFixupField.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeLazyFixupField.Sorting.cs index d3156fbefb2cf4..755340991928f9 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeLazyFixupField.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeLazyFixupField.Sorting.cs @@ -5,7 +5,7 @@ namespace Internal.IL.Stubs { - partial class PInvokeLazyFixupField + public partial class PInvokeLazyFixupField { protected override int ClassCode => -1784477702; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.Diagnostic.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.Diagnostic.cs index 66be6d96544525..940710e5078c22 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.Diagnostic.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.Diagnostic.cs @@ -1,11 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Internal.TypeSystem; - namespace Internal.IL.Stubs { - partial class PInvokeTargetNativeMethod + public partial class PInvokeTargetNativeMethod { public override string DiagnosticName { diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.Mangling.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.Mangling.cs index 0840a5856fa2a5..34ec3ed4ec351a 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.Mangling.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.Mangling.cs @@ -5,7 +5,7 @@ namespace Internal.IL.Stubs { - partial class PInvokeTargetNativeMethod : IPrefixMangledMethod + public partial class PInvokeTargetNativeMethod : IPrefixMangledMethod { MethodDesc IPrefixMangledMethod.BaseMethod { diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.Sorting.cs index da12ad0a8b2dc4..40449fc96b97a6 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.IL.Stubs { // Functionality related to deterministic ordering of types - partial class PInvokeTargetNativeMethod + public partial class PInvokeTargetNativeMethod { protected internal override int ClassCode => -1626939381; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.cs index 5683eee0429f10..0e3eaeae12e7e0 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.cs @@ -14,7 +14,7 @@ public sealed partial class PInvokeTargetNativeMethod : MethodDesc { private readonly MethodDesc _declMethod; private readonly MethodSignature _signature; - + public MethodDesc Target { get diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/RuntimeHelpersIntrinsics.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/RuntimeHelpersIntrinsics.cs index 53af0f37161d96..b8e1a23ca21e53 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/RuntimeHelpersIntrinsics.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/RuntimeHelpersIntrinsics.cs @@ -96,4 +96,3 @@ public static MethodIL EmitIL(MethodDesc method) } } } - diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StreamIntrinsics.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StreamIntrinsics.cs index 292e0240c67208..fc28505f84ced3 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StreamIntrinsics.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StreamIntrinsics.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem; using Debug = System.Diagnostics.Debug; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.Sorting.cs index 0cbb4f7e7c6c38..99365af5d86af7 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.Sorting.cs @@ -6,7 +6,7 @@ namespace Internal.IL.Stubs { // Functionality related to deterministic ordering of types - partial class StructMarshallingThunk + public partial class StructMarshallingThunk { protected override int ClassCode => 340834018; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.cs index 2751290f0c91ef..f8025e77c20876 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/StructMarshallingThunk.cs @@ -90,7 +90,7 @@ public override MethodSignature Signature }; break; default: - System.Diagnostics.Debug.Fail("Unexpected Struct marshalling thunk type"); + Debug.Fail("Unexpected Struct marshalling thunk type"); break; } _signature = new MethodSignature(MethodSignatureFlags.Static, 0, Context.GetWellKnownType(WellKnownType.Void), parameters); @@ -112,7 +112,7 @@ private string NamePrefix case StructMarshallingThunkType.Cleanup: return "Cleanup"; default: - System.Diagnostics.Debug.Fail("Unexpected Struct marshalling thunk type"); + Debug.Fail("Unexpected Struct marshalling thunk type"); return string.Empty; } } @@ -148,7 +148,7 @@ private Marshaller[] InitializeMarshallers() Marshaller[] marshallers = new Marshaller[numInstanceFields]; - PInvokeFlags flags = new PInvokeFlags(); + PInvokeFlags flags = default(PInvokeFlags); if (ManagedType.PInvokeStringFormat == PInvokeStringFormat.UnicodeClass || ManagedType.PInvokeStringFormat == PInvokeStringFormat.AutoClass) { flags.CharSet = CharSet.Unicode; @@ -203,17 +203,17 @@ private MethodIL EmitMarshallingIL(PInvokeILCodeStreams pInvokeILCodeStreams) } bool notEmpty = nativeEnumerator.MoveNext(); - Debug.Assert(notEmpty == true); + Debug.Assert(notEmpty); var nativeField = nativeEnumerator.Current; Debug.Assert(nativeField != null); bool isInlineArray = nativeField.FieldType is InlineArrayType; // - // Field marshallers expects the value of the fields to be + // Field marshallers expects the value of the fields to be // loaded on the stack. We load the value on the stack // before calling the marshallers. // Only exception is ByValArray marshallers. Since they can - // only be used for field marshalling, they load/store values + // only be used for field marshalling, they load/store values // directly from arguments. // @@ -270,7 +270,7 @@ private MethodIL EmitCleanupIL(PInvokeILCodeStreams pInvokeILCodeStreams) } bool notEmpty = nativeEnumerator.MoveNext(); - Debug.Assert(notEmpty == true); + Debug.Assert(notEmpty); var nativeField = nativeEnumerator.Current; Debug.Assert(nativeField != null); @@ -310,7 +310,7 @@ public override MethodIL EmitIL() } catch (InvalidProgramException ex) { - Debug.Assert(!String.IsNullOrEmpty(ex.Message)); + Debug.Assert(!string.IsNullOrEmpty(ex.Message)); return MarshalHelpers.EmitExceptionBody(ex.Message, this); } } @@ -318,7 +318,7 @@ public override MethodIL EmitIL() /// /// Loads the value of field of a struct at argument index argIndex to stack /// - private void LoadFieldValueFromArg(int argIndex, FieldDesc field, PInvokeILCodeStreams pInvokeILCodeStreams) + private static void LoadFieldValueFromArg(int argIndex, FieldDesc field, PInvokeILCodeStreams pInvokeILCodeStreams) { ILCodeStream stream = pInvokeILCodeStreams.MarshallingCodeStream; ILEmitter emitter = pInvokeILCodeStreams.Emitter; @@ -326,7 +326,7 @@ private void LoadFieldValueFromArg(int argIndex, FieldDesc field, PInvokeILCodeS stream.Emit(ILOpcode.ldfld, emitter.NewToken(field)); } - private void StoreFieldValueFromArg(int argIndex, FieldDesc field, PInvokeILCodeStreams pInvokeILCodeStreams) + private static void StoreFieldValueFromArg(int argIndex, FieldDesc field, PInvokeILCodeStreams pInvokeILCodeStreams) { ILCodeStream stream = pInvokeILCodeStreams.MarshallingCodeStream; ILEmitter emitter = pInvokeILCodeStreams.Emitter; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/TypeGetTypeMethodThunk.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/TypeGetTypeMethodThunk.Sorting.cs index c99a3ff3b40fa8..ceb658e3bd8952 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/TypeGetTypeMethodThunk.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/TypeGetTypeMethodThunk.Sorting.cs @@ -8,7 +8,7 @@ namespace Internal.IL.Stubs { // Functionality related to deterministic ordering of types - partial class TypeGetTypeMethodThunk + internal partial class TypeGetTypeMethodThunk { protected override int ClassCode => -949164050; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/TypeGetTypeMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/TypeGetTypeMethodThunk.cs index 7e7a9133b13c04..48db579f5ea5a9 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/TypeGetTypeMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/TypeGetTypeMethodThunk.cs @@ -12,7 +12,7 @@ namespace Internal.IL.Stubs /// the calling assembly for a matching type if the type name supplied by the user code was not assembly qualified. /// This thunk calls a helper method, passing it a string for what should be considered the "calling assembly". /// - internal partial class TypeGetTypeMethodThunk : ILStubMethod + internal sealed partial class TypeGetTypeMethodThunk : ILStubMethod { private readonly MethodDesc _helperMethod; @@ -104,7 +104,7 @@ public override MethodIL EmitIL() } } - internal class TypeGetTypeMethodThunkCache + internal sealed class TypeGetTypeMethodThunkCache { private TypeDesc _owningTypeForThunks; private Unifier _cache; @@ -132,7 +132,7 @@ public Key(string defaultAssemblyName, MethodDesc getTypeOverload) } } - private class Unifier : LockFreeReaderHashtable + private sealed class Unifier : LockFreeReaderHashtable { private TypeGetTypeMethodThunkCache _parent; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/UnsafeIntrinsics.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/UnsafeIntrinsics.cs index c371ec782fec6c..f25671773490bf 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/UnsafeIntrinsics.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/UnsafeIntrinsics.cs @@ -81,7 +81,7 @@ public static MethodIL EmitIL(MethodDesc method) case "IsNullRef": return new ILStubMethodIL(method, new byte[] { - (byte)ILOpcode.ldarg_0, + (byte)ILOpcode.ldarg_0, (byte)ILOpcode.ldc_i4_0, (byte)ILOpcode.conv_u, (byte)ILOpcode.prefix1, unchecked((byte)ILOpcode.ceq), (byte)ILOpcode.ret }, Array.Empty(), null); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.Sorting.cs index e12b3bc41567f9..2a650a278e24a9 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.Sorting.cs @@ -5,7 +5,7 @@ namespace Internal.IL.Stubs { - partial class ValueTypeGetFieldHelperMethodOverride + public partial class ValueTypeGetFieldHelperMethodOverride { protected override int ClassCode => 2036839816; diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.cs index 76c9184d4e6372..9bb60e317e2496 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/ValueTypeGetFieldHelperMethodOverride.cs @@ -71,7 +71,7 @@ public override MethodIL EmitIL() var switchStream = emitter.NewCodeStream(); var getFieldStream = emitter.NewCodeStream(); - ArrayBuilder fieldGetters = new ArrayBuilder(); + ArrayBuilder fieldGetters = default(ArrayBuilder); foreach (FieldDesc field in owningType.GetFields()) { if (field.IsStatic) @@ -120,7 +120,7 @@ public override MethodIL EmitIL() } switchStream.EmitLdc(fieldGetters.Count); - + switchStream.Emit(ILOpcode.ret); return emitter.Link(this); diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/FieldDesc.Interop.cs b/src/coreclr/tools/Common/TypeSystem/Interop/FieldDesc.Interop.cs index ad5a51232d7311..e12791ba2d7c55 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/FieldDesc.Interop.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/FieldDesc.Interop.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class FieldDesc + public partial class FieldDesc { /// /// Returns description of how the field should be marshalled to native code. @@ -14,7 +14,7 @@ public virtual MarshalAsDescriptor GetMarshalAsDescriptor() } } - partial class FieldForInstantiatedType + public partial class FieldForInstantiatedType { public override MarshalAsDescriptor GetMarshalAsDescriptor() { diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.Sorting.cs index a6d57faa45a4e5..ca637423c2cb20 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem.Interop { // Functionality related to deterministic ordering of types - partial class InlineArrayType + internal partial class InlineArrayType { protected override int ClassCode => 226817075; @@ -18,7 +18,7 @@ protected override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer return comparer.Compare(ElementType, otherType.ElementType); } - partial class InlineArrayMethod + private partial class InlineArrayMethod { protected override int ClassCode => -1303220581; @@ -34,7 +34,7 @@ protected override int CompareToImpl(MethodDesc other, TypeSystemComparer compar } } - partial class InlineArrayField + private partial class InlineArrayField { protected override int ClassCode => 1542668652; diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.cs index 51ac01f9a2fb68..512cad4be34eff 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/InlineArrayType.cs @@ -173,7 +173,7 @@ public InlineArrayType(ModuleDesc owningModule, MetadataType elementType, uint l public override ClassLayoutMetadata GetClassLayout() { - ClassLayoutMetadata result = new ClassLayoutMetadata(); + ClassLayoutMetadata result = default(ClassLayoutMetadata); result.PackingSize = 0; result.Size = checked((int)Length * ElementType.GetElementSize().AsInt); return result; @@ -329,7 +329,7 @@ public override string Name { return "get_Item"; } - else + else { return "set_Item"; } @@ -352,9 +352,9 @@ public override MethodSignature Signature { if (_kind == InlineArrayMethodKind.Getter) { - _signature = new MethodSignature(MethodSignatureFlags.None, - genericParameterCount: 0, - returnType: _owningType.ElementType, + _signature = new MethodSignature(MethodSignatureFlags.None, + genericParameterCount: 0, + returnType: _owningType.ElementType, parameters: new TypeDesc[] { Context.GetWellKnownType(WellKnownType.Int32) }); } else @@ -373,10 +373,7 @@ public override MethodIL EmitIL() { var emitter = new ILEmitter(); var codeStream = emitter.NewCodeStream(); - var lIntermediate = emitter.NewCodeLabel(); - var lCheck = emitter.NewCodeLabel(); - var lValid = emitter.NewCodeLabel(); - var vFlag = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Boolean)); + _ = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Boolean)); var elementType = _owningType.ElementType; // Getter: diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.Aot.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.Aot.cs index b047f29e9ec64f..29abb9313ea305 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.Aot.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.Aot.cs @@ -1,8 +1,6 @@ // 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 Internal.IL; using Internal.IL.Stubs; @@ -51,7 +49,7 @@ public static bool IsStructMarshallingRequired(TypeDesc typeDesc) internal static TypeDesc GetNativeMethodParameterType(TypeDesc type, MarshalAsDescriptor marshalAs, InteropStateManager interopStateManager, bool isReturn, bool isAnsi) { MarshallerKind elementMarshallerKind; - MarshallerKind marshallerKind = MarshalHelpers.GetMarshallerKind(type, + MarshallerKind marshallerKind = GetMarshallerKind(type, null, /* parameterIndex */ null, /* customModifierData */ marshalAs, @@ -70,7 +68,7 @@ internal static TypeDesc GetNativeMethodParameterType(TypeDesc type, MarshalAsDe internal static TypeDesc GetNativeStructFieldType(TypeDesc type, MarshalAsDescriptor marshalAs, InteropStateManager interopStateManager, bool isAnsi) { MarshallerKind elementMarshallerKind; - MarshallerKind marshallerKind = MarshalHelpers.GetMarshallerKind(type, + MarshallerKind marshallerKind = GetMarshallerKind(type, null, /* parameterIndex */ null, /* customModifierData */ marshalAs, diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.cs index eac31ec115d9ab..ebcaee6ddfe55a 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using Internal.IL; using Debug = System.Diagnostics.Debug; -using Internal.IL.Stubs; using Internal.TypeSystem.Ecma; namespace Internal.TypeSystem.Interop diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalUtils.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalUtils.cs index 33c609ee23b807..fcc954bc8f9846 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalUtils.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalUtils.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem.Interop { public static class MarshalUtils diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.Aot.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.Aot.cs index c001032f31291b..f35e028ff49fb1 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.Aot.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.Aot.cs @@ -3,7 +3,6 @@ using System; using System.Buffers.Binary; -using System.Runtime.InteropServices; using Internal.IL.Stubs; using Internal.IL; @@ -14,7 +13,7 @@ namespace Internal.TypeSystem.Interop { - partial class Marshaller + internal partial class Marshaller { protected static Marshaller CreateMarshaller(MarshallerKind kind) { @@ -104,7 +103,7 @@ protected static Marshaller CreateMarshaller(MarshallerKind kind) } } - class AnsiCharArrayMarshaller : ArrayMarshaller + internal sealed class AnsiCharArrayMarshaller : ArrayMarshaller { protected override void AllocManagedToNative(ILCodeStream codeStream) { @@ -141,7 +140,7 @@ protected override void TransformNativeToManaged(ILCodeStream codeStream) } } - class AnsiCharMarshaller : Marshaller + internal sealed class AnsiCharMarshaller : Marshaller { protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { @@ -166,7 +165,7 @@ protected override void TransformNativeToManaged(ILCodeStream codeStream) } } - class StringBuilderMarshaller : Marshaller + internal sealed class StringBuilderMarshaller : Marshaller { private bool _isAnsi; public StringBuilderMarshaller(bool isAnsi) @@ -250,7 +249,7 @@ protected override void EmitCleanupManaged(ILCodeStream codeStream) } } - class HandleRefMarshaller : Marshaller + internal sealed class HandleRefMarshaller : Marshaller { protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { @@ -277,7 +276,7 @@ protected override void EmitCleanupManaged(ILCodeStream codeStream) } } - class StructMarshaller : Marshaller + internal sealed class StructMarshaller : Marshaller { protected override void AllocManagedToNative(ILCodeStream codeStream) { @@ -315,7 +314,7 @@ protected override void EmitCleanupManaged(ILCodeStream codeStream) } } - class ByValArrayMarshaller : ArrayMarshaller + internal class ByValArrayMarshaller : ArrayMarshaller { protected FieldDesc _managedField; protected FieldDesc _nativeField; @@ -542,11 +541,10 @@ protected override void EmitMarshalFieldNativeToManaged() } } - abstract class ByValStringMarshaller : ByValArrayMarshaller + internal abstract class ByValStringMarshaller : ByValArrayMarshaller { protected override void EmitElementCount(ILCodeStream codeStream, MarshalDirection direction) { - ILEmitter emitter = _ilCodeStreams.Emitter; if (MarshalAsDescriptor == null || !MarshalAsDescriptor.SizeConst.HasValue) { throw new InvalidProgramException("SizeConst is required for ByValString."); @@ -608,7 +606,7 @@ protected override void EmitMarshalFieldNativeToManaged() } } - class ByValAnsiStringMarshaller : ByValStringMarshaller + internal sealed class ByValAnsiStringMarshaller : ByValStringMarshaller { protected override bool IsAnsi { @@ -629,7 +627,7 @@ protected override MethodDesc GetNativeToManagedHelper() } } - class ByValUnicodeStringMarshaller : ByValStringMarshaller + internal sealed class ByValUnicodeStringMarshaller : ByValStringMarshaller { protected override bool IsAnsi { @@ -650,7 +648,7 @@ protected override MethodDesc GetNativeToManagedHelper() } } - class LayoutClassMarshaler : Marshaller + internal sealed class LayoutClassMarshaler : Marshaller { protected override void AllocManagedToNative(ILCodeStream codeStream) { @@ -710,7 +708,7 @@ protected override void EmitCleanupManaged(ILCodeStream codeStream) } } - class LayoutClassPtrMarshaller : Marshaller + internal sealed class LayoutClassPtrMarshaller : Marshaller { protected override void AllocManagedToNative(ILCodeStream codeStream) { @@ -801,7 +799,7 @@ protected override void EmitCleanupManaged(ILCodeStream codeStream) } } - class AsAnyMarshaller : Marshaller + internal sealed class AsAnyMarshaller : Marshaller { // This flag affects encoding of string, StringBuilder and Char array marshalling. // It does not affect LayoutClass marshalling. @@ -893,7 +891,7 @@ protected override void EmitCleanupManaged(ILCodeStream codeStream) } } - class ComInterfaceMarshaller : Marshaller + internal sealed class ComInterfaceMarshaller : Marshaller { protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { @@ -965,7 +963,7 @@ protected override void TransformManagedToNative(ILCodeStream codeStream) } } - class AnsiBSTRStringMarshaller : Marshaller + internal sealed class AnsiBSTRStringMarshaller : Marshaller { internal override bool CleanupRequired => true; @@ -998,7 +996,7 @@ protected override void TransformNativeToManaged(ILCodeStream codeStream) } } - class BSTRStringMarshaller : Marshaller + internal sealed class BSTRStringMarshaller : Marshaller { internal override bool CleanupRequired => true; @@ -1031,7 +1029,7 @@ protected override void TransformNativeToManaged(ILCodeStream codeStream) } } - class OleDateTimeMarshaller : Marshaller + internal sealed class OleDateTimeMarshaller : Marshaller { protected override void TransformManagedToNative(ILCodeStream codeStream) { @@ -1056,7 +1054,7 @@ protected override void TransformNativeToManaged(ILCodeStream codeStream) } } - class OleCurrencyMarshaller : Marshaller + internal sealed class OleCurrencyMarshaller : Marshaller { protected override void TransformManagedToNative(ILCodeStream codeStream) { @@ -1081,7 +1079,7 @@ protected override void TransformNativeToManaged(ILCodeStream codeStream) } } - class FailedTypeLoadMarshaller : Marshaller + internal sealed class FailedTypeLoadMarshaller : Marshaller { protected override void TransformManagedToNative(ILCodeStream codeStream) { @@ -1094,7 +1092,7 @@ protected override void TransformNativeToManaged(ILCodeStream codeStream) } } - class VariantMarshaller : Marshaller + internal sealed class VariantMarshaller : Marshaller { protected override void AllocManagedToNative(ILCodeStream codeStream) { @@ -1150,8 +1148,9 @@ protected override void EmitCleanupManaged(ILCodeStream codeStream) codeStream.Emit(ILOpcode.call, emitter.NewToken(helper)); } } - - class CustomTypeMarshaller : Marshaller +#pragma warning disable CA1852 + internal class CustomTypeMarshaller : Marshaller +#pragma warning restore CA1852 { private ILLocalVariable MarshallerLocalVariable = (ILLocalVariable)(-1); @@ -1283,7 +1282,7 @@ protected void EmitCleanUpNativeData(ILCodeStream codeStream) } } - class BlittableValueClassByRefReturn : Marshaller + internal sealed class BlittableValueClassByRefReturn : Marshaller { protected override void SetupArgumentsForReturnValueMarshalling() { diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.cs index 06d839390d1f83..a7d62d1c422f23 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.cs @@ -20,7 +20,7 @@ public enum MarshalDirection // Each type of marshaller knows how to generate the marshalling code for the argument it marshals. // Marshallers contain method related marshalling information (which is common to all the Marshallers) // and also argument specific marshalling information. - abstract partial class Marshaller + internal abstract partial class Marshaller { #region Instance state information public TypeSystemContext Context; @@ -111,7 +111,7 @@ internal virtual bool CleanupRequired protected Home _nativeHome; #endregion - enum HomeType + private enum HomeType { Arg, Local, @@ -122,7 +122,7 @@ enum HomeType /// /// Abstraction for handling by-ref and non-by-ref locals/arguments /// - internal class Home + internal sealed class Home { public Home(ILLocalVariable var, TypeDesc type, bool isByRef) { @@ -203,10 +203,10 @@ public void StoreValue(ILCodeStream stream) } } - HomeType _homeType; - TypeDesc _type; - ILLocalVariable _var; - int _argIndex; + private HomeType _homeType; + private TypeDesc _type; + private ILLocalVariable _var; + private int _argIndex; } #region Creation of marshallers @@ -489,7 +489,6 @@ protected virtual void EmitReverseFieldMarshallingIL() protected virtual void EmitMarshalReturnValueManagedToNative() { - ILEmitter emitter = _ilCodeStreams.Emitter; SetupArgumentsForReturnValueMarshalling(); StoreNativeValue(_ilCodeStreams.ReturnValueMarshallingCodeStream); @@ -757,7 +756,6 @@ protected virtual void EmitCleanupManaged(ILCodeStream codeStream) protected virtual void EmitMarshalReturnValueNativeToManaged() { - ILEmitter emitter = _ilCodeStreams.Emitter; SetupArgumentsForReturnValueMarshalling(); StoreManagedValue(_ilCodeStreams.ReturnValueMarshallingCodeStream); @@ -805,7 +803,6 @@ protected virtual void EmitMarshalArgumentNativeToManaged() protected virtual void EmitMarshalElementManagedToNative() { - ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.MarshallingCodeStream; Debug.Assert(codeStream != null); @@ -821,7 +818,6 @@ protected virtual void EmitMarshalElementManagedToNative() protected virtual void EmitMarshalElementNativeToManaged() { - ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.MarshallingCodeStream; Debug.Assert(codeStream != null); @@ -836,7 +832,6 @@ protected virtual void EmitMarshalElementNativeToManaged() protected virtual void EmitMarshalFieldManagedToNative() { - ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream marshallingCodeStream = _ilCodeStreams.MarshallingCodeStream; SetupArgumentsForFieldMarshalling(); @@ -854,7 +849,6 @@ protected virtual void EmitMarshalFieldManagedToNative() protected virtual void EmitMarshalFieldNativeToManaged() { - ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.MarshallingCodeStream; SetupArgumentsForFieldMarshalling(); @@ -879,7 +873,7 @@ internal virtual void EmitElementCleanup(ILCodeStream codestream, ILEmitter emit } } - class NotSupportedMarshaller : Marshaller + internal sealed class NotSupportedMarshaller : Marshaller { public override void EmitMarshallingIL(PInvokeILCodeStreams pInvokeILCodeStreams) { @@ -887,7 +881,7 @@ public override void EmitMarshallingIL(PInvokeILCodeStreams pInvokeILCodeStreams } } - class VoidReturnMarshaller : Marshaller + internal sealed class VoidReturnMarshaller : Marshaller { protected override void EmitMarshalReturnValueManagedToNative() { @@ -901,7 +895,7 @@ public override void LoadReturnValue(ILCodeStream codeStream) } } - class BlittableValueMarshaller : Marshaller + internal sealed class BlittableValueMarshaller : Marshaller { protected override void EmitMarshalArgumentManagedToNative() { @@ -944,7 +938,7 @@ protected override void EmitMarshalArgumentNativeToManaged() } } - class BlittableStructPtrMarshaller : Marshaller + internal sealed class BlittableStructPtrMarshaller : Marshaller { protected override void TransformManagedToNative(ILCodeStream codeStream) { @@ -967,7 +961,7 @@ protected override void TransformNativeToManaged(ILCodeStream codeStream) } } - class ArrayMarshaller : Marshaller + internal class ArrayMarshaller : Marshaller { private Marshaller _elementMarshaller; @@ -1039,8 +1033,8 @@ protected virtual void EmitElementCount(ILCodeStream codeStream, MarshalDirectio else { - uint? sizeParamIndex = MarshalAsDescriptor != null ? MarshalAsDescriptor.SizeParamIndex : null; - uint? sizeConst = MarshalAsDescriptor != null ? MarshalAsDescriptor.SizeConst : null; + uint? sizeParamIndex = MarshalAsDescriptor?.SizeParamIndex; + uint? sizeConst = MarshalAsDescriptor?.SizeConst; if (sizeConst.HasValue) { @@ -1350,7 +1344,7 @@ protected override void EmitCleanupManaged(ILCodeStream codeStream) } } - class BlittableArrayMarshaller : ArrayMarshaller + internal sealed class BlittableArrayMarshaller : ArrayMarshaller { protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { @@ -1419,7 +1413,7 @@ protected override void EmitCleanupManaged(ILCodeStream codeStream) } } - class BooleanMarshaller : Marshaller + internal sealed class BooleanMarshaller : Marshaller { private int _trueValue; public BooleanMarshaller(int trueValue = 1) @@ -1467,7 +1461,7 @@ protected override void AllocAndTransformNativeToManaged(ILCodeStream codeStream } } - class UnicodeStringMarshaller : Marshaller + internal sealed class UnicodeStringMarshaller : Marshaller { private bool ShouldBePinned { @@ -1587,7 +1581,7 @@ protected override void EmitCleanupManaged(ILCodeStream codeStream) } } - class AnsiStringMarshaller : Marshaller + internal sealed class AnsiStringMarshaller : Marshaller { internal override bool CleanupRequired @@ -1648,11 +1642,11 @@ protected override void EmitCleanupManaged(ILCodeStream codeStream) } } - class UTF8StringMarshaller : Marshaller + internal sealed class UTF8StringMarshaller : Marshaller { private const int LocalBufferLength = 0x100; - private ILLocalVariable? _marshallerInstance = null; + private ILLocalVariable? _marshallerInstance; private MetadataType Marshaller => Context.SystemModule.GetKnownType("System.Runtime.InteropServices.Marshalling", "Utf8StringMarshaller"); @@ -1680,8 +1674,7 @@ protected override void TransformManagedToNative(ILCodeStream codeStream) { TypeDesc marshallerIn = MarshallerIn; - if (_marshallerInstance == null) - _marshallerInstance = emitter.NewLocal(marshallerIn); + _marshallerInstance ??= emitter.NewLocal(marshallerIn); var vBuffer = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); codeStream.EmitLdc(LocalBufferLength); @@ -1744,7 +1737,7 @@ protected override void EmitCleanupManaged(ILCodeStream codeStream) } } - class SafeHandleMarshaller : Marshaller + internal sealed class SafeHandleMarshaller : Marshaller { private void AllocSafeHandle(ILCodeStream codeStream) { @@ -1787,7 +1780,6 @@ protected override void EmitMarshalArgumentManagedToNative() ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream marshallingCodeStream = _ilCodeStreams.MarshallingCodeStream; ILCodeStream callsiteCodeStream = _ilCodeStreams.CallsiteSetupCodeStream; - ILCodeStream unmarshallingCodeStream = _ilCodeStreams.UnmarshallingCodestream; ILCodeStream cleanupCodeStream = _ilCodeStreams.CleanupCodeStream; SetupArguments(); @@ -1905,7 +1897,7 @@ protected override void EmitMarshalFieldNativeToManaged() } } - class DelegateMarshaller : Marshaller + internal sealed class DelegateMarshaller : Marshaller { protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshallerKind.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshallerKind.cs index 65f9e979e76f28..b1ff401809e28b 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshallerKind.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshallerKind.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem.Interop { - enum MarshallerKind + internal enum MarshallerKind { Unknown, BlittableValue, diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.Mangling.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.Mangling.cs index fe3edc156824a6..c209aebdec5528 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.Mangling.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.Mangling.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem.Interop { - partial class NativeStructType : IPrefixMangledType + public partial class NativeStructType : IPrefixMangledType { TypeDesc IPrefixMangledType.BaseType => ManagedStructType; diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.Sorting.cs index e66dc55d975c01..1796d26e60782a 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem.Interop { // Functionality related to deterministic ordering of types - partial class NativeStructType + public partial class NativeStructType { protected override int ClassCode => -377751537; @@ -13,7 +13,7 @@ protected override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer return comparer.Compare(ManagedStructType, ((NativeStructType)other).ManagedStructType); } - partial class NativeStructField + private sealed partial class NativeStructField { protected override int ClassCode => 1580219745; diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.cs index 477d5c8168b542..9f5ee9edcb96fd 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/NativeStructType.cs @@ -161,7 +161,7 @@ public FieldDesc[] Fields } [ThreadStatic] - static Stack s_typesBeingLookedAt; + private static Stack s_typesBeingLookedAt; public NativeStructType(ModuleDesc owningModule, MetadataType managedStructType, InteropStateManager interopStateManager) { @@ -190,7 +190,6 @@ public NativeStructType(ModuleDesc owningModule, MetadataType managedStructType, private void CalculateFields() { - bool isSequential = ManagedStructType.IsSequentialLayout; bool isAnsi = ManagedStructType.PInvokeStringFormat == PInvokeStringFormat.AnsiClass; int numFields = 0; diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Mangling.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Mangling.cs index ab66c754f58b08..9ebfc462f9655b 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Mangling.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Mangling.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem.Interop { - partial class PInvokeDelegateWrapper : IPrefixMangledType + public partial class PInvokeDelegateWrapper : IPrefixMangledType { TypeDesc IPrefixMangledType.BaseType { diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Sorting.cs index c62bc7675e5afd..0611936fca4192 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem.Interop { // Functionality related to deterministic ordering of types - partial class PInvokeDelegateWrapper + public partial class PInvokeDelegateWrapper { protected override int ClassCode => -262930217; diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.cs index dcc2fbff41c065..c7577641566001 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapper.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using Internal.IL; using Internal.IL.Stubs; using Debug = System.Diagnostics.Debug; using System.Threading; @@ -154,7 +153,7 @@ public PInvokeDelegateWrapper(ModuleDesc owningModule, MetadataType delegateType Debug.Assert(delegateType.IsDelegate); Module = owningModule; - DelegateType = delegateType; + DelegateType = delegateType; _interopStateManager = interopStateManager; } @@ -238,7 +237,7 @@ private void InitializeMethods() { MethodDesc[] methods = new MethodDesc[] { new PInvokeDelegateWrapperConstructor(this), // Constructor - new DelegateMarshallingMethodThunk(DelegateType, this, _interopStateManager, + new DelegateMarshallingMethodThunk(DelegateType, this, _interopStateManager, DelegateMarshallingMethodThunkKind.ForwardNativeFunctionWrapper) // a forward marshalling instance method }; diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.Sorting.cs index 5fe9290213b2f6..d5b75a170e379d 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem.Interop { // Functionality related to deterministic ordering of methods - partial class PInvokeDelegateWrapperConstructor + public partial class PInvokeDelegateWrapperConstructor { protected override int ClassCode => 1000342011; diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.cs index 2e138f6098c7ff..10727fac2b4b8e 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/PInvokeDelegateWrapperConstructor.cs @@ -1,12 +1,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; -using System.Collections.Generic; using Internal.IL; using Internal.IL.Stubs; -using Debug = System.Diagnostics.Debug; -using System.Threading; namespace Internal.TypeSystem.Interop { @@ -46,15 +42,12 @@ public override MethodSignature Signature { get { - if (_signature == null) - { - _signature = new MethodSignature(MethodSignatureFlags.None, + _signature ??= new MethodSignature(MethodSignatureFlags.None, genericParameterCount: 0, returnType: Context.GetWellKnownType(WellKnownType.Void), parameters: new TypeDesc[] { Context.GetWellKnownType(WellKnownType.IntPtr) }); - } return _signature; } } diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/InteropStateManager.cs b/src/coreclr/tools/Common/TypeSystem/Interop/InteropStateManager.cs index f149f08dc449e4..f8a3ea39640662 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/InteropStateManager.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/InteropStateManager.cs @@ -1,7 +1,6 @@ // 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 Internal.IL.Stubs; using Internal.TypeSystem.Interop; using Debug = System.Diagnostics.Debug; @@ -195,7 +194,7 @@ public MethodDesc GetPInvokeCalliStub(MethodSignature signature, ModuleDesc modu return _pInvokeCalliHashtable.GetOrCreateValue(new CalliMarshallingMethodThunkKey(normalizedSignatureBuilder.ToSignature(), MarshalHelpers.IsRuntimeMarshallingEnabled(moduleContext))); } - private class NativeStructTypeHashtable : LockFreeReaderHashtable + private sealed class NativeStructTypeHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(MetadataType key) { @@ -209,12 +208,12 @@ protected override int GetValueHashCode(NativeStructType value) protected override bool CompareKeyToValue(MetadataType key, NativeStructType value) { - return Object.ReferenceEquals(key, value.ManagedStructType); + return ReferenceEquals(key, value.ManagedStructType); } protected override bool CompareValueToValue(NativeStructType value1, NativeStructType value2) { - return Object.ReferenceEquals(value1.ManagedStructType, value2.ManagedStructType); + return ReferenceEquals(value1.ManagedStructType, value2.ManagedStructType); } protected override NativeStructType CreateValueFromKey(MetadataType key) @@ -244,7 +243,7 @@ public StructMarshallingThunkKey(MetadataType type, StructMarshallingThunkType t } } - private class StructMarshallingThunkHashTable : LockFreeReaderHashtable + private sealed class StructMarshallingThunkHashTable : LockFreeReaderHashtable { protected override int GetKeyHashCode(StructMarshallingThunkKey key) { @@ -258,13 +257,13 @@ protected override int GetValueHashCode(StructMarshallingThunk value) protected override bool CompareKeyToValue(StructMarshallingThunkKey key, StructMarshallingThunk value) { - return Object.ReferenceEquals(key.ManagedType, value.ManagedType) && + return ReferenceEquals(key.ManagedType, value.ManagedType) && key.ThunkType == value.ThunkType; } protected override bool CompareValueToValue(StructMarshallingThunk value1, StructMarshallingThunk value2) { - return Object.ReferenceEquals(value1.ManagedType, value2.ManagedType) && + return ReferenceEquals(value1.ManagedType, value2.ManagedType) && value1.ThunkType == value2.ThunkType; } @@ -283,7 +282,7 @@ public StructMarshallingThunkHashTable(InteropStateManager interopStateManager, } } - private class InlineArrayHashTable : LockFreeReaderHashtable + private sealed class InlineArrayHashTable : LockFreeReaderHashtable { protected override int GetKeyHashCode(InlineArrayCandidate key) { @@ -297,13 +296,13 @@ protected override int GetValueHashCode(InlineArrayType value) protected override bool CompareKeyToValue(InlineArrayCandidate key, InlineArrayType value) { - return Object.ReferenceEquals(key.ElementType, value.ElementType) && + return ReferenceEquals(key.ElementType, value.ElementType) && key.Length == value.Length; } protected override bool CompareValueToValue(InlineArrayType value1, InlineArrayType value2) { - return Object.ReferenceEquals(value1.ElementType, value2.ElementType) && + return ReferenceEquals(value1.ElementType, value2.ElementType) && value1.Length == value2.Length; } @@ -333,7 +332,7 @@ public DelegateMarshallingStubHashtableKey(MetadataType type, DelegateMarshallin Kind = kind; } } - private class DelegateMarshallingStubHashtable : LockFreeReaderHashtable + private sealed class DelegateMarshallingStubHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(DelegateMarshallingStubHashtableKey key) { @@ -347,13 +346,13 @@ protected override int GetValueHashCode(DelegateMarshallingMethodThunk value) protected override bool CompareKeyToValue(DelegateMarshallingStubHashtableKey key, DelegateMarshallingMethodThunk value) { - return Object.ReferenceEquals(key.DelegateType, value.DelegateType) && + return ReferenceEquals(key.DelegateType, value.DelegateType) && key.Kind== value.Kind; } protected override bool CompareValueToValue(DelegateMarshallingMethodThunk value1, DelegateMarshallingMethodThunk value2) { - return Object.ReferenceEquals(value1.DelegateType, value2.DelegateType) && + return ReferenceEquals(value1.DelegateType, value2.DelegateType) && value1.Kind== value2.Kind; } @@ -373,7 +372,7 @@ public DelegateMarshallingStubHashtable(InteropStateManager interopStateManager, } } - private class ForwardDelegateCreationStubHashtable : LockFreeReaderHashtable + private sealed class ForwardDelegateCreationStubHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(MetadataType key) { @@ -387,12 +386,12 @@ protected override int GetValueHashCode(ForwardDelegateCreationThunk value) protected override bool CompareKeyToValue(MetadataType key, ForwardDelegateCreationThunk value) { - return Object.ReferenceEquals(key, value.DelegateType); + return ReferenceEquals(key, value.DelegateType); } protected override bool CompareValueToValue(ForwardDelegateCreationThunk value1, ForwardDelegateCreationThunk value2) { - return Object.ReferenceEquals(value1.DelegateType, value2.DelegateType); + return ReferenceEquals(value1.DelegateType, value2.DelegateType); } protected override ForwardDelegateCreationThunk CreateValueFromKey(MetadataType key) @@ -410,7 +409,7 @@ public ForwardDelegateCreationStubHashtable(InteropStateManager interopStateMana } } - private class PInvokeDelegateWrapperHashtable : LockFreeReaderHashtable + private sealed class PInvokeDelegateWrapperHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(MetadataType key) { @@ -424,12 +423,12 @@ protected override int GetValueHashCode(PInvokeDelegateWrapper value) protected override bool CompareKeyToValue(MetadataType key, PInvokeDelegateWrapper value) { - return Object.ReferenceEquals(key, value.DelegateType); + return ReferenceEquals(key, value.DelegateType); } protected override bool CompareValueToValue(PInvokeDelegateWrapper value1, PInvokeDelegateWrapper value2) { - return Object.ReferenceEquals(value1.DelegateType, value2.DelegateType); + return ReferenceEquals(value1.DelegateType, value2.DelegateType); } protected override PInvokeDelegateWrapper CreateValueFromKey(MetadataType key) @@ -447,7 +446,7 @@ public PInvokeDelegateWrapperHashtable(InteropStateManager interopStateManager, } } - private class PInvokeLazyFixupFieldHashtable : LockFreeReaderHashtable + private sealed class PInvokeLazyFixupFieldHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(MethodDesc key) { @@ -484,7 +483,7 @@ public PInvokeLazyFixupFieldHashtable(DefType owningType) private readonly record struct CalliMarshallingMethodThunkKey(MethodSignature Signature, bool RuntimeMarshallingEnabled); - private class PInvokeCalliHashtable : LockFreeReaderHashtable + private sealed class PInvokeCalliHashtable : LockFreeReaderHashtable { private readonly InteropStateManager _interopStateManager; private readonly TypeDesc _owningType; diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/InteropTypes.cs b/src/coreclr/tools/Common/TypeSystem/Interop/InteropTypes.cs index f69879a10ee15f..8bbdb13630bfe3 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/InteropTypes.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/InteropTypes.cs @@ -3,8 +3,6 @@ using Internal.IL; -using Debug = System.Diagnostics.Debug; - namespace Internal.TypeSystem.Interop { public static class InteropTypes diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/MarshalAsDescriptor.cs b/src/coreclr/tools/Common/TypeSystem/Interop/MarshalAsDescriptor.cs index c76e2cf469350d..39ecc973755e17 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/MarshalAsDescriptor.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/MarshalAsDescriptor.cs @@ -1,8 +1,6 @@ // 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; -using System; using System.Diagnostics; namespace Internal.TypeSystem diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/MetadataType.Interop.cs b/src/coreclr/tools/Common/TypeSystem/Interop/MetadataType.Interop.cs index eeed1cc9343d98..10e3bbeeb18354 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/MetadataType.Interop.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/MetadataType.Interop.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem { public enum PInvokeStringFormat diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/MethodDelegator.Interop.cs b/src/coreclr/tools/Common/TypeSystem/Interop/MethodDelegator.Interop.cs index 47291cd62bc63d..d9919796639e2f 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/MethodDelegator.Interop.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/MethodDelegator.Interop.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class MethodDelegator + public partial class MethodDelegator { public override bool IsPInvoke => _wrappedMethod.IsPInvoke; diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/MethodDesc.Interop.cs b/src/coreclr/tools/Common/TypeSystem/Interop/MethodDesc.Interop.cs index c49c654423a7e3..39e7e751bbc8a4 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/MethodDesc.Interop.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/MethodDesc.Interop.cs @@ -7,7 +7,7 @@ namespace Internal.TypeSystem { // Additional extensions to MethodDesc related to interop - partial class MethodDesc + public partial class MethodDesc { /// /// Gets a value indicating whether this method is a (native unmanaged) platform invoke. @@ -350,7 +350,7 @@ public PInvokeMetadata(string module, string entrypoint, PInvokeFlags flags) } } - partial class InstantiatedMethod + public partial class InstantiatedMethod { public override ParameterMetadata[] GetParameterMetadata() { @@ -358,7 +358,7 @@ public override ParameterMetadata[] GetParameterMetadata() } } - partial class MethodForInstantiatedType + public partial class MethodForInstantiatedType { public override ParameterMetadata[] GetParameterMetadata() { diff --git a/src/coreclr/tools/Common/TypeSystem/MetadataEmitter/TypeSystemMetadataEmitter.cs b/src/coreclr/tools/Common/TypeSystem/MetadataEmitter/TypeSystemMetadataEmitter.cs index 8e0a9272392cfb..8499fa23d80464 100644 --- a/src/coreclr/tools/Common/TypeSystem/MetadataEmitter/TypeSystemMetadataEmitter.cs +++ b/src/coreclr/tools/Common/TypeSystem/MetadataEmitter/TypeSystemMetadataEmitter.cs @@ -9,22 +9,23 @@ using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; -using Internal.TypeSystem; namespace Internal.TypeSystem { - class TypeSystemMetadataEmitter +#pragma warning disable CA1852 + internal class TypeSystemMetadataEmitter +#pragma warning restore CA1852 { - MetadataBuilder _metadataBuilder; - BlobBuilder _ilBuilder; - MethodBodyStreamEncoder _methodBodyStream; - Dictionary _assemblyRefNameHandles = new Dictionary(); - Dictionary _assemblyRefs = new Dictionary(); - Dictionary _typeRefs = new Dictionary(); - Dictionary _methodRefs = new Dictionary(); - Dictionary _fieldRefs = new Dictionary(); - Blob _mvidFixup; - BlobHandle _noArgsVoidReturnStaticMethodSigHandle; + private MetadataBuilder _metadataBuilder; + private BlobBuilder _ilBuilder; + private MethodBodyStreamEncoder _methodBodyStream; + private Dictionary _assemblyRefNameHandles = new Dictionary(); + private Dictionary _assemblyRefs = new Dictionary(); + private Dictionary _typeRefs = new Dictionary(); + private Dictionary _methodRefs = new Dictionary(); + private Dictionary _fieldRefs = new Dictionary(); + private Blob _mvidFixup; + private BlobHandle _noArgsVoidReturnStaticMethodSigHandle; protected TypeSystemContext _typeSystemContext; public TypeSystemMetadataEmitter(AssemblyName assemblyName, TypeSystemContext context, AssemblyFlags flags = default(AssemblyFlags), byte[] publicKeyArray = null, AssemblyHashAlgorithm hashAlgorithm = AssemblyHashAlgorithm.None) @@ -41,7 +42,7 @@ class TypeSystemMetadataEmitter _mvidFixup = mvid.Content; _metadataBuilder.AddModule(0, assemblyNameHandle, mvid.Handle, default(GuidHandle), default(GuidHandle)); - _metadataBuilder.AddAssembly(assemblyNameHandle, assemblyName.Version ?? new Version(0,0,0,0), default(StringHandle), publicKey: publicKeyArray != null ? _metadataBuilder.GetOrAddBlob(publicKeyArray) : default(BlobHandle), flags, AssemblyHashAlgorithm.None); + _metadataBuilder.AddAssembly(assemblyNameHandle, assemblyName.Version ?? new Version(0, 0, 0, 0), default(StringHandle), publicKey: publicKeyArray != null ? _metadataBuilder.GetOrAddBlob(publicKeyArray) : default(BlobHandle), flags, AssemblyHashAlgorithm.None); _metadataBuilder.AddTypeDefinition( default(TypeAttributes), @@ -167,7 +168,7 @@ public EntityHandle EmitMetadataHandleForTypeSystemEntity(TypeSystemEntity entit throw new NotSupportedException(); } } - + public IEnumerable> TypeSystemEntitiesKnown { get @@ -264,7 +265,6 @@ private BlobHandle GetMethodSignatureBlobHandle(MethodSignature sig) private BlobHandle GetFieldSignatureBlobHandle(FieldDesc field) { - var fieldDef = field.GetTypicalFieldDefinition(); var embeddedSigData = field.GetEmbeddedSignatureData(); EmbeddedSignatureDataEmitter signatureDataEmitter; if (embeddedSigData != null && embeddedSigData.Length != 0) @@ -455,9 +455,8 @@ private void EncodeType(BlobBuilder blobBuilder, TypeDesc type, EmbeddedSignatur { blobBuilder.WriteByte((byte)SignatureTypeCode.Void); } - else if (type is SignatureVariable) + else if (type is SignatureVariable sigVar) { - SignatureVariable sigVar = (SignatureVariable)type; SignatureTypeCode code = sigVar.IsMethodSignatureVariable ? SignatureTypeCode.GenericMethodParameter : SignatureTypeCode.GenericTypeParameter; blobBuilder.WriteByte((byte)code); blobBuilder.WriteCompressedInteger(sigVar.Index); @@ -470,9 +469,8 @@ private void EncodeType(BlobBuilder blobBuilder, TypeDesc type, EmbeddedSignatur foreach (var instantiationArg in type.Instantiation) EncodeType(blobBuilder, instantiationArg, signatureDataEmitter); } - else if (type is MetadataType) + else if (type is MetadataType metadataType) { - var metadataType = (MetadataType)type; // Must be class or valuetype blobBuilder.WriteByte(type.IsValueType ? (byte)SignatureTypeKind.ValueType : (byte)SignatureTypeKind.Class); int codedIndex = CodedIndex.TypeDefOrRef(GetTypeRef(metadataType)); @@ -486,12 +484,12 @@ private void EncodeType(BlobBuilder blobBuilder, TypeDesc type, EmbeddedSignatur signatureDataEmitter.Pop(); } - class EmbeddedSignatureDataEmitter + private sealed class EmbeddedSignatureDataEmitter { - EmbeddedSignatureData[] _embeddedData; - int _embeddedDataIndex; - Stack _indexStack = new Stack(); - TypeSystemMetadataEmitter _metadataEmitter; + private EmbeddedSignatureData[] _embeddedData; + private int _embeddedDataIndex; + private Stack _indexStack = new Stack(); + private TypeSystemMetadataEmitter _metadataEmitter; public static EmbeddedSignatureDataEmitter EmptySingleton = new EmbeddedSignatureDataEmitter(null, null); @@ -536,11 +534,11 @@ public void EmitArrayShapeAtCurrentIndexStack(BlobBuilder signatureBuilder, int for (int i = 0; i < boundsStr.Length; i++) { - bounds[i] = Int32.Parse(boundsStr[i]); + bounds[i] = int.Parse(boundsStr[i]); } for (int i = 0; i < loBoundsStr.Length; i++) { - loBounds[i] = Int32.Parse(loBoundsStr[i]); + loBounds[i] = int.Parse(loBoundsStr[i]); } shapeEncoder.Shape(rank, ImmutableArray.Create(bounds), ImmutableArray.Create(loBounds)); @@ -636,7 +634,7 @@ public void Pop() } } - void EncodeMethodSignature(BlobBuilder signatureBuilder, MethodSignature sig, EmbeddedSignatureDataEmitter signatureDataEmitter) + private void EncodeMethodSignature(BlobBuilder signatureBuilder, MethodSignature sig, EmbeddedSignatureDataEmitter signatureDataEmitter) { signatureDataEmitter.Push(); BlobEncoder signatureEncoder = new BlobEncoder(signatureBuilder); @@ -672,7 +670,7 @@ void EncodeMethodSignature(BlobBuilder signatureBuilder, MethodSignature sig, Em signatureDataEmitter.Pop(); } - void EncodeFieldSignature(BlobBuilder signatureBuilder, TypeDesc fieldType, EmbeddedSignatureDataEmitter signatureDataEmitter) + private void EncodeFieldSignature(BlobBuilder signatureBuilder, TypeDesc fieldType, EmbeddedSignatureDataEmitter signatureDataEmitter) { signatureDataEmitter.Push(); BlobEncoder signatureEncoder = new BlobEncoder(signatureBuilder); diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/ArrayType.RuntimeDetermined.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/ArrayType.RuntimeDetermined.cs index 2e05f1b87f2ba5..5da5d7f03133d7 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/ArrayType.RuntimeDetermined.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/ArrayType.RuntimeDetermined.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class ArrayType + public partial class ArrayType { public override TypeDesc GetNonRuntimeDeterminedTypeFromRuntimeDeterminedSubtypeViaSubstitution(Instantiation typeInstantiation, Instantiation methodInstantiation) { @@ -17,7 +17,7 @@ public override TypeDesc GetNonRuntimeDeterminedTypeFromRuntimeDeterminedSubtype } } - partial class ArrayMethod + public partial class ArrayMethod { public override MethodDesc GetNonRuntimeDeterminedMethodFromRuntimeDeterminedMethodViaSubstitution(Instantiation typeInstantiation, Instantiation methodInstantiation) { diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/ByRefType.RuntimeDetermined.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/ByRefType.RuntimeDetermined.cs index 21b4b9a3b067c6..8f3426cf753bc4 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/ByRefType.RuntimeDetermined.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/ByRefType.RuntimeDetermined.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class ByRefType + public partial class ByRefType { public override TypeDesc GetNonRuntimeDeterminedTypeFromRuntimeDeterminedSubtypeViaSubstitution(Instantiation typeInstantiation, Instantiation methodInstantiation) { diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/DefType.RuntimeDetermined.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/DefType.RuntimeDetermined.cs index 81d24031df36d1..62799f6ba6145b 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/DefType.RuntimeDetermined.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/DefType.RuntimeDetermined.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class DefType + public partial class DefType { public override bool IsRuntimeDeterminedSubtype { diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/FieldDesc.RuntimeDetermined.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/FieldDesc.RuntimeDetermined.cs index 748ea1d87720bc..f1bf0d968189ed 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/FieldDesc.RuntimeDetermined.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/FieldDesc.RuntimeDetermined.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class FieldDesc + public partial class FieldDesc { public FieldDesc GetNonRuntimeDeterminedFieldFromRuntimeDeterminedFieldViaSubstitution(Instantiation typeInstantiation, Instantiation methodInstantiation) { diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/FunctionPointerType.RuntimeDetermined.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/FunctionPointerType.RuntimeDetermined.cs index 64767657f56b05..5f2d9b5c8af017 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/FunctionPointerType.RuntimeDetermined.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/FunctionPointerType.RuntimeDetermined.cs @@ -5,7 +5,7 @@ namespace Internal.TypeSystem { - partial class FunctionPointerType + public partial class FunctionPointerType { public override bool IsRuntimeDeterminedSubtype { diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/GenericParameterDesc.RuntimeDetermined.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/GenericParameterDesc.RuntimeDetermined.cs index e2abaf141c4843..d6540d7ae40764 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/GenericParameterDesc.RuntimeDetermined.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/GenericParameterDesc.RuntimeDetermined.cs @@ -5,7 +5,7 @@ namespace Internal.TypeSystem { - partial class GenericParameterDesc + public partial class GenericParameterDesc { public sealed override bool IsRuntimeDeterminedSubtype { diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodDesc.RuntimeDetermined.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodDesc.RuntimeDetermined.cs index 909c73465d841e..2a66359448f0a4 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodDesc.RuntimeDetermined.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodDesc.RuntimeDetermined.cs @@ -1,11 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Debug = System.Diagnostics.Debug; - namespace Internal.TypeSystem { - partial class MethodDesc + public partial class MethodDesc { /// /// Gets the shared runtime determined form of the method. This is a canonical form of the method diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodForRuntimeDeterminedType.Diagnostic.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodForRuntimeDeterminedType.Diagnostic.cs index aca586c0c1517b..40047e9c6ab334 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodForRuntimeDeterminedType.Diagnostic.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodForRuntimeDeterminedType.Diagnostic.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class MethodForRuntimeDeterminedType + public partial class MethodForRuntimeDeterminedType { public override string DiagnosticName => _typicalMethodDef.DiagnosticName; } diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodForRuntimeDeterminedType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodForRuntimeDeterminedType.Sorting.cs index 2aeab414f4aad7..2aec790ee00150 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodForRuntimeDeterminedType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodForRuntimeDeterminedType.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types - partial class MethodForRuntimeDeterminedType + public partial class MethodForRuntimeDeterminedType { protected internal override int ClassCode => 719937490; diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodForRuntimeDeterminedType.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodForRuntimeDeterminedType.cs index 24f7ec0eb2d559..d111f8b130af73 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodForRuntimeDeterminedType.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/MethodForRuntimeDeterminedType.cs @@ -1,7 +1,6 @@ // 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; namespace Internal.TypeSystem diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/ParameterizedType.RuntimeDetermined.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/ParameterizedType.RuntimeDetermined.cs index 430e57596c96b4..a241bc7d050183 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/ParameterizedType.RuntimeDetermined.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/ParameterizedType.RuntimeDetermined.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class ParameterizedType + public partial class ParameterizedType { public sealed override bool IsRuntimeDeterminedSubtype { diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/PointerType.RuntimeDetermined.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/PointerType.RuntimeDetermined.cs index ef6c1e6bb061ef..5219e32e4a581e 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/PointerType.RuntimeDetermined.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/PointerType.RuntimeDetermined.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class PointerType + public partial class PointerType { public override TypeDesc GetNonRuntimeDeterminedTypeFromRuntimeDeterminedSubtypeViaSubstitution(Instantiation typeInstantiation, Instantiation methodInstantiation) { diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedCanonicalizationAlgorithm.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedCanonicalizationAlgorithm.cs index a0e7c07778374a..f3b9094e11efef 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedCanonicalizationAlgorithm.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedCanonicalizationAlgorithm.cs @@ -110,7 +110,7 @@ public static TypeDesc ConvertToCanon(TypeDesc typeToConvert, ref CanonicalFormK else if (typeToConvert.IsRuntimeDeterminedType) { // For non-universal canon cases, RuntimeDeterminedType's passed into this function are either - // reference types (which are turned into normal Canon), or instantiated types (which are handled + // reference types (which are turned into normal Canon), or instantiated types (which are handled // by the above case.). But for UniversalCanon, we can have non-instantiated universal canon // which will reach this case. diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedFieldLayoutAlgorithm.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedFieldLayoutAlgorithm.cs index 7dd50f06f34415..55c3bfbd85f029 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedFieldLayoutAlgorithm.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedFieldLayoutAlgorithm.cs @@ -2,9 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections.Generic; - -using Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem { @@ -37,7 +34,7 @@ public override ComputedInstanceFieldLayout ComputeInstanceLayout(DefType defTyp return result; } - public unsafe override ComputedStaticFieldLayout ComputeStaticFieldLayout(DefType defType, StaticLayoutKind layoutKind) + public override unsafe ComputedStaticFieldLayout ComputeStaticFieldLayout(DefType defType, StaticLayoutKind layoutKind) { // Static field layout for a RuntimeDeterminedType is not a supported operation throw new NotSupportedException(); diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.Diagnostic.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.Diagnostic.cs index 91451e43ee6131..09899ba8923eb7 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.Diagnostic.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.Diagnostic.cs @@ -1,11 +1,9 @@ // 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 Internal.TypeSystem { - partial class RuntimeDeterminedType + public partial class RuntimeDeterminedType { public override string DiagnosticName { @@ -19,7 +17,7 @@ public override string DiagnosticNamespace { get { - return String.Concat(_runtimeDeterminedDetailsType.DiagnosticName, "_", _rawCanonType.DiagnosticNamespace); ; + return string.Concat(_runtimeDeterminedDetailsType.DiagnosticName, "_", _rawCanonType.DiagnosticNamespace); ; } } } diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.Sorting.cs index 70d1d7e7348a27..5a1a2293a220e1 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types - partial class RuntimeDeterminedType + public partial class RuntimeDeterminedType { protected internal override int ClassCode => 351938209; diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.cs index df7dbd13dde940..d9f2742c25f84f 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/RuntimeDeterminedType.cs @@ -1,7 +1,6 @@ // 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 Debug = System.Diagnostics.Debug; @@ -17,11 +16,11 @@ namespace Internal.TypeSystem /// The use of runtime determined types is limited to the dependency analysis and to communicating /// with the codegen backend during shared generic code generation. They should not show up within /// the system otherwise. - /// + /// /// Runtime determined types behave mostly like the canonical type they are wrapping. Most of the overrides /// this type implements will forward the implementation to the 's /// implementation. - /// + /// /// Runtime determined types also behave like signature variables in the sense that they allow being /// substituted during signature instantiation. /// @@ -102,7 +101,7 @@ public override string Namespace { get { - return String.Concat(_runtimeDeterminedDetailsType.Name, "_", _rawCanonType.Namespace); + return string.Concat(_runtimeDeterminedDetailsType.Name, "_", _rawCanonType.Namespace); } } diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/SignatureVariable.RuntimeDetermined.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/SignatureVariable.RuntimeDetermined.cs index 8eff9f5195443e..7caa4d7255ca59 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/SignatureVariable.RuntimeDetermined.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/SignatureVariable.RuntimeDetermined.cs @@ -5,7 +5,7 @@ namespace Internal.TypeSystem { - partial class SignatureVariable + public partial class SignatureVariable { public sealed override bool IsRuntimeDeterminedSubtype { diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/TypeDesc.RuntimeDetermined.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/TypeDesc.RuntimeDetermined.cs index dc602f5ed282a6..f69f411f1f7ddc 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/TypeDesc.RuntimeDetermined.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/TypeDesc.RuntimeDetermined.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class TypeDesc + public partial class TypeDesc { /// /// Gets a value indicating whether the concrete type this object represents is unknown diff --git a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/TypeSystemContext.RuntimeDetermined.cs b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/TypeSystemContext.RuntimeDetermined.cs index dbbb7442aa4f4c..689905e9526d5e 100644 --- a/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/TypeSystemContext.RuntimeDetermined.cs +++ b/src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/TypeSystemContext.RuntimeDetermined.cs @@ -8,7 +8,7 @@ namespace Internal.TypeSystem { - partial class TypeSystemContext + public partial class TypeSystemContext { private struct RuntimeDeterminedTypeKey { @@ -21,7 +21,7 @@ public RuntimeDeterminedTypeKey(DefType plainCanonType, GenericParameterDesc det _detailsType = detailsType; } - public class RuntimeDeterminedTypeKeyHashtable : LockFreeReaderHashtable + public sealed class RuntimeDeterminedTypeKeyHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(RuntimeDeterminedTypeKey key) { @@ -96,7 +96,7 @@ public RuntimeDeterminedType RDType } } - public class MethodForRuntimeDeterminedTypeKeyHashtable : LockFreeReaderHashtable + public sealed class MethodForRuntimeDeterminedTypeKeyHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(MethodForRuntimeDeterminedTypeKey key) { diff --git a/src/coreclr/tools/Common/TypeSystem/Serialization/FieldDesc.Serialization.cs b/src/coreclr/tools/Common/TypeSystem/Serialization/FieldDesc.Serialization.cs index 6552d1eaaa80e3..c30d2521188dbf 100644 --- a/src/coreclr/tools/Common/TypeSystem/Serialization/FieldDesc.Serialization.cs +++ b/src/coreclr/tools/Common/TypeSystem/Serialization/FieldDesc.Serialization.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Additional members of FieldDesc related to serialization. - partial class FieldDesc + public partial class FieldDesc { /// /// Gets a value indicating whether this field is not serialized. @@ -19,7 +19,7 @@ public virtual bool IsNotSerialized } } - partial class FieldForInstantiatedType + public partial class FieldForInstantiatedType { public override bool IsNotSerialized { diff --git a/src/coreclr/tools/Common/TypeSystem/Serialization/TypeDesc.Serialization.cs b/src/coreclr/tools/Common/TypeSystem/Serialization/TypeDesc.Serialization.cs index 9c4fcf89376ef4..ff129b0885a817 100644 --- a/src/coreclr/tools/Common/TypeSystem/Serialization/TypeDesc.Serialization.cs +++ b/src/coreclr/tools/Common/TypeSystem/Serialization/TypeDesc.Serialization.cs @@ -3,7 +3,7 @@ namespace Internal.TypeSystem { - partial class TypeDesc + public partial class TypeDesc { /// /// Gets a value indicating whether this type is serializable. @@ -17,7 +17,7 @@ public virtual bool IsSerializable } } - partial class InstantiatedType + public partial class InstantiatedType { public override bool IsSerializable { diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/ArrayType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/ArrayType.Sorting.cs index 30993214e5d681..bdd089e939c82d 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/ArrayType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/ArrayType.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types - partial class ArrayType + public partial class ArrayType { protected internal override int ClassCode => -1274559616; @@ -19,7 +19,7 @@ protected internal override int CompareToImpl(TypeDesc other, TypeSystemComparer } } - partial class ArrayMethod + public partial class ArrayMethod { protected internal override int ClassCode => 487354154; diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/ByRefType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/ByRefType.Sorting.cs index 031e675c684288..34708718db4131 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/ByRefType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/ByRefType.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types - partial class ByRefType + public partial class ByRefType { protected internal override int ClassCode => -959602231; diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/FieldDesc.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/FieldDesc.Sorting.cs index a1f7c02a2d5927..bf02ec18b86d9b 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/FieldDesc.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/FieldDesc.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types and members - partial class FieldDesc + public partial class FieldDesc { /// /// Gets an identifier that is the same for all instances of this diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/FieldForInstantiatedType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/FieldForInstantiatedType.Sorting.cs index 1682d6abe97a6e..5548241264c2c8 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/FieldForInstantiatedType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/FieldForInstantiatedType.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types and members - partial class FieldForInstantiatedType + public partial class FieldForInstantiatedType { protected internal override int ClassCode => 1140200283; diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/FunctionPointerType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/FunctionPointerType.Sorting.cs index e833b9557fa7e6..5bcbb190d890f4 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/FunctionPointerType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/FunctionPointerType.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types - partial class FunctionPointerType + public partial class FunctionPointerType { protected internal override int ClassCode => -914739489; diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/InstantiatedMethod.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/InstantiatedMethod.Sorting.cs index 0fe7eb4686fd2d..5527d2813fbd6b 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/InstantiatedMethod.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/InstantiatedMethod.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types - partial class InstantiatedMethod + public partial class InstantiatedMethod { protected internal override int ClassCode => -873941872; @@ -16,9 +16,9 @@ protected internal override int CompareToImpl(MethodDesc other, TypeSystemCompar // to each other. This is a better heuristic than sorting by method definition // then by instantiation. // - // The goal is to sort methods like SomeClass.SomeMethod, + // The goal is to sort methods like SomeClass.SomeMethod, // near SomeOtherClass.SomeOtherMethod - int result = 0; + int result; // Sort instantiations of the same type together for (int i = 0; i < _instantiation.Length; i++) { diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/InstantiatedType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/InstantiatedType.Sorting.cs index 887effee9706db..ff304295a7afc8 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/InstantiatedType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/InstantiatedType.Sorting.cs @@ -1,12 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Debug = System.Diagnostics.Debug; - namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types - partial class InstantiatedType + public partial class InstantiatedType { protected internal override int ClassCode => 1150020412; @@ -21,13 +19,13 @@ protected internal override int CompareToImpl(TypeDesc other, TypeSystemComparer // The goal is to sort classes like SomeClass, // near SomeOtherClass - int result = 0; // Sort instantiations of the same type together for (int i = 0; i < _instantiation.Length; i++) { if (i >= otherType._instantiation.Length) return 1; - result = comparer.Compare(_instantiation[i], otherType._instantiation[i]); + + int result = comparer.Compare(_instantiation[i], otherType._instantiation[i]); if (result != 0) return result; } diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/MethodDesc.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/MethodDesc.Sorting.cs index baa78bda20360a..05f1091628af6c 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/MethodDesc.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/MethodDesc.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types and members - partial class MethodDesc + public partial class MethodDesc { /// /// Gets an identifier that is the same for all instances of this diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/MethodForInstantiatedType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/MethodForInstantiatedType.Sorting.cs index eabd0ce0a23e73..3de11f8d63484d 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/MethodForInstantiatedType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/MethodForInstantiatedType.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types - partial class MethodForInstantiatedType + public partial class MethodForInstantiatedType { protected internal override int ClassCode => 1359759636; diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/MethodSignature.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/MethodSignature.Sorting.cs index edeaf981a52eb2..4ec7211d7b9a01 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/MethodSignature.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/MethodSignature.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types - partial class MethodSignature + public partial class MethodSignature { internal int CompareTo(MethodSignature other, TypeSystemComparer comparer) { diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/PointerType.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/PointerType.Sorting.cs index 6d2a13ebe305e9..e8eb0276aa5d37 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/PointerType.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/PointerType.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types - partial class PointerType + public partial class PointerType { protected internal override int ClassCode => -2124247792; diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/SignatureVariable.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/SignatureVariable.Sorting.cs index ddfdbb065da1c0..b11a1b3f414f51 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/SignatureVariable.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/SignatureVariable.Sorting.cs @@ -1,12 +1,10 @@ // 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 Internal.TypeSystem { // Functionality related to deterministic ordering of types - partial class SignatureVariable + public partial class SignatureVariable { protected internal sealed override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer) { @@ -14,7 +12,7 @@ protected internal sealed override int CompareToImpl(TypeDesc other, TypeSystemC } } - partial class SignatureTypeVariable + public partial class SignatureTypeVariable { protected internal override int ClassCode { @@ -25,7 +23,7 @@ protected internal override int ClassCode } } - partial class SignatureMethodVariable + public partial class SignatureMethodVariable { protected internal override int ClassCode { diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/TypeDesc.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/TypeDesc.Sorting.cs index 7c75359d7cb935..8ed7b8b5374a36 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/TypeDesc.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/TypeDesc.Sorting.cs @@ -4,7 +4,7 @@ namespace Internal.TypeSystem { // Functionality related to deterministic ordering of types and members - partial class TypeDesc + public partial class TypeDesc { /// /// Gets an identifier that is the same for all instances of this diff --git a/src/coreclr/tools/Common/TypeSystem/Sorting/TypeSystemComparer.cs b/src/coreclr/tools/Common/TypeSystem/Sorting/TypeSystemComparer.cs index 39f795683d6cc5..4db2f4e603eb67 100644 --- a/src/coreclr/tools/Common/TypeSystem/Sorting/TypeSystemComparer.cs +++ b/src/coreclr/tools/Common/TypeSystem/Sorting/TypeSystemComparer.cs @@ -131,4 +131,3 @@ public int Compare(MethodSignature x, MethodSignature y) } } } - diff --git a/src/coreclr/tools/aot/.editorconfig b/src/coreclr/tools/aot/.editorconfig index f5e97a5d50a0d6..0190ebce7043fe 100644 --- a/src/coreclr/tools/aot/.editorconfig +++ b/src/coreclr/tools/aot/.editorconfig @@ -1,3 +1,15 @@ +### Code Style Analyzers + +[*.cs] +# IDE0005: Remove unnecessary usings/imports +dotnet_diagnostic.IDE0005.severity = error + +# IL3000: Avoid accessing Assembly file path when publishing as a single file +dotnet_diagnostic.IL3000.severity = suggestion + +# CS0176: Cannot be accessed with an instance ref +dotnet_diagnostic.CS0176.severity = silent + # Linker port settings: # A newline ending every file # Use tabs as indentation @@ -28,6 +40,12 @@ csharp_style_expression_bodied_properties = true:none csharp_style_expression_bodied_indexers = true:none csharp_style_expression_bodied_accessors = true:none +# IL3000: Avoid accessing Assembly file path when publishing as a single file +dotnet_diagnostic.IL3000.severity = suggestion + +# IDE0073: The file header does not match the required text +dotnet_diagnostic.IDE0073.severity = none + [Mono.Linker.Tests/**.cs] indent_style = tab indent_size = 4 @@ -55,6 +73,15 @@ csharp_style_expression_bodied_properties = true:none csharp_style_expression_bodied_indexers = true:none csharp_style_expression_bodied_accessors = true:none +# IDE0073: The file header does not match the required text +dotnet_diagnostic.IDE0073.severity = none + +# IL3000: Avoid accessing Assembly file path when publishing as a single file +dotnet_diagnostic.IL3000.severity = suggestion + +# IL3002: Avoid calling members marked with 'RequiresAssemblyFilesAttribute' when publishing as a single-file +dotnet_diagnostic.IL3002.severity = suggestion + [Mono.Linker.Tests.Cases/**.cs] indent_style = tab indent_size = 4 @@ -82,6 +109,12 @@ csharp_style_expression_bodied_properties = true:none csharp_style_expression_bodied_indexers = true:none csharp_style_expression_bodied_accessors = true:none +# IL3000: Avoid accessing Assembly file path when publishing as a single file +dotnet_diagnostic.IL3000.severity = suggestion + +# IDE0073: The file header does not match the required text +dotnet_diagnostic.IDE0073.severity = none + [Mono.Linker.Tests.Cases.Expectations/**.cs] indent_style = tab indent_size = 4 @@ -108,3 +141,9 @@ dotnet_sort_system_directives_first = true csharp_style_expression_bodied_properties = true:none csharp_style_expression_bodied_indexers = true:none csharp_style_expression_bodied_accessors = true:none + +# IL3000: Avoid accessing Assembly file path when publishing as a single file +dotnet_diagnostic.IL3000.severity = suggestion + +# IDE0073: The file header does not match the required text +dotnet_diagnostic.IDE0073.severity = none diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/AnalysisBasedMetadataManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/AnalysisBasedMetadataManager.cs index 1eec083ff59431..f287624d266b48 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/AnalysisBasedMetadataManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/AnalysisBasedMetadataManager.cs @@ -56,7 +56,7 @@ public AnalysisBasedMetadataManager( { _modulesWithMetadata = new List(modulesWithMetadata); _typesWithRootedCctorContext = new List(rootedCctorContexts); - + foreach (var refType in reflectableTypes) { _reflectableTypes.Add(refType.Entity, refType.Category); @@ -214,7 +214,7 @@ private struct Policy : IMetadataPolicy private readonly MetadataBlockingPolicy _blockingPolicy; private readonly AnalysisBasedMetadataManager _parent; - public Policy(MetadataBlockingPolicy blockingPolicy, + public Policy(MetadataBlockingPolicy blockingPolicy, AnalysisBasedMetadataManager parent) { _blockingPolicy = blockingPolicy; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/BlockedInternalsBlockingPolicy.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/BlockedInternalsBlockingPolicy.cs index 8d07a9363e2499..7abb3b45155cb5 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/BlockedInternalsBlockingPolicy.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/BlockedInternalsBlockingPolicy.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem; using Internal.TypeSystem.Ecma; @@ -25,7 +23,7 @@ private enum ModuleBlockingMode FullyBlocked, } - private class ModuleBlockingState + private sealed class ModuleBlockingState { public ModuleDesc Module { get; } public ModuleBlockingMode BlockingMode { get; } @@ -36,12 +34,12 @@ public ModuleBlockingState(ModuleDesc module, ModuleBlockingMode mode) } } - private class BlockedModulesHashtable : LockFreeReaderHashtable + private sealed class BlockedModulesHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(ModuleDesc key) => key.GetHashCode(); protected override int GetValueHashCode(ModuleBlockingState value) => value.Module.GetHashCode(); - protected override bool CompareKeyToValue(ModuleDesc key, ModuleBlockingState value) => Object.ReferenceEquals(key, value.Module); - protected override bool CompareValueToValue(ModuleBlockingState value1, ModuleBlockingState value2) => Object.ReferenceEquals(value1.Module, value2.Module); + protected override bool CompareKeyToValue(ModuleDesc key, ModuleBlockingState value) => ReferenceEquals(key, value.Module); + protected override bool CompareValueToValue(ModuleBlockingState value1, ModuleBlockingState value2) => ReferenceEquals(value1.Module, value2.Module); protected override ModuleBlockingState CreateValueFromKey(ModuleDesc module) { ModuleBlockingMode blockingMode = ModuleBlockingMode.None; @@ -60,7 +58,7 @@ protected override ModuleBlockingState CreateValueFromKey(ModuleDesc module) } private BlockedModulesHashtable _blockedModules = new BlockedModulesHashtable(); - private class BlockingState + private sealed class BlockingState { public EcmaType Type { get; } public bool IsBlocked { get; } @@ -71,7 +69,7 @@ public BlockingState(EcmaType type, bool isBlocked) } } - private class BlockedTypeHashtable : LockFreeReaderHashtable + private sealed class BlockedTypeHashtable : LockFreeReaderHashtable { private readonly BlockedModulesHashtable _blockedModules; @@ -82,8 +80,8 @@ public BlockedTypeHashtable(BlockedModulesHashtable blockedModules) protected override int GetKeyHashCode(EcmaType key) => key.GetHashCode(); protected override int GetValueHashCode(BlockingState value) => value.Type.GetHashCode(); - protected override bool CompareKeyToValue(EcmaType key, BlockingState value) => Object.ReferenceEquals(key, value.Type); - protected override bool CompareValueToValue(BlockingState value1, BlockingState value2) => Object.ReferenceEquals(value1.Type, value2.Type); + protected override bool CompareKeyToValue(EcmaType key, BlockingState value) => ReferenceEquals(key, value.Type); + protected override bool CompareValueToValue(BlockingState value1, BlockingState value2) => ReferenceEquals(value1.Type, value2.Type); protected override BlockingState CreateValueFromKey(EcmaType type) { ModuleBlockingMode moduleBlockingMode = _blockedModules.GetOrCreateValue(type.EcmaModule).BlockingMode; @@ -120,7 +118,7 @@ private bool ComputeIsBlocked(EcmaType type, ModuleBlockingMode blockingMode) DefType containingType = type.ContainingType; var typeDefinition = type.MetadataReader.GetTypeDefinition(type.Handle); - + if (containingType == null) { if ((typeDefinition.Attributes & TypeAttributes.Public) == 0) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/BodySubstitution.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/BodySubstitution.cs index be138cefa7de1e..769f088c81da47 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/BodySubstitution.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/BodySubstitution.cs @@ -12,10 +12,10 @@ internal sealed class BodySubstitution { private object _value; - private readonly static object Throw = new object(); + private static readonly object Throw = new object(); - public readonly static BodySubstitution ThrowingBody = new BodySubstitution(Throw); - public readonly static BodySubstitution EmptyBody = new BodySubstitution(null); + public static readonly BodySubstitution ThrowingBody = new BodySubstitution(Throw); + public static readonly BodySubstitution EmptyBody = new BodySubstitution(null); public object Value { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/BodySubstitutionParser.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/BodySubstitutionParser.cs index 3aade53731c65e..a0025c2d3e7907 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/BodySubstitutionParser.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/BodySubstitutionParser.cs @@ -114,7 +114,7 @@ protected override void ProcessField(TypeDesc type, XPathNavigator fieldNav) return; } - if (String.Equals(GetAttribute(fieldNav, "initialize"), "true", StringComparison.InvariantCultureIgnoreCase)) + if (string.Equals(GetAttribute(fieldNav, "initialize"), "true", StringComparison.InvariantCultureIgnoreCase)) { // We would need to also mess with the cctor of the type to set the field to this value: // @@ -128,7 +128,7 @@ protected override void ProcessField(TypeDesc type, XPathNavigator fieldNav) _fieldSubstitutions[field] = substitution; } - static MethodDesc FindMethod(TypeDesc type, string signature) + private static MethodDesc FindMethod(TypeDesc type, string signature) { foreach (MethodDesc meth in type.GetMethods()) if (signature == GetMethodSignature(meth, includeGenericParameters: true)) @@ -136,7 +136,7 @@ static MethodDesc FindMethod(TypeDesc type, string signature) return null; } - private object TryCreateSubstitution(TypeDesc type, string value) + private static object TryCreateSubstitution(TypeDesc type, string value) { switch (type.UnderlyingType.Category) { @@ -148,7 +148,7 @@ private object TryCreateSubstitution(TypeDesc type, string value) break; case TypeFlags.Boolean: - if (String.IsNullOrEmpty(value)) + if (string.IsNullOrEmpty(value)) return 0; else if (bool.TryParse(value, out bool bvalue)) return bvalue ? 1 : 0; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Compilation.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Compilation.cs index 018226ef842703..02057abde7e4cd 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Compilation.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Compilation.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.IO; -using System.Runtime.InteropServices; using ILCompiler.DependencyAnalysis; using ILCompiler.DependencyAnalysisFramework; @@ -266,7 +265,7 @@ public bool NeedsRuntimeLookup(ReadyToRunHelperId lookupKind, object targetOfLoo public ReadyToRunHelperId GetLdTokenHelperForType(TypeDesc type) { bool canConstructPerWholeProgramAnalysis = _devirtualizationManager == null ? true : _devirtualizationManager.CanConstructType(type); - bool creationAllowed = DependencyAnalysis.ConstructedEETypeNode.CreationAllowed(type); + bool creationAllowed = ConstructedEETypeNode.CreationAllowed(type); return (canConstructPerWholeProgramAnalysis && creationAllowed) ? ReadyToRunHelperId.TypeHandle : ReadyToRunHelperId.NecessaryTypeHandle; @@ -520,17 +519,11 @@ public MethodDesc GetTargetOfGenericVirtualMethodCall(MethodDesc calledMethod) CompilationResults ICompilation.Compile(string outputFile, ObjectDumper dumper) { - if (dumper != null) - { - dumper.Begin(); - } + dumper?.Begin(); CompileInternal(outputFile, dumper); - if (dumper != null) - { - dumper.End(); - } + dumper?.End(); return new CompilationResults(_dependencyGraph, _nodeFactory); } @@ -554,18 +547,18 @@ protected override int GetValueHashCode(MethodILData value) } protected override bool CompareKeyToValue(MethodDesc key, MethodILData value) { - return Object.ReferenceEquals(key, value.Method); + return ReferenceEquals(key, value.Method); } protected override bool CompareValueToValue(MethodILData value1, MethodILData value2) { - return Object.ReferenceEquals(value1.Method, value2.Method); + return ReferenceEquals(value1.Method, value2.Method); } protected override MethodILData CreateValueFromKey(MethodDesc key) { return new MethodILData() { Method = key, MethodIL = ILProvider.GetMethodIL(key) }; } - internal class MethodILData + internal sealed class MethodILData { public MethodDesc Method; public MethodIL MethodIL; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilationBuilder.Aot.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilationBuilder.Aot.cs index 232df5cd22d4e2..bf1a053c0c612c 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilationBuilder.Aot.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilationBuilder.Aot.cs @@ -3,11 +3,9 @@ using System; -using Internal.JitInterface; - namespace ILCompiler { - partial class CompilationBuilder + public partial class CompilationBuilder { private PreinitializationManager _preinitializationManager; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilationModuleGroup.Aot.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilationModuleGroup.Aot.cs index a7522ba8810a96..a56072d34842e1 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilationModuleGroup.Aot.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilationModuleGroup.Aot.cs @@ -5,7 +5,7 @@ namespace ILCompiler { - partial class CompilationModuleGroup : IInliningPolicy + public partial class CompilationModuleGroup : IInliningPolicy { /// /// If true, type dictionary of "type" is in the module to be compiled @@ -25,13 +25,13 @@ partial class CompilationModuleGroup : IInliningPolicy /// public abstract bool IsSingleFileCompilation { get; } /// - /// If true, the full type should be generated. This occurs in situations where the type is + /// If true, the full type should be generated. This occurs in situations where the type is /// shared between modules (generics, parameterized types), or the type lives in a different module /// and therefore needs a full VTable /// public abstract bool ShouldProduceFullVTable(TypeDesc type); /// - /// If true, the necessary type should be promoted to a full type should be generated. + /// If true, the necessary type should be promoted to a full type should be generated. /// public abstract bool ShouldPromoteToFullType(TypeDesc type); /// diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerGeneratedInteropStubManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerGeneratedInteropStubManager.cs index 5c83e2211c9c5c..b56ca367618e9a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerGeneratedInteropStubManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerGeneratedInteropStubManager.cs @@ -28,7 +28,7 @@ public sealed override PInvokeILProvider CreatePInvokeILProvider() { return new PInvokeILProvider(_pInvokeILEmitterConfiguration, _interopStateManager); } - + public sealed override void AddToReadyToRunHeader(ReadyToRunHeaderNode header, NodeFactory nodeFactory, ExternalReferencesTableNode commonFixupsTableNode) { var delegateMapNode = new DelegateMarshallingStubMapNode(commonFixupsTableNode, _interopStateManager); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerMetadataFieldLayoutAlgorithm.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerMetadataFieldLayoutAlgorithm.cs index 8c0882b08f2317..1bb77e03eeb97a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerMetadataFieldLayoutAlgorithm.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerMetadataFieldLayoutAlgorithm.cs @@ -1,16 +1,13 @@ // 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 Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace ILCompiler { - internal class CompilerMetadataFieldLayoutAlgorithm : MetadataFieldLayoutAlgorithm + internal sealed class CompilerMetadataFieldLayoutAlgorithm : MetadataFieldLayoutAlgorithm { // GC statics start with a pointer to the "MethodTable" that signals the size and GCDesc to the GC public static LayoutInt GetGCStaticFieldOffset(TypeSystemContext context) => context.Target.LayoutPointerSize; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Aot.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Aot.cs index 0d07c51c40d3e9..97176e404cb82d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Aot.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Aot.cs @@ -12,7 +12,7 @@ namespace ILCompiler { - partial class CompilerTypeSystemContext + public partial class CompilerTypeSystemContext { // Chosen rather arbitrarily. For the app that I was looking at, cutoff point of 7 compiled // more than 10 minutes on a release build of the compiler, and I lost patience. @@ -57,10 +57,7 @@ public CompilerTypeSystemContext(TargetDetails details, SharedGenericsMode gener protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForNonPointerArrayType(ArrayType type) { - if (_arrayOfTRuntimeInterfacesAlgorithm == null) - { - _arrayOfTRuntimeInterfacesAlgorithm = new ArrayOfTRuntimeInterfacesAlgorithm(SystemModule.GetKnownType("System", "Array`1")); - } + _arrayOfTRuntimeInterfacesAlgorithm ??= new ArrayOfTRuntimeInterfacesAlgorithm(SystemModule.GetKnownType("System", "Array`1")); return _arrayOfTRuntimeInterfacesAlgorithm; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.BoxedTypes.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.BoxedTypes.cs index beba5d59dc8528..c38e5cfceb89f2 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.BoxedTypes.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.BoxedTypes.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Text; using Internal.TypeSystem; using Internal.IL; @@ -51,7 +50,7 @@ namespace ILCompiler { // Contains functionality related to pseudotypes representing boxed instances of value types - partial class CompilerTypeSystemContext + public partial class CompilerTypeSystemContext { /// /// For a shared (canonical) instance method on a generic valuetype, gets a method that can be used to call the @@ -152,7 +151,7 @@ public BoxedValuetypeHashtableKey(MetadataType valueType, ModuleDesc owningModul } } - private class BoxedValuetypeHashtable : LockFreeReaderHashtable + private sealed class BoxedValuetypeHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(BoxedValuetypeHashtableKey key) { @@ -164,13 +163,13 @@ protected override int GetValueHashCode(BoxedValueType value) } protected override bool CompareKeyToValue(BoxedValuetypeHashtableKey key, BoxedValueType value) { - return Object.ReferenceEquals(key.ValueType, value.ValueTypeRepresented) && - Object.ReferenceEquals(key.OwningModule, value.Module); + return ReferenceEquals(key.ValueType, value.ValueTypeRepresented) && + ReferenceEquals(key.OwningModule, value.Module); } protected override bool CompareValueToValue(BoxedValueType value1, BoxedValueType value2) { - return Object.ReferenceEquals(value1.ValueTypeRepresented, value2.ValueTypeRepresented) && - Object.ReferenceEquals(value1.Module, value2.Module); + return ReferenceEquals(value1.ValueTypeRepresented, value2.ValueTypeRepresented) && + ReferenceEquals(value1.Module, value2.Module); } protected override BoxedValueType CreateValueFromKey(BoxedValuetypeHashtableKey key) { @@ -191,7 +190,7 @@ public UnboxingThunkHashtableKey(MethodDesc targetMethod, BoxedValueType owningT } } - private class UnboxingThunkHashtable : LockFreeReaderHashtable + private sealed class UnboxingThunkHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(UnboxingThunkHashtableKey key) { @@ -203,13 +202,13 @@ protected override int GetValueHashCode(GenericUnboxingThunk value) } protected override bool CompareKeyToValue(UnboxingThunkHashtableKey key, GenericUnboxingThunk value) { - return Object.ReferenceEquals(key.TargetMethod, value.TargetMethod) && - Object.ReferenceEquals(key.OwningType, value.OwningType); + return ReferenceEquals(key.TargetMethod, value.TargetMethod) && + ReferenceEquals(key.OwningType, value.OwningType); } protected override bool CompareValueToValue(GenericUnboxingThunk value1, GenericUnboxingThunk value2) { - return Object.ReferenceEquals(value1.TargetMethod, value2.TargetMethod) && - Object.ReferenceEquals(value1.OwningType, value2.OwningType); + return ReferenceEquals(value1.TargetMethod, value2.TargetMethod) && + ReferenceEquals(value1.OwningType, value2.OwningType); } protected override GenericUnboxingThunk CreateValueFromKey(UnboxingThunkHashtableKey key) { @@ -218,7 +217,7 @@ protected override GenericUnboxingThunk CreateValueFromKey(UnboxingThunkHashtabl } private UnboxingThunkHashtable _unboxingThunkHashtable = new UnboxingThunkHashtable(); - private class NonGenericUnboxingThunkHashtable : LockFreeReaderHashtable + private sealed class NonGenericUnboxingThunkHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(UnboxingThunkHashtableKey key) { @@ -230,13 +229,13 @@ protected override int GetValueHashCode(UnboxingThunk value) } protected override bool CompareKeyToValue(UnboxingThunkHashtableKey key, UnboxingThunk value) { - return Object.ReferenceEquals(key.TargetMethod, value.TargetMethod) && - Object.ReferenceEquals(key.OwningType, value.OwningType); + return ReferenceEquals(key.TargetMethod, value.TargetMethod) && + ReferenceEquals(key.OwningType, value.OwningType); } protected override bool CompareValueToValue(UnboxingThunk value1, UnboxingThunk value2) { - return Object.ReferenceEquals(value1.TargetMethod, value2.TargetMethod) && - Object.ReferenceEquals(value1.OwningType, value2.OwningType); + return ReferenceEquals(value1.TargetMethod, value2.TargetMethod) && + ReferenceEquals(value1.OwningType, value2.OwningType); } protected override UnboxingThunk CreateValueFromKey(UnboxingThunkHashtableKey key) { @@ -250,7 +249,7 @@ protected override UnboxingThunk CreateValueFromKey(UnboxingThunkHashtableKey ke /// A type with an identical layout to the layout of a boxed value type. /// The type has a single field of the type of the valuetype it represents. /// - private partial class BoxedValueType : MetadataType, INonEmittableType + private sealed partial class BoxedValueType : MetadataType, INonEmittableType { public MetadataType ValueTypeRepresented { get; } @@ -380,7 +379,7 @@ public MethodDesc GetTargetOfSpecialUnboxingThunk(MethodDesc method) /// /// Represents a thunk to call shared instance method on boxed valuetypes. /// - private partial class GenericUnboxingThunk : ILStubMethod + private sealed partial class GenericUnboxingThunk : ILStubMethod { private MethodDesc _targetMethod; private ValueTypeInstanceMethodWithHiddenParameter _nakedTargetMethod; @@ -466,7 +465,7 @@ public override MethodIL EmitIL() /// /// Represents a thunk to call instance method on boxed valuetypes. /// - private partial class UnboxingThunk : ILStubMethod + private sealed partial class UnboxingThunk : ILStubMethod { private MethodDesc _targetMethod; private BoxedValueType _owningType; @@ -565,7 +564,7 @@ public override MethodIL EmitIL() /// signature. This is so that we can refer to the parameter from IL. References to this method will /// be replaced by the actual instance method after codegen is done. /// - internal partial class ValueTypeInstanceMethodWithHiddenParameter : MethodDesc + internal sealed partial class ValueTypeInstanceMethodWithHiddenParameter : MethodDesc { private MethodDesc _methodRepresented; private MethodSignature _signature; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DelegateInfo.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DelegateInfo.cs index a021e39691d226..abd33f4726ac2e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DelegateInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DelegateInfo.cs @@ -1,16 +1,14 @@ // 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 Internal.IL; using Internal.TypeSystem; namespace ILCompiler { - partial class CompilerTypeSystemContext + public partial class CompilerTypeSystemContext { - private class DelegateInfoHashtable : LockFreeReaderHashtable + private sealed class DelegateInfoHashtable : LockFreeReaderHashtable { private readonly DelegateFeature _delegateFeatures; @@ -27,11 +25,11 @@ protected override int GetValueHashCode(DelegateInfo value) } protected override bool CompareKeyToValue(TypeDesc key, DelegateInfo value) { - return Object.ReferenceEquals(key, value.Type); + return ReferenceEquals(key, value.Type); } protected override bool CompareValueToValue(DelegateInfo value1, DelegateInfo value2) { - return Object.ReferenceEquals(value1.Type, value2.Type); + return ReferenceEquals(value1.Type, value2.Type); } protected override DelegateInfo CreateValueFromKey(TypeDesc key) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DynamicInvoke.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DynamicInvoke.cs index f67306c264149b..38dc8e080c8827 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DynamicInvoke.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.DynamicInvoke.cs @@ -4,13 +4,11 @@ using Internal.IL.Stubs; using Internal.TypeSystem; -using Debug = System.Diagnostics.Debug; - namespace ILCompiler { - partial class CompilerTypeSystemContext + public partial class CompilerTypeSystemContext { - private class DynamicInvokeThunkHashtable : LockFreeReaderHashtable + private sealed class DynamicInvokeThunkHashtable : LockFreeReaderHashtable { protected override bool CompareKeyToValue(MethodSignature key, DynamicInvokeMethodThunk value) => key.Equals(value.TargetSignature); protected override bool CompareValueToValue(DynamicInvokeMethodThunk value1, DynamicInvokeMethodThunk value2) => value1.TargetSignature.Equals(value2.TargetSignature) && value1.OwningType == value2.OwningType; @@ -21,7 +19,8 @@ protected override DynamicInvokeMethodThunk CreateValueFromKey(MethodSignature k return new DynamicInvokeMethodThunk(((CompilerTypeSystemContext)key.Context).GeneratedAssembly.GetGlobalModuleType(), key); } } - DynamicInvokeThunkHashtable _dynamicInvokeThunks = new DynamicInvokeThunkHashtable(); + + private DynamicInvokeThunkHashtable _dynamicInvokeThunks = new DynamicInvokeThunkHashtable(); public MethodDesc GetDynamicInvokeThunk(MethodSignature signature, bool valueTypeInstanceMethod) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.EnumMethods.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.EnumMethods.cs index b777e28a2d144e..283153caae470d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.EnumMethods.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.EnumMethods.cs @@ -10,9 +10,9 @@ namespace ILCompiler { - partial class CompilerTypeSystemContext + public partial class CompilerTypeSystemContext { - private class EnumInfo + private sealed class EnumInfo { public TypeDesc Type => EqualsMethod.OwningType; @@ -28,7 +28,7 @@ public EnumInfo(TypeDesc enumType) } } - private class EnumInfoHashtable : LockFreeReaderHashtable + private sealed class EnumInfoHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(TypeDesc key) => key.GetHashCode(); protected override int GetValueHashCode(EnumInfo value) => value.Type.GetHashCode(); @@ -78,8 +78,7 @@ protected virtual IEnumerable GetAllMethodsForEnum(TypeDesc enumType yield break; } - if (_objectEqualsMethod == null) - _objectEqualsMethod = GetWellKnownType(WellKnownType.Object).GetMethod("Equals", null); + _objectEqualsMethod ??= GetWellKnownType(WellKnownType.Object).GetMethod("Equals", null); // If the classlib doesn't have Object.Equals, we don't need this. if (_objectEqualsMethod == null) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.Sorting.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.Sorting.cs index 1fc7bd2414e33d..135c50cc5b00cc 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.Sorting.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.Sorting.cs @@ -7,10 +7,10 @@ namespace ILCompiler { - partial class CompilerTypeSystemContext + public partial class CompilerTypeSystemContext { // Functionality related to deterministic ordering of types and members - partial class CompilerGeneratedType : MetadataType + internal partial class CompilerGeneratedType : MetadataType { protected override int ClassCode => -1036681447; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.cs index 280f2d85684a3b..d18c44ec8706cc 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.GeneratedAssembly.cs @@ -13,7 +13,7 @@ namespace ILCompiler { - partial class CompilerTypeSystemContext + public partial class CompilerTypeSystemContext { private ModuleDesc _generatedAssembly; @@ -30,7 +30,7 @@ public ModuleDesc GeneratedAssembly } } - private class CompilerGeneratedAssembly : ModuleDesc, IAssemblyDesc + private sealed class CompilerGeneratedAssembly : ModuleDesc, IAssemblyDesc { private MetadataType _globalModuleType; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.InterfaceThunks.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.InterfaceThunks.cs index f91414132f609d..53c34efc0ef703 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.InterfaceThunks.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.InterfaceThunks.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections.Generic; -using System.Text; using Internal.TypeSystem; using Internal.IL; @@ -62,7 +60,7 @@ namespace ILCompiler { // Contains functionality related to instantiating thunks for default interface methods - partial class CompilerTypeSystemContext + public partial class CompilerTypeSystemContext { private const int UseContextFromRuntime = -1; @@ -127,7 +125,7 @@ public DefaultInterfaceMethodImplementationInstantiationThunkHashtableKey(Method } } - private class DefaultInterfaceMethodImplementationInstantiationThunkHashtable : LockFreeReaderHashtable + private sealed class DefaultInterfaceMethodImplementationInstantiationThunkHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(DefaultInterfaceMethodImplementationInstantiationThunkHashtableKey key) { @@ -139,12 +137,12 @@ protected override int GetValueHashCode(DefaultInterfaceMethodImplementationInst } protected override bool CompareKeyToValue(DefaultInterfaceMethodImplementationInstantiationThunkHashtableKey key, DefaultInterfaceMethodImplementationInstantiationThunk value) { - return Object.ReferenceEquals(key.TargetMethod, value.TargetMethod) && + return ReferenceEquals(key.TargetMethod, value.TargetMethod) && key.InterfaceIndex == value.InterfaceIndex; } protected override bool CompareValueToValue(DefaultInterfaceMethodImplementationInstantiationThunk value1, DefaultInterfaceMethodImplementationInstantiationThunk value2) { - return Object.ReferenceEquals(value1.TargetMethod, value2.TargetMethod) && + return ReferenceEquals(value1.TargetMethod, value2.TargetMethod) && value1.InterfaceIndex == value2.InterfaceIndex; } protected override DefaultInterfaceMethodImplementationInstantiationThunk CreateValueFromKey(DefaultInterfaceMethodImplementationInstantiationThunkHashtableKey key) @@ -158,7 +156,7 @@ protected override DefaultInterfaceMethodImplementationInstantiationThunk Create /// /// Represents a thunk to call shared instance method on generic interfaces. /// - private partial class DefaultInterfaceMethodImplementationInstantiationThunk : ILStubMethod, IPrefixMangledMethod + private sealed partial class DefaultInterfaceMethodImplementationInstantiationThunk : ILStubMethod, IPrefixMangledMethod { private readonly MethodDesc _targetMethod; private readonly DefaultInterfaceMethodImplementationWithHiddenParameter _nakedTargetMethod; @@ -254,7 +252,7 @@ public override MethodIL EmitIL() /// signature. This is so that we can refer to the parameter from IL. References to this method will /// be replaced by the actual instance method after codegen is done. /// - internal partial class DefaultInterfaceMethodImplementationWithHiddenParameter : MethodDesc + internal sealed partial class DefaultInterfaceMethodImplementationWithHiddenParameter : MethodDesc { private readonly MethodDesc _methodRepresented; private readonly TypeDesc _owningType; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Mangling.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Mangling.cs index edbb37fedb4c29..676f3ae77a970f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Mangling.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Mangling.cs @@ -1,15 +1,14 @@ // 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 Internal.TypeSystem; namespace ILCompiler { // Contains functionality related to name mangling - partial class CompilerTypeSystemContext + public partial class CompilerTypeSystemContext { - partial class BoxedValueType : IPrefixMangledType + private partial class BoxedValueType : IPrefixMangledType { TypeDesc IPrefixMangledType.BaseType { @@ -28,7 +27,7 @@ string IPrefixMangledType.Prefix } } - partial class GenericUnboxingThunk : IPrefixMangledMethod + private partial class GenericUnboxingThunk : IPrefixMangledMethod { MethodDesc IPrefixMangledMethod.BaseMethod { @@ -47,7 +46,7 @@ string IPrefixMangledMethod.Prefix } } - partial class UnboxingThunk : IPrefixMangledMethod + private partial class UnboxingThunk : IPrefixMangledMethod { MethodDesc IPrefixMangledMethod.BaseMethod { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Sorting.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Sorting.cs index 62666ae4da581d..92f553ce526f96 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Sorting.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Sorting.cs @@ -6,9 +6,9 @@ namespace ILCompiler { // Functionality related to deterministic ordering of types and members - partial class CompilerTypeSystemContext + public partial class CompilerTypeSystemContext { - partial class BoxedValueType + private partial class BoxedValueType { protected override int ClassCode => 1062019524; @@ -18,7 +18,7 @@ protected override int CompareToImpl(TypeDesc other, TypeSystemComparer comparer } } - partial class GenericUnboxingThunk + private partial class GenericUnboxingThunk { protected override int ClassCode => -247515475; @@ -29,7 +29,7 @@ protected override int CompareToImpl(MethodDesc other, TypeSystemComparer compar } } - partial class UnboxingThunk + private partial class UnboxingThunk { protected override int ClassCode => 446545583; @@ -40,7 +40,7 @@ protected override int CompareToImpl(MethodDesc other, TypeSystemComparer compar } } - partial class ValueTypeInstanceMethodWithHiddenParameter + internal partial class ValueTypeInstanceMethodWithHiddenParameter { protected override int ClassCode => 2131875345; @@ -51,7 +51,7 @@ protected override int CompareToImpl(MethodDesc other, TypeSystemComparer compar } } - partial class DefaultInterfaceMethodImplementationInstantiationThunk + private partial class DefaultInterfaceMethodImplementationInstantiationThunk { protected override int ClassCode => -789598; @@ -67,7 +67,7 @@ protected override int CompareToImpl(MethodDesc other, TypeSystemComparer compar } } - partial class DefaultInterfaceMethodImplementationWithHiddenParameter + internal partial class DefaultInterfaceMethodImplementationWithHiddenParameter { protected override int ClassCode => 4903209; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.ValueTypeMethods.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.ValueTypeMethods.cs index 738b43554182c8..e4ffab14cd713f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.ValueTypeMethods.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.ValueTypeMethods.cs @@ -10,11 +10,11 @@ namespace ILCompiler { - partial class CompilerTypeSystemContext + public partial class CompilerTypeSystemContext { private MethodDesc _objectEqualsMethod; - private class ValueTypeMethodHashtable : LockFreeReaderHashtable + private sealed class ValueTypeMethodHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(DefType key) => key.GetHashCode(); protected override int GetValueHashCode(MethodDesc value) => value.OwningType.GetHashCode(); @@ -54,8 +54,7 @@ protected virtual IEnumerable GetAllMethodsForValueType(TypeDesc val private bool RequiresGetFieldHelperMethod(MetadataType valueType) { - if (_objectEqualsMethod == null) - _objectEqualsMethod = GetWellKnownType(WellKnownType.Object).GetMethod("Equals", null); + _objectEqualsMethod ??= GetWellKnownType(WellKnownType.Object).GetMethod("Equals", null); // If the classlib doesn't have Object.Equals, we don't need this. if (_objectEqualsMethod == null) @@ -77,7 +76,7 @@ private bool RequiresGetFieldHelperMethod(MetadataType valueType) return !_typeStateHashtable.GetOrCreateValue(valueType).CanCompareValueTypeBits; } - private class TypeState + private sealed class TypeState { private enum Flags { @@ -180,7 +179,7 @@ private bool ComputeCanCompareValueTypeBits(MetadataType type) } } - private class TypeStateHashtable : LockFreeReaderHashtable + private sealed class TypeStateHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(TypeDesc key) => key.GetHashCode(); protected override int GetValueHashCode(TypeState value) => value.Type.GetHashCode(); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ArrayValue.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ArrayValue.cs index 23740b13ef31a5..c6b8010e5077ea 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ArrayValue.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ArrayValue.cs @@ -14,7 +14,7 @@ namespace ILLink.Shared.TrimAnalysis { - partial record ArrayValue + internal partial record ArrayValue { public static MultiValue Create(MultiValue size, TypeDesc elementType) { @@ -35,7 +35,7 @@ public static ArrayValue Create(int size, TypeDesc elementType) /// /// Constructs an array value of the given size /// - ArrayValue(SingleValue size, TypeDesc elementType) + private ArrayValue(SingleValue size, TypeDesc elementType) { Size = size; ElementType = elementType; @@ -102,11 +102,11 @@ public override string ToString() { if (!first) { - result.Append(","); + result.Append(','); first = false; } - result.Append("("); + result.Append('('); result.Append(element.Key); result.Append(",("); bool firstValue = true; @@ -114,7 +114,7 @@ public override string ToString() { if (firstValue) { - result.Append(","); + result.Append(','); firstValue = false; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/AttributeDataFlow.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/AttributeDataFlow.cs index afdc85ab9e06e3..c524038d74d97a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/AttributeDataFlow.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/AttributeDataFlow.cs @@ -24,10 +24,10 @@ namespace ILCompiler.Dataflow { public readonly struct AttributeDataFlow { - readonly Logger _logger; - readonly NodeFactory _factory; - readonly FlowAnnotations _annotations; - readonly MessageOrigin _origin; + private readonly Logger _logger; + private readonly NodeFactory _factory; + private readonly FlowAnnotations _annotations; + private readonly MessageOrigin _origin; public AttributeDataFlow(Logger logger, NodeFactory factory, FlowAnnotations annotations, in MessageOrigin origin) { @@ -80,7 +80,7 @@ public AttributeDataFlow(Logger logger, NodeFactory factory, FlowAnnotations ann return result; } - void ProcessAttributeDataflow(MethodDesc method, ImmutableArray arguments, ref DependencyList? result) + private void ProcessAttributeDataflow(MethodDesc method, ImmutableArray arguments, ref DependencyList? result) { for (int i = 0; i < method.Signature.Length; i++) { @@ -106,7 +106,7 @@ public void ProcessAttributeDataflow(FieldDesc field, object? value, ref Depende } } - MultiValue GetValueForCustomAttributeArgument(object? argument) + private static MultiValue GetValueForCustomAttributeArgument(object? argument) => argument switch { TypeDesc td => new SystemTypeValue(td), @@ -116,7 +116,7 @@ MultiValue GetValueForCustomAttributeArgument(object? argument) _ => throw new InvalidOperationException() }; - void RequireDynamicallyAccessedMembers( + private void RequireDynamicallyAccessedMembers( in DiagnosticContext diagnosticContext, in MultiValue value, ValueWithDynamicallyAccessedMembers targetValue, diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedCallGraph.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedCallGraph.cs index 643e0a6a4bf138..f37894a5875a59 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedCallGraph.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedCallGraph.cs @@ -5,19 +5,18 @@ using System.Diagnostics; using Internal.TypeSystem; -using Internal.TypeSystem.Ecma; #nullable enable namespace ILCompiler.Dataflow { - sealed class CompilerGeneratedCallGraph + internal sealed class CompilerGeneratedCallGraph { - readonly Dictionary> _callGraph; + private readonly Dictionary> _callGraph; public CompilerGeneratedCallGraph() => _callGraph = new Dictionary>(); - void TrackCallInternal(TypeSystemEntity fromMember, TypeSystemEntity toMember) + private void TrackCallInternal(TypeSystemEntity fromMember, TypeSystemEntity toMember) { if (!_callGraph.TryGetValue(fromMember, out HashSet? toMembers)) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedNames.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedNames.cs index 90584110173b88..9135cda60e5ac4 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedNames.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedNames.cs @@ -5,7 +5,7 @@ namespace ILCompiler.Dataflow { - sealed class CompilerGeneratedNames + internal sealed class CompilerGeneratedNames { internal static bool IsGeneratedMemberName(string memberName) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedState.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedState.cs index c62233bd957a9c..359ccf70cfe788 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedState.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/CompilerGeneratedState.cs @@ -20,20 +20,20 @@ namespace ILCompiler.Dataflow // Currently this is implemented using heuristics public class CompilerGeneratedState { - readonly record struct TypeArgumentInfo( + private readonly record struct TypeArgumentInfo( /// The method which calls the ctor for the given type MethodDesc CreatingMethod, /// Attributes for the type, pulled from the creators type arguments IReadOnlyList? OriginalAttributes); - readonly TypeCacheHashtable _typeCacheHashtable; + private readonly TypeCacheHashtable _typeCacheHashtable; public CompilerGeneratedState(ILProvider ilProvider, Logger logger) { _typeCacheHashtable = new TypeCacheHashtable(ilProvider, logger); } - class TypeCacheHashtable : LockFreeReaderHashtable + private sealed class TypeCacheHashtable : LockFreeReaderHashtable { private ILProvider _ilProvider; private Logger? _logger; @@ -49,7 +49,7 @@ protected override TypeCache CreateValueFromKey(MetadataType key) => new TypeCache(key, _logger, _ilProvider); } - class TypeCache + private sealed class TypeCache { public readonly MetadataType Type; @@ -484,7 +484,7 @@ public bool TryGetOwningMethodForCompilerGeneratedType(MetadataType compilerGene } } - static IEnumerable GetCompilerGeneratedNestedTypes(MetadataType type) + private static IEnumerable GetCompilerGeneratedNestedTypes(MetadataType type) { foreach (var nestedType in type.GetNestedTypes()) { @@ -531,13 +531,9 @@ public static bool TryGetStateMachineType(MethodDesc method, [NotNullWhen(true)] // Discover state machine methods. if (method is not EcmaMethod ecmaMethod) return false; - - CustomAttributeValue? decodedAttribute = null; - decodedAttribute = ecmaMethod.GetDecodedCustomAttribute("System.Runtime.CompilerServices", "AsyncIteratorStateMachineAttribute"); - if (decodedAttribute == null) - decodedAttribute = ecmaMethod.GetDecodedCustomAttribute("System.Runtime.CompilerServices", "AsyncStateMachineAttribute"); - if (decodedAttribute == null) - decodedAttribute = ecmaMethod.GetDecodedCustomAttribute("System.Runtime.CompilerServices", "IteratorStateMachineAttribute"); + CustomAttributeValue? decodedAttribute = ecmaMethod.GetDecodedCustomAttribute("System.Runtime.CompilerServices", "AsyncIteratorStateMachineAttribute"); + decodedAttribute ??= ecmaMethod.GetDecodedCustomAttribute("System.Runtime.CompilerServices", "AsyncStateMachineAttribute"); + decodedAttribute ??= ecmaMethod.GetDecodedCustomAttribute("System.Runtime.CompilerServices", "IteratorStateMachineAttribute"); if (decodedAttribute == null) return false; @@ -565,7 +561,7 @@ public static bool TryGetStateMachineType(MethodDesc method, [NotNullWhen(true)] return _typeCacheHashtable.GetOrCreateValue(userType); } - static TypeDesc? GetFirstConstructorArgumentAsType(CustomAttributeValue attribute) + private static TypeDesc? GetFirstConstructorArgumentAsType(CustomAttributeValue attribute) { if (attribute.FixedArguments.Length == 0) return null; @@ -650,7 +646,7 @@ public bool TryGetUserMethodForCompilerGeneratedMember(TypeSystemEntity sourceMe return false; TypeSystemEntity member = sourceMember; - MethodDesc? userMethodCandidate = null; + MethodDesc? userMethodCandidate; while (TryGetOwningMethodForCompilerGeneratedMember(member, out userMethodCandidate)) { Debug.Assert(userMethodCandidate != member); @@ -660,7 +656,7 @@ public bool TryGetUserMethodForCompilerGeneratedMember(TypeSystemEntity sourceMe if (userMethod != null) { - Debug.Assert(!CompilerGeneratedState.IsNestedFunctionOrStateMachineMember(userMethod)); + Debug.Assert(!IsNestedFunctionOrStateMachineMember(userMethod)); return true; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/DiagnosticContext.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/DiagnosticContext.cs index 85dbe6df084970..b05470c724d32c 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/DiagnosticContext.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/DiagnosticContext.cs @@ -11,11 +11,11 @@ namespace ILLink.Shared.TrimAnalysis public readonly partial struct DiagnosticContext { public readonly MessageOrigin Origin; - readonly bool _diagnosticsEnabled; - readonly bool _suppressTrimmerDiagnostics; - readonly bool _suppressAotDiagnostics; - readonly bool _suppressSingleFileDiagnostics; - readonly Logger _logger; + private readonly bool _diagnosticsEnabled; + private readonly bool _suppressTrimmerDiagnostics; + private readonly bool _suppressAotDiagnostics; + private readonly bool _suppressSingleFileDiagnostics; + private readonly Logger _logger; public DiagnosticContext(in MessageOrigin origin, bool diagnosticsEnabled, Logger logger) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/DiagnosticUtilities.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/DiagnosticUtilities.cs index af70f21e31233b..da271c2fb5f1a7 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/DiagnosticUtilities.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/DiagnosticUtilities.cs @@ -1,17 +1,15 @@ // 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.Diagnostics.CodeAnalysis; using System.Reflection.Metadata; -using ILLink.Shared; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler.Dataflow { - static class DiagnosticUtilities + internal static class DiagnosticUtilities { internal static Origin GetMethodParameterFromIndex(MethodDesc method, int parameterIndex) { @@ -151,7 +149,7 @@ internal static bool IsInRequiresScope(this MethodDesc method, string requiresAt /// Doesn't check the associated symbol for overrides and virtual methods because we should warn on mismatched between the property AND the accessors /// /// - /// MethodDesc that is either an overriding member or an overridden/virtual member + /// MethodDesc that is either an overriding member or an overridden/virtual member /// internal static bool IsOverrideInRequiresScope(this MethodDesc method, string requiresAttribute) => method.IsInRequiresScope(requiresAttribute, false); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/EcmaExtensions.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/EcmaExtensions.cs index 5d91895e35711d..b13bf5556eef9f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/EcmaExtensions.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/EcmaExtensions.cs @@ -15,7 +15,7 @@ namespace ILCompiler.Dataflow { - static class EcmaExtensions + internal static class EcmaExtensions { public static bool IsPublic(this MethodDesc method) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/FieldValue.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/FieldValue.cs index 3c23fba55f5f3b..d20d5962c5ecc9 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/FieldValue.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/FieldValue.cs @@ -16,7 +16,7 @@ namespace ILLink.Shared.TrimAnalysis /// /// A representation of a field. Typically a result of ldfld. /// - sealed partial record FieldValue : IValueWithStaticType + internal sealed partial record FieldValue : IValueWithStaticType { public FieldValue(FieldDesc field, DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/FlowAnnotations.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/FlowAnnotations.cs index 270f578fbdfd29..eaccfc76e196ee 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/FlowAnnotations.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/FlowAnnotations.cs @@ -25,7 +25,7 @@ namespace ILLink.Shared.TrimAnalysis /// /// Caches dataflow annotations for type members. /// - sealed public partial class FlowAnnotations + public sealed partial class FlowAnnotations { private readonly TypeAnnotationsHashtable _hashtable; private readonly Logger _logger; @@ -285,7 +285,7 @@ private TypeAnnotations GetAnnotations(TypeDesc type) return _hashtable.GetOrCreateValue(type); } - private class TypeAnnotationsHashtable : LockFreeReaderHashtable + private sealed class TypeAnnotationsHashtable : LockFreeReaderHashtable { private readonly ILProvider _ilProvider; private readonly Logger _logger; @@ -356,7 +356,7 @@ protected override TypeAnnotations CreateValueFromKey(TypeDesc key) // If the class hierarchy is not walkable, just stop collecting the annotations. } - var annotatedFields = new ArrayBuilder(); + var annotatedFields = default(ArrayBuilder); // First go over all fields with an explicit annotation foreach (EcmaField field in ecmaType.GetFields()) @@ -379,7 +379,7 @@ protected override TypeAnnotations CreateValueFromKey(TypeDesc key) annotatedFields.Add(new FieldAnnotation(field, annotation)); } - var annotatedMethods = new ArrayBuilder(); + var annotatedMethods = default(ArrayBuilder); // Next go over all methods with an explicit annotation foreach (EcmaMethod method in ecmaType.GetMethods()) @@ -458,10 +458,7 @@ protected override TypeAnnotations CreateValueFromKey(TypeDesc key) continue; } - if (paramAnnotations == null) - { - paramAnnotations = new DynamicallyAccessedMemberTypes[signature.Length + offset]; - } + paramAnnotations ??= new DynamicallyAccessedMemberTypes[signature.Length + offset]; paramAnnotations[parameter.SequenceNumber - 1 + offset] = pa; } } @@ -473,8 +470,7 @@ protected override TypeAnnotations CreateValueFromKey(TypeDesc key) var annotation = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, genericParameterDef.GetCustomAttributes()); if (annotation != DynamicallyAccessedMemberTypes.None) { - if (genericParameterAnnotations == null) - genericParameterAnnotations = new DynamicallyAccessedMemberTypes[method.Instantiation.Length]; + genericParameterAnnotations ??= new DynamicallyAccessedMemberTypes[method.Instantiation.Length]; genericParameterAnnotations[genericParameter.Index] = annotation; } } @@ -614,8 +610,7 @@ protected override TypeAnnotations CreateValueFromKey(TypeDesc key) var annotation = GetMemberTypesForDynamicallyAccessedMembersAttribute(reader, genericParameterDef.GetCustomAttributes()); if (annotation != DynamicallyAccessedMemberTypes.None) { - if (typeGenericParameterAnnotations == null) - typeGenericParameterAnnotations = new DynamicallyAccessedMemberTypes[ecmaType.Instantiation.Length]; + typeGenericParameterAnnotations ??= new DynamicallyAccessedMemberTypes[ecmaType.Instantiation.Length]; typeGenericParameterAnnotations[genericParameterIndex] = annotation; } } @@ -749,7 +744,7 @@ internal void ValidateMethodAnnotationsAreSame(MethodDesc method, MethodDesc bas } } - void ValidateMethodParametersHaveNoAnnotations(DynamicallyAccessedMemberTypes[] parameterAnnotations, MethodDesc method, MethodDesc baseMethod, MethodDesc origin) + private void ValidateMethodParametersHaveNoAnnotations(DynamicallyAccessedMemberTypes[] parameterAnnotations, MethodDesc method, MethodDesc baseMethod, MethodDesc origin) { for (int parameterIndex = 0; parameterIndex < parameterAnnotations.Length; parameterIndex++) { @@ -762,7 +757,7 @@ void ValidateMethodParametersHaveNoAnnotations(DynamicallyAccessedMemberTypes[] } } - void ValidateMethodGenericParametersHaveNoAnnotations(DynamicallyAccessedMemberTypes[] genericParameterAnnotations, MethodDesc method, MethodDesc baseMethod, MethodDesc origin) + private void ValidateMethodGenericParametersHaveNoAnnotations(DynamicallyAccessedMemberTypes[] genericParameterAnnotations, MethodDesc method, MethodDesc baseMethod, MethodDesc origin) { for (int genericParameterIndex = 0; genericParameterIndex < genericParameterAnnotations.Length; genericParameterIndex++) { @@ -776,7 +771,7 @@ void ValidateMethodGenericParametersHaveNoAnnotations(DynamicallyAccessedMemberT } } - void LogValidationWarning(object provider, object baseProvider, MethodDesc origin) + private void LogValidationWarning(object provider, object baseProvider, MethodDesc origin) { switch (provider) { @@ -790,7 +785,7 @@ void LogValidationWarning(object provider, object baseProvider, MethodDesc origi genericParameterOverride.Name, DiagnosticUtilities.GetGenericParameterDeclaringMemberDisplayName(new GenericParameterOrigin(genericParameterOverride)), ((GenericParameterDesc)baseProvider).Name, DiagnosticUtilities.GetGenericParameterDeclaringMemberDisplayName(new GenericParameterOrigin((GenericParameterDesc)baseProvider))); break; - case TypeDesc methodReturnType: + case TypeDesc: _logger.LogWarning(origin, DiagnosticId.DynamicallyAccessedMembersMismatchOnMethodReturnValueBetweenOverrides, DiagnosticUtilities.GetMethodSignatureDisplayName(origin), DiagnosticUtilities.GetMethodSignatureDisplayName((MethodDesc)baseProvider)); break; @@ -804,7 +799,7 @@ void LogValidationWarning(object provider, object baseProvider, MethodDesc origi } } - private class TypeAnnotations + private sealed class TypeAnnotations { public readonly TypeDesc Type; public readonly DynamicallyAccessedMemberTypes TypeAnnotation; @@ -932,7 +927,9 @@ public FieldAnnotation(FieldDesc field, DynamicallyAccessedMemberTypes annotatio internal partial bool MethodRequiresDataFlowAnalysis(MethodProxy method) => RequiresDataflowAnalysis(method.Method); +#pragma warning disable CA1822 // Other partial implementations are not in the ilc project internal partial MethodReturnValue GetMethodReturnValue(MethodProxy method, DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes) +#pragma warning restore CA1822 // Mark members as static => new MethodReturnValue(method.Method, dynamicallyAccessedMemberTypes); internal partial MethodReturnValue GetMethodReturnValue(MethodProxy method) @@ -949,7 +946,9 @@ internal partial MethodThisParameterValue GetMethodThisParameterValue(MethodProx internal partial MethodThisParameterValue GetMethodThisParameterValue(MethodProxy method) => GetMethodThisParameterValue(method, GetParameterAnnotation(method.Method, 0)); +#pragma warning disable CA1822 // Other partial implementations are not in the ilc project internal partial MethodParameterValue GetMethodParameterValue(MethodProxy method, int parameterIndex, DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes) +#pragma warning restore CA1822 // Mark members as static => new(method.Method, parameterIndex, dynamicallyAccessedMemberTypes); internal partial MethodParameterValue GetMethodParameterValue(MethodProxy method, int parameterIndex) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/GenericArgumentDataFlow.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/GenericArgumentDataFlow.cs index 1bdc58eee2922d..071f2bed0fbaf2 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/GenericArgumentDataFlow.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/GenericArgumentDataFlow.cs @@ -20,10 +20,10 @@ namespace ILCompiler.Dataflow { public readonly struct GenericArgumentDataFlow { - readonly Logger _logger; - readonly NodeFactory _factory; - readonly FlowAnnotations _annotations; - readonly MessageOrigin _origin; + private readonly Logger _logger; + private readonly NodeFactory _factory; + private readonly FlowAnnotations _annotations; + private readonly MessageOrigin _origin; public GenericArgumentDataFlow(Logger logger, NodeFactory factory, FlowAnnotations annotations, in MessageOrigin origin) { @@ -47,7 +47,7 @@ public DependencyList ProcessGenericArgumentDataFlow(GenericParameterDesc generi return RequireDynamicallyAccessedMembers(diagnosticContext, genericArgumentValue, genericParameterValue, new GenericParameterOrigin(genericParameter)); } - DependencyList RequireDynamicallyAccessedMembers( + private DependencyList RequireDynamicallyAccessedMembers( in DiagnosticContext diagnosticContext, in MultiValue value, ValueWithDynamicallyAccessedMembers targetValue, diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/GenericParameterValue.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/GenericParameterValue.cs index 423b17c54d5f1a..3e7ef0550d098a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/GenericParameterValue.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/GenericParameterValue.cs @@ -15,7 +15,7 @@ namespace ILLink.Shared.TrimAnalysis /// This is a System.Type value which represents generic parameter (basically result of typeof(T)) /// Its actual type is unknown, but it can have annotations. /// - partial record GenericParameterValue + internal partial record GenericParameterValue { public GenericParameterValue(GenericParameterDesc genericParameter, DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HandleCallAction.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HandleCallAction.cs index e885dc796f9f54..4fdb6c2f8b9f3c 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HandleCallAction.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HandleCallAction.cs @@ -14,13 +14,13 @@ namespace ILLink.Shared.TrimAnalysis { - partial struct HandleCallAction + internal partial struct HandleCallAction { #pragma warning disable CA1822 // Mark members as static - the other partial implementations might need to be instance methods - readonly ReflectionMarker _reflectionMarker; - readonly MethodDesc _callingMethod; - readonly Origin _memberWithRequirements; + private readonly ReflectionMarker _reflectionMarker; + private readonly MethodDesc _callingMethod; + private readonly Origin _memberWithRequirements; public HandleCallAction( FlowAnnotations annotations, diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HoistedLocalKey.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HoistedLocalKey.cs index 11be949bed019d..289a62232bfc8e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HoistedLocalKey.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HoistedLocalKey.cs @@ -15,7 +15,7 @@ namespace ILCompiler.Dataflow // or local functions). public readonly struct HoistedLocalKey : IEquatable { - readonly FieldDesc Field; + private readonly FieldDesc Field; public HoistedLocalKey(FieldDesc field) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/IValueWithStaticType.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/IValueWithStaticType.cs index eb08e77d0171e1..85d1fe273956f8 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/IValueWithStaticType.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/IValueWithStaticType.cs @@ -7,7 +7,7 @@ namespace ILCompiler.Dataflow { - interface IValueWithStaticType + internal interface IValueWithStaticType { /// /// The IL type of the value, represented as closely as possible, but not always exact. It can be null, for diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/InterproceduralState.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/InterproceduralState.cs index 304fa353d69e84..d76f69fd41d3ae 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/InterproceduralState.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/InterproceduralState.cs @@ -20,7 +20,7 @@ namespace ILCompiler.Dataflow { // Wrapper that implements IEquatable for MethodBody. - readonly record struct MethodBodyValue(MethodIL MethodBody) : IEquatable + internal readonly record struct MethodBodyValue(MethodIL MethodBody) : IEquatable { bool IEquatable.Equals(ILCompiler.Dataflow.MethodBodyValue other) => other.MethodBody.OwningMethod == MethodBody.OwningMethod; @@ -30,12 +30,14 @@ bool IEquatable.Equals(ILCompiler.Dataflow.MethodBodyValue othe // Tracks the set of methods which get analyzer together during interprocedural analysis, // and the possible states of hoisted locals in state machine methods and lambdas/local functions. - struct InterproceduralState : IEquatable +#pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable + internal struct InterproceduralState : IEquatable +#pragma warning restore CA1067 // Override Object.Equals(object) when implementing IEquatable { - readonly ILProvider _ilProvider; + private readonly ILProvider _ilProvider; public ValueSet MethodBodies; public HoistedLocalState HoistedLocals; - readonly InterproceduralStateLattice lattice; + private readonly InterproceduralStateLattice lattice; public InterproceduralState(ILProvider ilProvider, ValueSet methodBodies, HoistedLocalState hoistedLocals, InterproceduralStateLattice lattice) => (_ilProvider, MethodBodies, HoistedLocals, this.lattice) = (ilProvider, methodBodies, hoistedLocals, lattice); @@ -119,7 +121,7 @@ public void SetHoistedLocal(HoistedLocalKey key, MultiValue value) public MultiValue GetHoistedLocal(HoistedLocalKey key) => HoistedLocals.Get(key); - bool TryGetMethodBody(MethodDesc method, [NotNullWhen(true)] out MethodIL? methodBody) + private bool TryGetMethodBody(MethodDesc method, [NotNullWhen(true)] out MethodIL? methodBody) { methodBody = null; @@ -135,7 +137,7 @@ bool TryGetMethodBody(MethodDesc method, [NotNullWhen(true)] out MethodIL? metho } } - struct InterproceduralStateLattice : ILattice + internal struct InterproceduralStateLattice : ILattice { private readonly ILProvider _ilProvider; public readonly ValueSetLattice MethodBodyLattice; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodBodyScanner.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodBodyScanner.cs index 428d5658bedabd..0fa9c843faf717 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodBodyScanner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodBodyScanner.cs @@ -26,7 +26,7 @@ namespace ILCompiler.Dataflow /// /// Tracks information about the contents of a stack slot /// - readonly struct StackSlot + internal readonly struct StackSlot { public MultiValue Value { get; } @@ -46,14 +46,14 @@ public StackSlot(MultiValue value) } } - abstract partial class MethodBodyScanner + internal abstract partial class MethodBodyScanner { protected readonly InterproceduralStateLattice InterproceduralStateLattice; protected static ValueSetLattice MultiValueLattice => default; protected readonly FlowAnnotations _annotations; - internal MultiValue ReturnValue { private set; get; } + internal MultiValue ReturnValue { get; private set; } protected MethodBodyScanner(FlowAnnotations annotations) { @@ -160,10 +160,10 @@ private static void NewKnownStack(Dictionary> knownStacks, private struct BasicBlockIterator { - readonly HashSet _methodBranchTargets; - int _currentBlockIndex; - bool _foundEndOfPrevBlock; - MethodIL _methodBody; + private readonly HashSet _methodBranchTargets; + private int _currentBlockIndex; + private bool _foundEndOfPrevBlock; + private MethodIL _methodBody; public BasicBlockIterator(MethodIL methodBody) { @@ -202,7 +202,7 @@ public int MoveNext(int offset) } [Conditional("DEBUG")] - static void ValidateNoReferenceToReference(ValueBasicBlockPair?[] locals, MethodIL method, int ilOffset) + private static void ValidateNoReferenceToReference(ValueBasicBlockPair?[] locals, MethodIL method, int ilOffset) { for (int localVariableIndex = 0; localVariableIndex < locals.Length; localVariableIndex++) { @@ -241,14 +241,14 @@ private static void StoreMethodLocalValue( if (!existingValue.HasValue || existingValue.Value.BasicBlockIndex == curBasicBlock) { - // If the previous value was stored in the current basic block, then we can safely + // If the previous value was stored in the current basic block, then we can safely // overwrite the previous value with the new one. value = valueToStore; } else { - // If the previous value came from a previous basic block, then some other use of - // the local could see the previous value, so we must merge the new value with the + // If the previous value came from a previous basic block, then some other use of + // the local could see the previous value, so we must merge the new value with the // old value. value = MultiValueLattice.Meet(existingValue.Value.Value, valueToStore); } @@ -269,14 +269,14 @@ private static void StoreMethodLocalValue( if (existingValue.BasicBlockIndex == curBasicBlock) { - // If the previous value was stored in the current basic block, then we can safely + // If the previous value was stored in the current basic block, then we can safely // overwrite the previous value with the new one. value = valueToStore; } else { - // If the previous value came from a previous basic block, then some other use of - // the local could see the previous value, so we must merge the new value with the + // If the previous value came from a previous basic block, then some other use of + // the local could see the previous value, so we must merge the new value with the // old value. value = MultiValueLattice.Meet(existingValue.Value, valueToStore); } @@ -328,7 +328,7 @@ public virtual void InterproceduralScan(MethodIL startingMethodBody) // Disabled asserts due to a bug // Debug.Assert (interproceduralState.Count == 1 + calleeMethods.Count ()); // foreach (var method in calleeMethods) - // Debug.Assert (interproceduralState.Any (kvp => kvp.Key.Method == method)); + // Debug.Assert (interproceduralState.Any (kvp => kvp.Key.Method == method)); } else { @@ -337,7 +337,7 @@ public virtual void InterproceduralScan(MethodIL startingMethodBody) #endif } - void TrackNestedFunctionReference(MethodDesc referencedMethod, ref InterproceduralState interproceduralState) + private static void TrackNestedFunctionReference(MethodDesc referencedMethod, ref InterproceduralState interproceduralState) { MethodDesc method = referencedMethod.GetTypicalMethodDefinition(); @@ -360,7 +360,7 @@ protected virtual void Scan(MethodIL methodBody, ref InterproceduralState interp BasicBlockIterator blockIterator = new BasicBlockIterator(methodBody); - ReturnValue = new(); + ReturnValue = default(MultiValue); ILReader reader = new ILReader(methodBody.GetILBytes()); while (reader.HasNext) { @@ -380,10 +380,7 @@ protected virtual void Scan(MethodIL methodBody, ref InterproceduralState interp } } - if (currentStack == null) - { - currentStack = new Stack(methodBody.MaxStack); - } + currentStack ??= new Stack(methodBody.MaxStack); int offset = reader.Offset; ILOpcode opcode = reader.ReadILOpcode(); @@ -790,7 +787,7 @@ protected virtual void Scan(MethodIL methodBody, ref InterproceduralState interp { StackSlot retValue = PopUnknown(currentStack, 1, methodBody, offset); // If the return value is a reference, treat it as the value itself for now - // We can handle ref return values better later + // We can handle ref return values better later ReturnValue = MultiValueLattice.Meet(ReturnValue, DereferenceValue(retValue.Value, locals, ref interproceduralState)); } ClearStack(ref currentStack); @@ -899,7 +896,7 @@ Stack currentStack // If the targetValue is MethodThisValue do nothing - it should never happen really, and if it does, there's nothing we can track there } - private void ScanLdloc( + private static void ScanLdloc( MethodIL methodBody, int offset, ILOpcode operation, diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodParameterValue.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodParameterValue.cs index b8e5e728030840..939774bdbb093d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodParameterValue.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodParameterValue.cs @@ -15,7 +15,7 @@ namespace ILLink.Shared.TrimAnalysis /// /// A value that came from a method parameter - such as the result of a ldarg. /// - partial record MethodParameterValue : IValueWithStaticType + internal partial record MethodParameterValue : IValueWithStaticType { public MethodParameterValue(MethodDesc method, int parameterIndex, DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodProxy.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodProxy.cs index 4795258de4a155..10bc11748a8e06 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodProxy.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodProxy.cs @@ -12,7 +12,7 @@ namespace ILLink.Shared.TypeSystemProxy { - readonly partial struct MethodProxy : IEquatable + internal readonly partial struct MethodProxy : IEquatable { public MethodProxy(MethodDesc method) => Method = method; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodReturnValue.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodReturnValue.cs index 552e971a059e3c..2162383cfb5744 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodReturnValue.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodReturnValue.cs @@ -14,7 +14,7 @@ namespace ILLink.Shared.TrimAnalysis /// /// Return value from a method /// - partial record MethodReturnValue : IValueWithStaticType + internal partial record MethodReturnValue : IValueWithStaticType { public MethodReturnValue(MethodDesc method, DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodThisParameterValue.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodThisParameterValue.cs index b04698e26d07ac..4597849963ba91 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodThisParameterValue.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodThisParameterValue.cs @@ -16,7 +16,7 @@ namespace ILLink.Shared.TrimAnalysis /// /// A value that came from the implicit this parameter of a method /// - partial record MethodThisParameterValue : IValueWithStaticType + internal partial record MethodThisParameterValue : IValueWithStaticType { public MethodThisParameterValue(MethodDesc method, DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/Origin.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/Origin.cs index 2668a4696cc5eb..13b6cf85447e8c 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/Origin.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/Origin.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using Internal.TypeSystem; -using Internal.TypeSystem.Ecma; namespace ILCompiler.Dataflow { @@ -10,7 +9,7 @@ internal abstract class Origin { } - class MethodReturnOrigin : Origin + internal sealed class MethodReturnOrigin : Origin { public MethodDesc Method { get; } @@ -22,7 +21,7 @@ public MethodReturnOrigin(MethodDesc method) public string GetDisplayName() => Method.GetDisplayName(); } - class ParameterOrigin : Origin + internal sealed class ParameterOrigin : Origin { public MethodDesc Method { get; } public int Index { get; } @@ -36,7 +35,7 @@ public ParameterOrigin(MethodDesc method, int index) public string GetDisplayName() => Method.GetDisplayName(); } - class MethodOrigin : Origin + internal sealed class MethodOrigin : Origin { public MethodDesc Method { get; } @@ -48,7 +47,7 @@ public MethodOrigin(MethodDesc method) public string GetDisplayName() => Method.GetDisplayName(); } - class FieldOrigin : Origin + internal sealed class FieldOrigin : Origin { public FieldDesc Field { get; } @@ -60,7 +59,7 @@ public FieldOrigin(FieldDesc field) public string GetDisplayName() => Field.GetDisplayName(); } - class TypeOrigin : Origin + internal sealed class TypeOrigin : Origin { public MetadataType Type { get; } @@ -72,7 +71,7 @@ public TypeOrigin(MetadataType type) public string GetDisplayName() => Type.GetDisplayName(); } - class GenericParameterOrigin : Origin + internal sealed class GenericParameterOrigin : Origin { public GenericParameterDesc GenericParameter { get; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMarker.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMarker.cs index c20596b08e45f8..79ee807c27d6e7 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMarker.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMarker.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; @@ -74,7 +73,7 @@ internal bool TryResolveTypeNameAndMark(string typeName, in DiagnosticContext di // NativeAOT doesn't have a fully capable type name resolver yet // Once this is implemented don't forget to wire up marking of type forwards which are used in generic parameters - if (!ILCompiler.DependencyAnalysis.ReflectionMethodBodyScanner.ResolveType(typeName, callingModule, diagnosticContext.Origin.MemberDefinition!.Context, out TypeDesc foundType, out ModuleDesc referenceModule)) + if (!DependencyAnalysis.ReflectionMethodBodyScanner.ResolveType(typeName, callingModule, diagnosticContext.Origin.MemberDefinition!.Context, out TypeDesc foundType, out ModuleDesc referenceModule)) { type = default; return false; @@ -111,7 +110,7 @@ internal void MarkMethod(in MessageOrigin origin, MethodDesc method, Origin memb RootingHelpers.TryGetDependenciesForReflectedMethod(ref _dependencies, Factory, method, memberWithRequirements.ToString()); } - void MarkField(in MessageOrigin origin, FieldDesc field, Origin memberWithRequirements) + private void MarkField(in MessageOrigin origin, FieldDesc field, Origin memberWithRequirements) { if (!_enabled) return; @@ -132,7 +131,7 @@ internal void MarkProperty(in MessageOrigin origin, PropertyPseudoDesc property, MarkMethod(origin, property.SetMethod, memberWithRequirements); } - void MarkEvent(in MessageOrigin origin, EventPseudoDesc @event, Origin memberWithRequirements) + private void MarkEvent(in MessageOrigin origin, EventPseudoDesc @event, Origin memberWithRequirements) { if (!_enabled) return; @@ -192,7 +191,7 @@ internal void MarkStaticConstructor(in MessageOrigin origin, TypeDesc type) } } - void CheckAndWarnOnReflectionAccess(in MessageOrigin origin, TypeSystemEntity entity, Origin memberWithRequirements) + private void CheckAndWarnOnReflectionAccess(in MessageOrigin origin, TypeSystemEntity entity, Origin memberWithRequirements) { if (entity.DoesMemberRequire(DiagnosticUtilities.RequiresUnreferencedCodeAttribute, out CustomAttributeValue? requiresAttribute)) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMethodBodyScanner.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMethodBodyScanner.cs index c6c3705b9551ad..3f075847110cd0 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMethodBodyScanner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMethodBodyScanner.cs @@ -2,23 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Reflection; -using System.Reflection.Metadata; using ILCompiler.Logging; using ILLink.Shared; -using ILLink.Shared.DataFlow; using ILLink.Shared.TrimAnalysis; -using ILLink.Shared.TypeSystemProxy; using Internal.IL; using Internal.TypeSystem; - -using CustomAttributeNamedArgumentKind = System.Reflection.Metadata.CustomAttributeNamedArgumentKind; -using CustomAttributeValue = System.Reflection.Metadata.CustomAttributeValue; using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyList; using InteropTypes = Internal.TypeSystem.Interop.InteropTypes; using MultiValue = ILLink.Shared.DataFlow.ValueSet; @@ -29,7 +21,7 @@ namespace ILCompiler.Dataflow { - sealed class ReflectionMethodBodyScanner : MethodBodyScanner + internal sealed class ReflectionMethodBodyScanner : MethodBodyScanner { private readonly Logger _logger; private readonly NodeFactory _factory; @@ -144,7 +136,7 @@ protected override void WarnAboutInvalidILInMethod(MethodIL method, int ilOffset protected override ValueWithDynamicallyAccessedMembers GetMethodParameterValue(MethodDesc method, int parameterIndex) => GetMethodParameterValue(method, parameterIndex, _annotations.GetParameterAnnotation(method, parameterIndex)); - ValueWithDynamicallyAccessedMembers GetMethodParameterValue(MethodDesc method, int parameterIndex, DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes) + private ValueWithDynamicallyAccessedMembers GetMethodParameterValue(MethodDesc method, int parameterIndex, DynamicallyAccessedMemberTypes dynamicallyAccessedMemberTypes) { if (!method.Signature.IsStatic) { @@ -183,7 +175,6 @@ protected override void HandleStoreMethodReturnValue(MethodIL methodBody, int of public override bool HandleCall(MethodIL callingMethodBody, MethodDesc calledMethod, ILOpcode operation, int offset, ValueNodeList methodParams, out MultiValue methodReturnValue) { - methodReturnValue = null; Debug.Assert(callingMethodBody.OwningMethod == _origin.MemberDefinition); _origin = _origin.WithInstructionOffset(callingMethodBody, offset); @@ -570,14 +561,14 @@ void AddReturnValue(MultiValue value) } } - static bool IsAotUnsafeDelegate(TypeDesc parameterType) + private static bool IsAotUnsafeDelegate(TypeDesc parameterType) { TypeSystemContext context = parameterType.Context; return parameterType.IsWellKnownType(Internal.TypeSystem.WellKnownType.MulticastDelegate) || parameterType == context.GetWellKnownType(Internal.TypeSystem.WellKnownType.MulticastDelegate).BaseType; } - static bool IsComInterop(MarshalAsDescriptor? marshalInfoProvider, TypeDesc parameterType) + private static bool IsComInterop(MarshalAsDescriptor? marshalInfoProvider, TypeDesc parameterType) { // This is best effort. One can likely find ways how to get COM without triggering these alarms. // AsAny marshalling of a struct with an object-typed field would be one, for example. @@ -656,7 +647,7 @@ static bool IsComInterop(MarshalAsDescriptor? marshalInfoProvider, TypeDesc para return false; } - void HandleAssignmentPattern( + private void HandleAssignmentPattern( in MessageOrigin origin, in MultiValue value, ValueWithDynamicallyAccessedMembers targetValue, diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/RequireDynamicallyAccessedMembersAction.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/RequireDynamicallyAccessedMembersAction.cs index 0b6abdb478faea..b4eb5fa48eec13 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/RequireDynamicallyAccessedMembersAction.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/RequireDynamicallyAccessedMembersAction.cs @@ -10,10 +10,10 @@ namespace ILLink.Shared.TrimAnalysis { - partial struct RequireDynamicallyAccessedMembersAction + internal partial struct RequireDynamicallyAccessedMembersAction { - readonly ReflectionMarker _reflectionMarker; - readonly Origin _memberWithRequirements; + private readonly ReflectionMarker _reflectionMarker; + private readonly Origin _memberWithRequirements; public RequireDynamicallyAccessedMembersAction( ReflectionMarker reflectionMarker, diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ScannerExtensions.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ScannerExtensions.cs index 4a63effd608026..df87273214673d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ScannerExtensions.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ScannerExtensions.cs @@ -1,13 +1,9 @@ // 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 Internal.IL; -using Internal.TypeSystem; - -using Debug = System.Diagnostics.Debug; namespace ILCompiler.Dataflow { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TrimAnalysisPatternStore.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TrimAnalysisPatternStore.cs index e728a5599ff85d..44ff8eabf39ab5 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TrimAnalysisPatternStore.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TrimAnalysisPatternStore.cs @@ -12,10 +12,10 @@ namespace ILCompiler.Dataflow { public readonly struct TrimAnalysisPatternStore { - readonly Dictionary<(MessageOrigin, bool), TrimAnalysisAssignmentPattern> AssignmentPatterns; - readonly Dictionary MethodCallPatterns; - readonly ValueSetLattice Lattice; - readonly Logger _logger; + private readonly Dictionary<(MessageOrigin, bool), TrimAnalysisAssignmentPattern> AssignmentPatterns; + private readonly Dictionary MethodCallPatterns; + private readonly ValueSetLattice Lattice; + private readonly Logger _logger; public TrimAnalysisPatternStore(ValueSetLattice lattice, Logger logger) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TypeExtensions.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TypeExtensions.cs index d8a0311b5a663f..8109b19732ff8a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TypeExtensions.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TypeExtensions.cs @@ -2,10 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections; using ILLink.Shared.TypeSystemProxy; using Internal.TypeSystem; -using Internal.TypeSystem.Ecma; using TypeSystemWellKnownType = Internal.TypeSystem.WellKnownType; using ILLinkSharedWellKnownType = ILLink.Shared.TypeSystemProxy.WellKnownType; @@ -14,7 +12,7 @@ namespace ILCompiler.Dataflow { - static class TypeExtensions + internal static class TypeExtensions { public static bool IsTypeOf(this TypeDesc type, string ns, string name) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ValueNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ValueNode.cs index 8e22a0c9fc96fc..f18186d768b04d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ValueNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ValueNode.cs @@ -28,7 +28,7 @@ public ValueNodeList(List other) public override int GetHashCode() { - HashCode hashCode = new HashCode(); + HashCode hashCode = default(HashCode); foreach (var item in this) hashCode.Add(item.GetHashCode()); return hashCode.ToHashCode(); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ArrayOfEmbeddedDataNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ArrayOfEmbeddedDataNode.cs index bc6a93c776aefc..beaa6c24c357e0 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ArrayOfEmbeddedDataNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ArrayOfEmbeddedDataNode.cs @@ -1,12 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Generic; -using System.Diagnostics; -using System.Text; -using ILCompiler.DependencyAnalysisFramework; -using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { @@ -31,7 +26,7 @@ public ArrayOfEmbeddedDataNode(string startSymbolMangledName, string endSymbolMa { _sorter = nodeSorter; } - + public void AddEmbeddedObject(TEmbedded symbol) { lock (_nestedNodes) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ArrayOfEmbeddedPointersNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ArrayOfEmbeddedPointersNode.cs index 2d426c40a62962..ba9e73eccfbfee 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ArrayOfEmbeddedPointersNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ArrayOfEmbeddedPointersNode.cs @@ -43,7 +43,7 @@ public EmbeddedObjectNode NewNodeWithSymbol(TTarget target) return new EmbeddedPointerIndirectionWithSymbolNode(this, target, GetNextId()); } - int GetNextId() + private int GetNextId() { return System.Threading.Interlocked.Increment(ref _nextId); } @@ -52,7 +52,7 @@ int GetNextId() public override int ClassCode => (int)ObjectNodeOrder.ArrayOfEmbeddedPointersNode; - private class PointerIndirectionNodeComparer : IComparer> + private sealed class PointerIndirectionNodeComparer : IComparer> { private IComparer _innerComparer; @@ -98,7 +98,7 @@ public override IEnumerable GetStaticDependencies(NodeFacto public override int ClassCode => -66002498; } - private class EmbeddedPointerIndirectionWithSymbolNode : SimpleEmbeddedPointerIndirectionNode, ISymbolDefinitionNode + private sealed class EmbeddedPointerIndirectionWithSymbolNode : SimpleEmbeddedPointerIndirectionNode, ISymbolDefinitionNode { private int _id; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ArrayOfFrozenObjectsNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ArrayOfFrozenObjectsNode.cs index e2bc6c4b70ec8e..b6d8ba5147f4b6 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ArrayOfFrozenObjectsNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ArrayOfFrozenObjectsNode.cs @@ -1,7 +1,6 @@ // 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 Internal.TypeSystem; @@ -15,7 +14,7 @@ public ArrayOfFrozenObjectsNode(string startSymbolMangledName, string endSymbolM { } - private void AlignNextObject(ref ObjectDataBuilder builder, NodeFactory factory) + private static void AlignNextObject(ref ObjectDataBuilder builder, NodeFactory factory) { builder.EmitZeros(AlignmentHelper.AlignUp(builder.CountBytes, factory.Target.PointerSize) - builder.CountBytes); } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/BlobNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/BlobNode.cs index 9e9a393c8f82d2..bee1c395219f89 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/BlobNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/BlobNode.cs @@ -4,7 +4,6 @@ using System; using Internal.Text; -using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/BlockReflectionTypeMapNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/BlockReflectionTypeMapNode.cs index 0020d0581f243d..184ab830eaf8cc 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/BlockReflectionTypeMapNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/BlockReflectionTypeMapNode.cs @@ -61,10 +61,10 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) if (!factory.MetadataManager.IsReflectionBlocked(mdType)) continue; - + if (!factory.CompilationModuleGroup.ContainsType(mdType)) continue; - + // Go with a necessary type symbol. It will be upgraded to a constructed one if a constructed was emitted. IEETypeNode typeSymbol = factory.NecessaryTypeSymbol(type); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CallingConventionConverterKey.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CallingConventionConverterKey.cs index 40b7281dbba01b..bad73673193beb 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CallingConventionConverterKey.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CallingConventionConverterKey.cs @@ -98,7 +98,7 @@ public override void AppendName(StringBuilder sb, GenericParameterDesc type) public override void AppendName(StringBuilder sb, SignatureTypeVariable type) { - sb.Append("!"); + sb.Append('!'); sb.Append(type.Index.ToStringInvariant()); } @@ -177,7 +177,7 @@ protected override void AppendNameForNamespaceType(StringBuilder sb, DefType typ } } - private void AppendAssemblyName(StringBuilder sb, IAssemblyDesc assembly) + private static void AppendAssemblyName(StringBuilder sb, IAssemblyDesc assembly) { if (assembly == null) return; @@ -201,18 +201,18 @@ protected override void AppendNameForNestedType(StringBuilder sb, DefType nested AppendEscapedIdentifier(sb, GetTypeName(nestedType)); } - private string GetTypeName(DefType type) + private static string GetTypeName(DefType type) { return type.Name; } - private string GetTypeNamespace(DefType type) + private static string GetTypeNamespace(DefType type) { return type.Namespace; } private static char[] s_escapedChars = new char[] { ',', '=', '"', ']', '[', '*', '&', '+', '\\' }; - private void AppendEscapedIdentifier(StringBuilder sb, string identifier) + private static void AppendEscapedIdentifier(StringBuilder sb, string identifier) { if (identifier.IndexOfAny(s_escapedChars) < 0) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CanonicalDefinitionEETypeNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CanonicalDefinitionEETypeNode.cs index a598bfe9961f1b..6d6050c5eb2722 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CanonicalDefinitionEETypeNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CanonicalDefinitionEETypeNode.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Diagnostics; using Internal.TypeSystem; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CanonicalEETypeNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CanonicalEETypeNode.cs index 772f2ed66d99d6..90555997d7e652 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CanonicalEETypeNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CanonicalEETypeNode.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Diagnostics; using Internal.TypeSystem; @@ -13,8 +11,8 @@ namespace ILCompiler.DependencyAnalysis /// /// Canonical type instantiations are emitted, not because they are used directly by the user code, but because /// they are used by the dynamic type loader when dynamically instantiating types at runtime. - /// The data that we emit on canonical type instantiations should just be the minimum that is needed by the template - /// type loader. + /// The data that we emit on canonical type instantiations should just be the minimum that is needed by the template + /// type loader. /// Similarly, the dependencies that we track for canonical type instantiations are minimal, and are just the ones used /// by the dynamic type loader /// @@ -109,7 +107,7 @@ protected override void OutputGCDesc(ref ObjectDataBuilder builder) protected override void OutputInterfaceMap(NodeFactory factory, ref ObjectDataBuilder objData) { - foreach (var itf in _type.RuntimeInterfaces) + for (int i = 0; i < _type.RuntimeInterfaces.Length; i++) { // Interface omitted for canonical instantiations (constructed at runtime for dynamic types from the native layout info) objData.EmitZeroPointer(); @@ -126,7 +124,7 @@ protected override int BaseSize if (instanceByteCount.IsIndeterminate) { - // For USG types, they may be of indeterminate size, and the size of the type may be meaningless. + // For USG types, they may be of indeterminate size, and the size of the type may be meaningless. // In that case emit a fixed constant. return MinimumObjectSize; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ClassConstructorContextMap.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ClassConstructorContextMap.cs index db7e7b2c353781..f8c39f2a61a93a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ClassConstructorContextMap.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ClassConstructorContextMap.cs @@ -11,7 +11,7 @@ namespace ILCompiler.DependencyAnalysis { - class ClassConstructorContextMap : ObjectNode, ISymbolDefinitionNode + internal sealed class ClassConstructorContextMap : ObjectNode, ISymbolDefinitionNode { private ObjectAndOffsetSymbolNode _endSymbol; private ExternalReferencesTableNode _externalReferences; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CodeBasedDependencyAlgorithm.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CodeBasedDependencyAlgorithm.cs index a879d035d17062..df54d26e3199a7 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CodeBasedDependencyAlgorithm.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CodeBasedDependencyAlgorithm.cs @@ -1,17 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Diagnostics; - using Internal.IL; -using Internal.Text; using Internal.TypeSystem; -using ILCompiler.DependencyAnalysisFramework; - -using DependencyList=ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyList; -using CombinedDependencyList=System.Collections.Generic.List.CombinedDependencyListEntry>; -using DependencyListEntry=ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyListEntry; +using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyList; +using CombinedDependencyList = System.Collections.Generic.List.CombinedDependencyListEntry>; namespace ILCompiler.DependencyAnalysis @@ -57,7 +51,7 @@ public static void AddDependenciesDueToMethodCodePresence(ref DependencyList dep if (templateDependencies != null) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); foreach (TypeDesc templateType in templateDependencies) { dependencies.Add(factory.NativeLayout.TemplateTypeLayout(templateType), "Generic comparer"); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ConstructedEETypeNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ConstructedEETypeNode.cs index 10d5aa6b31df40..01205d68e86aaf 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ConstructedEETypeNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ConstructedEETypeNode.cs @@ -1,12 +1,10 @@ // 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 Internal.Runtime; using Internal.TypeSystem; -using Internal.IL; namespace ILCompiler.DependencyAnalysis { @@ -66,11 +64,11 @@ protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFact { if (instantiationType.IsValueType) { - // All valuetype generic parameters of a constructed type may be effectively constructed. This is generally not that + // All valuetype generic parameters of a constructed type may be effectively constructed. This is generally not that // critical, but in the presence of universal generics the compiler may generate a Box followed by calls to ToString, // GetHashcode or Equals in ways that cannot otherwise be detected by dependency analysis. Thus force all struct type // generic parameters to be considered constructed when walking dependencies of a constructed generic - dependencyList.Add(factory.ConstructedTypeSymbol(instantiationType.ConvertToCanonForm(CanonicalFormKind.Specific)), + dependencyList.Add(factory.ConstructedTypeSymbol(instantiationType.ConvertToCanonForm(CanonicalFormKind.Specific)), "Struct generic parameters in constructed types may be assumed to be used as constructed in constructed generic types"); } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CustomAttributeBasedDependencyAlgorithm.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CustomAttributeBasedDependencyAlgorithm.cs index 3ce2085c08a713..3265e501a8cec1 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CustomAttributeBasedDependencyAlgorithm.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CustomAttributeBasedDependencyAlgorithm.cs @@ -17,7 +17,7 @@ namespace ILCompiler.DependencyAnalysis /// Computes the list of dependencies that are necessary to generate metadata for a custom attribute, but also the dependencies to /// make the custom attributes usable by the reflection stack at runtime. /// - internal class CustomAttributeBasedDependencyAlgorithm + internal static class CustomAttributeBasedDependencyAlgorithm { public static void AddDependenciesDueToCustomAttributes(ref DependencyList dependencies, NodeFactory factory, EcmaMethod method) { @@ -133,7 +133,7 @@ private static void AddDependenciesDueToCustomAttributes(ref DependencyList depe if (AddDependenciesFromCustomAttributeBlob(caDependencies, factory, constructor.OwningType, decodedValue)) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.AddRange(caDependencies); dependencies.Add(factory.CustomAttributeMetadata(new ReflectableCustomAttribute(module, caHandle)), "Attribute metadata"); } @@ -156,8 +156,6 @@ private static void AddDependenciesDueToCustomAttributes(ref DependencyList depe private static bool AddDependenciesFromCustomAttributeBlob(DependencyList dependencies, NodeFactory factory, TypeDesc attributeType, CustomAttributeValue value) { - MetadataManager mdManager = factory.MetadataManager; - foreach (CustomAttributeTypedArgument decodedArgument in value.FixedArguments) { if (!AddDependenciesFromCustomAttributeArgument(dependencies, factory, decodedArgument.Type, decodedArgument.Value)) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CustomAttributeMetadataNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CustomAttributeMetadataNode.cs index 9cb52e99ebb710..7b4706cde57bae 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CustomAttributeMetadataNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/CustomAttributeMetadataNode.cs @@ -5,10 +5,6 @@ using ILCompiler.DependencyAnalysisFramework; -using Internal.TypeSystem; - -using Debug = System.Diagnostics.Debug; - namespace ILCompiler.DependencyAnalysis { /// @@ -17,7 +13,7 @@ namespace ILCompiler.DependencyAnalysis /// /// Only expected to be used during ILScanning when scanning for reflection. /// - internal class CustomAttributeMetadataNode : DependencyNodeCore + internal sealed class CustomAttributeMetadataNode : DependencyNodeCore { private readonly ReflectableCustomAttribute _customAttribute; @@ -35,7 +31,7 @@ public CustomAttributeMetadataNode(ReflectableCustomAttribute customAttribute) // We need to walk the dependencies before placing the node into the graph to find out whether // the attribute even can be generated (does it refer to blocked types or something like that?). public override IEnumerable GetStaticDependencies(NodeFactory factory) => null; - + protected override string GetName(NodeFactory factory) { return $"Reflectable custom attribute {_customAttribute.CustomAttributeHandle} in {_customAttribute.Module}"; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DataflowAnalyzedMethodNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DataflowAnalyzedMethodNode.cs index 2935553dba0014..07f34d58a18292 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DataflowAnalyzedMethodNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DataflowAnalyzedMethodNode.cs @@ -6,7 +6,6 @@ using System.Diagnostics; using Internal.TypeSystem; -using Internal.Runtime; using Internal.IL; using ILCompiler.Dataflow; @@ -27,7 +26,7 @@ public DataflowAnalyzedMethodNode(MethodIL methodIL) Debug.Assert(!CompilerGeneratedState.IsNestedFunctionOrStateMachineMember(methodIL.OwningMethod)); _methodIL = methodIL; } - + public override IEnumerable GetStaticDependencies(NodeFactory factory) { var mdManager = (UsageBasedMetadataManager)factory.MetadataManager; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DefaultConstructorMapNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DefaultConstructorMapNode.cs index 01e18fd9824039..c1603a87ad1057 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DefaultConstructorMapNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DefaultConstructorMapNode.cs @@ -2,22 +2,18 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Diagnostics; -using System.Collections.Generic; using Internal.Text; using Internal.TypeSystem; using Internal.NativeFormat; -using ILCompiler.DependencyAnalysisFramework; - namespace ILCompiler.DependencyAnalysis { /// - /// DefaultConstructorMap blob, containing information on default constructor entrypoints of all types used + /// DefaultConstructorMap blob, containing information on default constructor entrypoints of all types used /// by lazy generic instantiations. /// - internal class DefaultConstructorMapNode : ObjectNode, ISymbolDefinitionNode + internal sealed class DefaultConstructorMapNode : ObjectNode, ISymbolDefinitionNode { private ObjectAndOffsetSymbolNode _endSymbol; private ExternalReferencesTableNode _externalReferences; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DictionaryLayoutNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DictionaryLayoutNode.cs index 26ddc6da9a13b5..d0faaf570c423f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DictionaryLayoutNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DictionaryLayoutNode.cs @@ -88,7 +88,7 @@ public virtual int GetSlotForFixedEntry(GenericLookupResult entry) { return GetSlotForEntry(entry); } - + public abstract IEnumerable Entries { get; @@ -113,7 +113,7 @@ public abstract bool HasFixedSlots public virtual ICollection GetTemplateEntries(NodeFactory factory) { - ArrayBuilder templateEntries = new ArrayBuilder(); + ArrayBuilder templateEntries = default(ArrayBuilder); foreach (var entry in Entries) { templateEntries.Add(entry.TemplateDictionaryNode(factory)); @@ -182,7 +182,7 @@ public override IEnumerable GetConditionalStaticDep return conditionalDependencies; } - protected override string GetName(NodeFactory factory) => $"Dictionary layout for {_owningMethodOrType.ToString()}"; + protected override string GetName(NodeFactory factory) => $"Dictionary layout for {_owningMethodOrType}"; public override bool HasConditionalStaticDependencies => HasFixedSlots; public override bool HasDynamicDependencies => false; @@ -201,7 +201,7 @@ public class PrecomputedDictionaryLayoutNode : DictionaryLayoutNode public PrecomputedDictionaryLayoutNode(TypeSystemEntity owningMethodOrType, IEnumerable layout) : base(owningMethodOrType) { - ArrayBuilder l = new ArrayBuilder(); + ArrayBuilder l = default(ArrayBuilder); foreach (var entry in layout) l.Add(entry); @@ -243,10 +243,10 @@ public override IEnumerable Entries public sealed class LazilyBuiltDictionaryLayoutNode : DictionaryLayoutNode { - class EntryHashTable : LockFreeReaderHashtable + private sealed class EntryHashTable : LockFreeReaderHashtable { - protected override bool CompareKeyToValue(GenericLookupResult key, GenericLookupResult value) => Object.Equals(key, value); - protected override bool CompareValueToValue(GenericLookupResult value1, GenericLookupResult value2) => Object.Equals(value1, value2); + protected override bool CompareKeyToValue(GenericLookupResult key, GenericLookupResult value) => Equals(key, value); + protected override bool CompareValueToValue(GenericLookupResult value1, GenericLookupResult value2) => Equals(value1, value2); protected override GenericLookupResult CreateValueFromKey(GenericLookupResult key) => key; protected override int GetKeyHashCode(GenericLookupResult key) => key.GetHashCode(); protected override int GetValueHashCode(GenericLookupResult value) => value.GetHashCode(); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DynamicDependencyAttributeAlgorithm.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DynamicDependencyAttributeAlgorithm.cs index 8b59f34554f9e0..aa5f4f0630f2fe 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DynamicDependencyAttributeAlgorithm.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/DynamicDependencyAttributeAlgorithm.cs @@ -13,7 +13,6 @@ using static ILCompiler.Dataflow.DynamicallyAccessedMembersBinder; using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyList; -using MethodAttributes = System.Reflection.MethodAttributes; namespace ILCompiler.DependencyAnalysis { @@ -21,7 +20,7 @@ namespace ILCompiler.DependencyAnalysis /// Computes the list of dependencies from DynamicDependencyAttribute. /// https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.codeanalysis.dynamicdependencyattribute /// - internal class DynamicDependencyAttributeAlgorithm + internal static class DynamicDependencyAttributeAlgorithm { public static void AddDependenciesDueToDynamicDependencyAttribute(ref DependencyList dependencies, NodeFactory factory, EcmaMethod method) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EETypeNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EETypeNode.cs index a74192ec045124..9c7b103af14619 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EETypeNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EETypeNode.cs @@ -660,12 +660,12 @@ private void OutputComponentSize(ref ObjectDataBuilder objData) private void OutputFlags(NodeFactory factory, ref ObjectDataBuilder objData) { - UInt16 flags = EETypeBuilderHelpers.ComputeFlags(_type); + ushort flags = EETypeBuilderHelpers.ComputeFlags(_type); if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType) { // Generic array enumerators use special variance rules recognized by the runtime - flags |= (UInt16)EETypeFlags.GenericVarianceFlag; + flags |= (ushort)EETypeFlags.GenericVarianceFlag; } if (factory.TypeSystemContext.IsGenericArrayInterfaceType(_type)) @@ -673,12 +673,12 @@ private void OutputFlags(NodeFactory factory, ref ObjectDataBuilder objData) // Runtime casting logic relies on all interface types implemented on arrays // to have the variant flag set (even if all the arguments are non-variant). // This supports e.g. casting uint[] to ICollection - flags |= (UInt16)EETypeFlags.GenericVarianceFlag; + flags |= (ushort)EETypeFlags.GenericVarianceFlag; } if (_type.IsIDynamicInterfaceCastable) { - flags |= (UInt16)EETypeFlags.IDynamicInterfaceCastableFlag; + flags |= (ushort)EETypeFlags.IDynamicInterfaceCastableFlag; } ISymbolNode relatedTypeNode = GetRelatedTypeNode(factory); @@ -688,17 +688,17 @@ private void OutputFlags(NodeFactory factory, ref ObjectDataBuilder objData) // that it should indirect through the import address table if (relatedTypeNode != null && relatedTypeNode.RepresentsIndirectionCell) { - flags |= (UInt16)EETypeFlags.RelatedTypeViaIATFlag; + flags |= (ushort)EETypeFlags.RelatedTypeViaIATFlag; } if (HasOptionalFields) { - flags |= (UInt16)EETypeFlags.OptionalFieldsFlag; + flags |= (ushort)EETypeFlags.OptionalFieldsFlag; } if (this is ClonedConstructedEETypeNode) { - flags |= (UInt16)EETypeKind.ClonedEEType; + flags |= (ushort)EETypeKind.ClonedEEType; } objData.EmitShort((short)flags); @@ -1050,7 +1050,7 @@ protected internal virtual void ComputeOptionalEETypeFields(NodeFactory factory, ComputeValueTypeFieldPadding(); } - void ComputeRareFlags(NodeFactory factory, bool relocsOnly) + private void ComputeRareFlags(NodeFactory factory, bool relocsOnly) { uint flags = 0; @@ -1102,7 +1102,7 @@ void ComputeRareFlags(NodeFactory factory, bool relocsOnly) /// To support boxing / unboxing, the offset of the value field of a Nullable type is recorded on the MethodTable. /// This is variable according to the alignment requirements of the Nullable<T> type parameter. /// - void ComputeNullableValueOffset() + private void ComputeNullableValueOffset() { if (!_type.IsNullable) return; @@ -1194,8 +1194,7 @@ public static void AddDependenciesForStaticsNode(NodeFactory factory, TypeDesc t if (factory.TypeSystemContext.SupportsUniversalCanon || (factory.TypeSystemContext.SupportsCanon && (type != type.ConvertToCanonForm(CanonicalFormKind.Specific)))) { - if (dependencies == null) - dependencies = new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.NecessaryTypeSymbol(type), "Static block owning type is necessary for canonically equivalent reflection"); } @@ -1221,8 +1220,7 @@ protected static void AddDependenciesForUniversalGVMSupport(NodeFactory factory, MethodDesc universalCanonMethodNonCanonicalized = method.MakeInstantiatedMethod(new Instantiation(universalCanonArray)); MethodDesc universalCanonGVMMethod = universalCanonMethodNonCanonicalized.GetCanonMethodTarget(CanonicalFormKind.Universal); - if (dependencies == null) - dependencies = new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(new DependencyListEntry(factory.MethodEntrypoint(universalCanonGVMMethod), "USG GVM Method")); } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EETypeOptionalFieldsNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EETypeOptionalFieldsNode.cs index aa6d25c8c82ac2..fbde550ed54fd3 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EETypeOptionalFieldsNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EETypeOptionalFieldsNode.cs @@ -1,11 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Diagnostics; - using Internal.Text; -using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { @@ -58,7 +54,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) _owner.ComputeOptionalEETypeFields(factory, relocsOnly: false); objData.EmitBytes(_owner.GetOptionalFieldsData()); } - + return objData.ToObjectData(); } @@ -66,7 +62,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { - return SortableDependencyNode.CompareImpl(_owner, ((EETypeOptionalFieldsNode)other)._owner, comparer); + return CompareImpl(_owner, ((EETypeOptionalFieldsNode)other)._owner, comparer); } } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EmbeddedPointerIndirectionNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EmbeddedPointerIndirectionNode.cs index 7b3664ffbc6e69..4dd52258d20840 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EmbeddedPointerIndirectionNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EmbeddedPointerIndirectionNode.cs @@ -1,7 +1,6 @@ // 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 Internal.Text; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EmbeddedTrimmingDescriptorNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EmbeddedTrimmingDescriptorNode.cs index b71403a1c9a691..0aeb11b5fc69c5 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EmbeddedTrimmingDescriptorNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/EmbeddedTrimmingDescriptorNode.cs @@ -24,7 +24,7 @@ public EmbeddedTrimmingDescriptorNode(EcmaModule module) { _module = module; } - + public override IEnumerable GetStaticDependencies(NodeFactory factory) { PEMemoryBlock resourceDirectory = _module.PEReader.GetSectionData(_module.PEReader.PEHeaders.CorHeader.ResourcesDirectory.RelativeVirtualAddress); @@ -60,7 +60,7 @@ public override IEnumerable GetStaticDependencies(NodeFacto protected override string GetName(NodeFactory factory) { - return $"Embedded descriptor from {_module.ToString()}"; + return $"Embedded descriptor from {_module}"; } public override bool InterestingForDynamicDependencyAnalysis => false; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExactMethodInstantiationsNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExactMethodInstantiationsNode.cs index 1635f4d07b560a..c91124338a7462 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExactMethodInstantiationsNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExactMethodInstantiationsNode.cs @@ -109,7 +109,7 @@ public static void GetExactMethodInstantiationDependenciesForMethod(ref Dependen if (!IsMethodEligibleForTracking(factory, method)) return; - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); // Method entry point dependency bool getUnboxingStub = method.OwningType.IsValueType && !method.Signature.IsStatic; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExternSymbolNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExternSymbolNode.cs index 721e983ef56401..ca02f10f177def 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExternSymbolNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExternSymbolNode.cs @@ -1,7 +1,6 @@ // 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 ILCompiler.DependencyAnalysisFramework; @@ -14,7 +13,7 @@ namespace ILCompiler.DependencyAnalysis /// Represents a symbol that is defined externally and statically linked to the output obj file. /// public class ExternSymbolNode : SortableDependencyNode, ISortableSymbolNode - { + { private readonly Utf8String _name; private readonly bool _isIndirection; @@ -24,7 +23,7 @@ public ExternSymbolNode(Utf8String name, bool isIndirection = false) _isIndirection = isIndirection; } - protected override string GetName(NodeFactory factory) => $"ExternSymbol {_name.ToString()}{(_isIndirection ? " (indirected)" : "")}"; + protected override string GetName(NodeFactory factory) => $"ExternSymbol {_name}{(_isIndirection ? " (indirected)" : "")}"; public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExternSymbolsImportedNodeProvider.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExternSymbolsImportedNodeProvider.cs index 18668be9769bbf..2af223e880fc09 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExternSymbolsImportedNodeProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExternSymbolsImportedNodeProvider.cs @@ -2,11 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using ILCompiler.DependencyAnalysisFramework; using Internal.TypeSystem; -using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExternalReferencesTableNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExternalReferencesTableNode.cs index 393ea936f240af..2cbd2b03a09878 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExternalReferencesTableNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ExternalReferencesTableNode.cs @@ -5,8 +5,6 @@ using System.Collections.Generic; using Internal.Text; -using Internal.TypeSystem; -using Internal.Runtime; using Debug = System.Diagnostics.Debug; @@ -109,7 +107,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) } _endSymbol.SetSymbolOffset(builder.CountBytes); - + builder.AddSymbol(this); builder.AddSymbol(_endSymbol); @@ -123,7 +121,7 @@ public override int CompareToImpl(ISortableNode other, CompilerComparer comparer return string.Compare(_blobName, ((ExternalReferencesTableNode)other)._blobName); } - struct SymbolAndDelta : IEquatable + private struct SymbolAndDelta : IEquatable { public readonly ISymbolNode Symbol; public readonly int Delta; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FatFunctionPointerNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FatFunctionPointerNode.cs index 2dd04047e594e0..a4622553d4c9ed 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FatFunctionPointerNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FatFunctionPointerNode.cs @@ -86,7 +86,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) // The next entry is a pointer to the context to be used for the canonical method builder.EmitPointerReloc(contextParameter); - + return builder.ToObjectData(); } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FieldMetadataNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FieldMetadataNode.cs index 603f7c7068fdc7..8cf60ae0f293ea 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FieldMetadataNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FieldMetadataNode.cs @@ -18,7 +18,7 @@ namespace ILCompiler.DependencyAnalysis /// /// Only expected to be used during ILScanning when scanning for reflection. /// - internal class FieldMetadataNode : DependencyNodeCore + internal sealed class FieldMetadataNode : DependencyNodeCore { private readonly FieldDesc _field; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FieldRvaDataNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FieldRvaDataNode.cs index d1f9e3e5800608..243a4cd225b9ad 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FieldRvaDataNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FieldRvaDataNode.cs @@ -14,7 +14,7 @@ namespace ILCompiler.DependencyAnalysis public class FieldRvaDataNode : ObjectNode, ISymbolDefinitionNode { private readonly EcmaField _field; - + public FieldRvaDataNode(EcmaField field) { Debug.Assert(field.HasRva); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FrozenObjectNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FrozenObjectNode.cs index 567ecb7595c513..7e036c8692c094 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FrozenObjectNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/FrozenObjectNode.cs @@ -18,7 +18,7 @@ public class FrozenObjectNode : EmbeddedObjectNode, ISymbolDefinitionNode private readonly MetadataType _owningType; private readonly TypePreinit.ISerializableReference _data; private readonly int _allocationSiteId; - + public FrozenObjectNode(MetadataType owningType, int allocationSiteId, TypePreinit.ISerializableReference data) { _owningType = owningType; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticEETypeNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticEETypeNode.cs index 653e7c378c8266..da28ef9d545770 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticEETypeNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticEETypeNode.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Text; using Internal.Runtime; using Internal.Text; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticsNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticsNode.cs index 929314cd7763f3..08e706b527cd25 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticsNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticsNode.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - using Internal.Text; using Internal.TypeSystem; @@ -89,7 +87,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) bool isPreinitialized = _preinitializationInfo != null && _preinitializationInfo.IsPreinitialized; if (isPreinitialized) delta |= GCStaticRegionConstants.HasPreInitializedData; - + builder.EmitPointerReloc(GetGCStaticEETypeNode(factory), delta); if (isPreinitialized) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticsPreInitDataNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticsPreInitDataNode.cs index d84317c8002e20..1514c8a1ce7caf 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticsPreInitDataNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GCStaticsPreInitDataNode.cs @@ -68,7 +68,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { if (!field.IsStatic || field.HasRva || field.IsLiteral || field.IsThreadStatic || !field.HasGCStaticBase) continue; - + int padding = field.Offset.AsInt - initialOffset - builder.CountBytes; Debug.Assert(padding >= 0); builder.EmitZeros(padding); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GVMDependenciesNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GVMDependenciesNode.cs index e13378f6b8ecc1..af6556e41762bc 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GVMDependenciesNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GVMDependenciesNode.cs @@ -1,12 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Diagnostics; using System.Collections.Generic; using ILCompiler.DependencyAnalysisFramework; -using Internal.Text; using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis @@ -59,7 +57,7 @@ public override IEnumerable GetStaticDependencies(NodeFacto } bool getUnboxingStub = _method.OwningType.IsValueType; - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(context.MethodEntrypoint(_method, getUnboxingStub), "GVM Dependency - Canon method"); if (_method.IsSharedByGenericInstantiations) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericCompositionNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericCompositionNode.cs index 9857c633784db6..0e17ad61b3b2f1 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericCompositionNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericCompositionNode.cs @@ -77,7 +77,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) builder.RequireInitialPointerAlignment(); - builder.EmitShort((short)checked((UInt16)_details.Instantiation.Length)); + builder.EmitShort((short)checked((ushort)_details.Instantiation.Length)); builder.EmitByte((byte)(hasVariance ? 1 : 0)); @@ -116,7 +116,7 @@ internal struct GenericCompositionDetails : IEquatable true; public sealed override bool IsShareable => true; @@ -104,7 +104,7 @@ public override void AppendMangledName(NameMangler nameMangler, Utf8StringBuilde protected override int HeaderSize => 0; public override Instantiation TypeInstantiation => _owningType.Instantiation; - public override Instantiation MethodInstantiation => new Instantiation(); + public override Instantiation MethodInstantiation => default(Instantiation); protected override TypeSystemContext Context => _owningType.Context; public override TypeSystemEntity OwningEntity => _owningType; public TypeDesc OwningType => _owningType; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericLookupResult.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericLookupResult.cs index cba6ebe4c2cdf8..43b64f3b0817ed 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericLookupResult.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericLookupResult.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; - -using Internal.IL; using Internal.Text; using Internal.TypeSystem; @@ -1360,7 +1358,6 @@ public override ISymbolNode GetTarget(NodeFactory factory, GenericLookupResultCo public override void EmitDictionaryEntry(ref ObjectDataBuilder builder, NodeFactory factory, GenericLookupResultContext dictionary, GenericDictionaryNode dictionaryNode) { - TypeDesc instantiatedType = _type.GetNonRuntimeDeterminedTypeFromRuntimeDeterminedSubtypeViaSubstitution(dictionary.TypeInstantiation, dictionary.MethodInstantiation); int typeSize; if (_type.IsDefType) @@ -1411,9 +1408,9 @@ protected override bool EqualsImpl(GenericLookupResult obj) internal sealed class ConstrainedMethodUseLookupResult : GenericLookupResult { - MethodDesc _constrainedMethod; - TypeDesc _constraintType; - bool _directCall; + private MethodDesc _constrainedMethod; + private TypeDesc _constraintType; + private bool _directCall; protected override int ClassCode => -1525377658; @@ -1547,7 +1544,7 @@ protected override bool EqualsImpl(GenericLookupResult obj) public sealed class IntegerLookupResult : GenericLookupResult { - int _integerValue; + private int _integerValue; public IntegerLookupResult(int integer) { @@ -1611,7 +1608,7 @@ public override void WriteDictionaryTocData(NodeFactory factory, IGenericLookupR public sealed class PointerToSlotLookupResult : GenericLookupResult { - int _slotIndex; + private int _slotIndex; public PointerToSlotLookupResult(int slotIndex) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericMethodsHashtableNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericMethodsHashtableNode.cs index 85ace207c8600a..c033f44fd1280f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericMethodsHashtableNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericMethodsHashtableNode.cs @@ -42,7 +42,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) if (relocsOnly) return new ObjectData(Array.Empty(), Array.Empty(), 1, new ISymbolDefinitionNode[] { this }); - // Ensure the native layout data has been saved, in order to get valid Vertex offsets for the signature Vertices + // Ensure the native layout data has been saved, in order to get valid Vertex offsets for the signature Vertices factory.MetadataManager.NativeLayoutInfo.SaveNativeLayoutInfoWriter(factory); NativeWriter nativeWriter = new NativeWriter(); @@ -100,7 +100,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) public static void GetGenericMethodsHashtableDependenciesForMethod(ref DependencyList dependencies, NodeFactory factory, MethodDesc method) { Debug.Assert(method.HasInstantiation && !method.IsCanonicalMethod(CanonicalFormKind.Any)); - + // Method's containing type IEETypeNode containingTypeNode = factory.NecessaryTypeSymbol(method.OwningType); dependencies.Add(new DependencyListEntry(containingTypeNode, "GenericMethodsHashtable entry containing type")); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericMethodsTemplateMap.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericMethodsTemplateMap.cs index a34b49a88151c7..2c07dc30adff20 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericMethodsTemplateMap.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericMethodsTemplateMap.cs @@ -83,7 +83,7 @@ public static void GetTemplateMethodDependencies(ref DependencyList dependencies if (!IsEligibleToBeATemplate(method)) return; - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(new DependencyListEntry(factory.NativeLayout.TemplateMethodEntry(method), "Template Method Entry")); dependencies.Add(new DependencyListEntry(factory.NativeLayout.TemplateMethodLayout(method), "Template Method Layout")); } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericTypesTemplateMap.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericTypesTemplateMap.cs index 150190833d2c19..f398a8cc519b82 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericTypesTemplateMap.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericTypesTemplateMap.cs @@ -5,7 +5,6 @@ using System.Diagnostics; using Internal.Text; -using ILCompiler.DependencyAnalysisFramework; using Internal.TypeSystem; using Internal.NativeFormat; @@ -80,7 +79,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) return new ObjectData(streamBytes, Array.Empty(), 1, new ISymbolDefinitionNode[] { this, _endSymbol }); } - + public static void GetTemplateTypeDependencies(ref DependencyList dependencies, NodeFactory factory, TypeDesc type) { TypeDesc templateType = ConvertArrayOfTToRegularArray(factory, type); @@ -88,7 +87,7 @@ public static void GetTemplateTypeDependencies(ref DependencyList dependencies, if (!IsEligibleToHaveATemplate(templateType)) return; - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(new DependencyListEntry(factory.NecessaryTypeSymbol(templateType), "Template type")); dependencies.Add(new DependencyListEntry(factory.NativeLayout.TemplateTypeLayout(templateType), "Template Type Layout")); } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ILScanNodeFactory.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ILScanNodeFactory.cs index 25912caeb15df8..58c570ffe08439 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ILScanNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ILScanNodeFactory.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem; using Debug = System.Diagnostics.Debug; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/INodeWithCodeInfo.Aot.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/INodeWithCodeInfo.Aot.cs index b11a5819ca34fc..942a097e00e316 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/INodeWithCodeInfo.Aot.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/INodeWithCodeInfo.Aot.cs @@ -1,8 +1,6 @@ // 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 ILCompiler.DependencyAnalysis { public interface INodeWithCodeInfo diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/INodeWithDebugInfo.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/INodeWithDebugInfo.cs index bf195f0170d69b..97563feff21a1a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/INodeWithDebugInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/INodeWithDebugInfo.cs @@ -23,7 +23,7 @@ public NativeSequencePoint(int nativeOffset, string fileName, int lineNumber, in ColNumber = colNumber; } } - + public interface INodeWithDebugInfo { bool IsStateMachineMoveNextMethod { get; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ISpecialUnboxThunkNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ISpecialUnboxThunkNode.cs index 1afba71128bc20..af444ca99e7f57 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ISpecialUnboxThunkNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ISpecialUnboxThunkNode.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Internal.TypeSystem; - namespace ILCompiler.DependencyAnalysis { /// diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ImportedNodeProvider.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ImportedNodeProvider.cs index 5b2ac08a8bbd79..9433faa12d09fd 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ImportedNodeProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ImportedNodeProvider.cs @@ -2,11 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using ILCompiler.DependencyAnalysisFramework; using Internal.TypeSystem; -using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/IndirectionExtensions.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/IndirectionExtensions.cs index c23ae00dd29d80..26102d18873e3b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/IndirectionExtensions.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/IndirectionExtensions.cs @@ -2,13 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. using Internal.Runtime; -using Internal.TypeSystem; - -using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis { - static class IndirectionExtensions + internal static class IndirectionExtensions { /// /// Use this api to generate a reloc to a symbol that may be an indirection cell or not as a pointer @@ -27,7 +24,7 @@ public static void EmitPointerRelocOrIndirectionReference(ref this ObjectDataBui public static void EmitRelativeRelocOrIndirectionReference(ref this ObjectDataBuilder builder, ISymbolNode symbol, int delta = 0, int indirectionBit = IndirectionConstants.IndirectionCellPointer) { if (symbol.RepresentsIndirectionCell) - delta = delta | indirectionBit; + delta |= indirectionBit; builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_RELPTR32, delta); } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceDispatchCellNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceDispatchCellNode.cs index fd0e943802f041..b1b7fc8ad7ec7a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceDispatchCellNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceDispatchCellNode.cs @@ -106,9 +106,9 @@ public override void EncodeData(ref ObjectDataBuilder objData, NodeFactory facto if (objData.TargetPointerSize == 8) { - // IMAGE_REL_BASED_RELPTR is a 32-bit relocation. However, the cell needs a full pointer + // IMAGE_REL_BASED_RELPTR is a 32-bit relocation. However, the cell needs a full pointer // width there since a pointer to the cache will be written into the cell. Emit additional - // 32 bits on targets whose pointer size is 64 bit. + // 32 bits on targets whose pointer size is 64 bit. objData.EmitInt(0); } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceDispatchCellSectionNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceDispatchCellSectionNode.cs index 13cdd42590982c..f83a168e08895c 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceDispatchCellSectionNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceDispatchCellSectionNode.cs @@ -26,7 +26,7 @@ protected override void GetElementDataForNodes(ref ObjectDataBuilder builder, No if (relocsOnly) return; - // The interface dispatch cell has an alignment requirement of 2 * [Pointer size] as part of the + // The interface dispatch cell has an alignment requirement of 2 * [Pointer size] as part of the // synchronization mechanism of the two values in the runtime. builder.RequireInitialAlignment(factory.Target.PointerSize * 2); @@ -90,7 +90,7 @@ protected override void GetElementDataForNodes(ref ObjectDataBuilder builder, No /// /// Comparer that groups interface dispatch cells by their slot number. /// - private class DispatchCellComparer : IComparer + private sealed class DispatchCellComparer : IComparer { private readonly NodeFactory _factory; private readonly TypeSystemComparer _comparer = TypeSystemComparer.Instance; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs index dd183cd1b54f38..4390f46cfa9f52 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs @@ -17,7 +17,7 @@ public class InterfaceDispatchMapNode : ObjectNode, ISymbolDefinitionNode, ISort public InterfaceDispatchMapNode(NodeFactory factory, TypeDesc type) { - // Multidimensional arrays should not get a sealed vtable or a dispatch map. Runtime should use the + // Multidimensional arrays should not get a sealed vtable or a dispatch map. Runtime should use the // sealed vtable and dispatch map of the System.Array basetype instead. // Pointer arrays also follow the same path Debug.Assert(!type.IsArrayTypeWithoutGenericInterfaces()); @@ -48,7 +48,7 @@ public override ObjectNodeSection Section return ObjectNodeSection.DataSection; } } - + protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory) { var result = new DependencyList(); @@ -137,7 +137,7 @@ public static bool MightHaveInterfaceDispatchMap(TypeDesc type, NodeFactory fact return false; } - void EmitDispatchMap(ref ObjectDataBuilder builder, NodeFactory factory) + private void EmitDispatchMap(ref ObjectDataBuilder builder, NodeFactory factory) { var entryCountReservation = builder.ReserveShort(); var defaultEntryCountReservation = builder.ReserveShort(); @@ -165,7 +165,7 @@ void EmitDispatchMap(ref ObjectDataBuilder builder, NodeFactory factory) Debug.Assert(interfaceType.IsInterface); IReadOnlyList virtualSlots = factory.VTable(interfaceType).Slots; - + for (int interfaceMethodSlot = 0; interfaceMethodSlot < virtualSlots.Count; interfaceMethodSlot++) { MethodDesc declMethod = virtualSlots[interfaceMethodSlot]; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceGenericVirtualMethodTableNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceGenericVirtualMethodTableNode.cs index 247ed24cc12cc1..1f99e62ed3dfa6 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceGenericVirtualMethodTableNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceGenericVirtualMethodTableNode.cs @@ -43,7 +43,7 @@ public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) /// /// Helper method to compute the dependencies that would be needed by a hashtable entry for an interface GVM call. - /// This helper is used by the TypeGVMEntriesNode, which is used by the dependency analysis to compute the + /// This helper is used by the TypeGVMEntriesNode, which is used by the dependency analysis to compute the /// GVM hashtable entries for the compiled types. /// The dependencies returned from this function will be reported as static dependencies of the TypeGVMEntriesNode, /// which we create for each type that has generic virtual methods. @@ -58,7 +58,7 @@ public static void GetGenericVirtualMethodImplementationDependencies(ref Depende var openCallingMethodNameAndSig = factory.NativeLayout.MethodNameAndSignatureVertex(openCallingMethod); dependencies.Add(new DependencyListEntry(factory.NativeLayout.PlacedSignatureVertex(openCallingMethodNameAndSig), "interface gvm table calling method signature")); - + // Implementation could be null if this is a default interface method reabstraction or diamond. We need to record those. if (implementationMethod != null) { @@ -97,7 +97,7 @@ private void AddGenericVirtualMethodImplementation(NodeFactory factory, MethodDe // If the implementation method is implementing some interface method, compute which // interface explicitly implemented on the type that the current method implements an interface method for. - // We need this because at runtime, the interfaces explicitly implemented on the type will have + // We need this because at runtime, the interfaces explicitly implemented on the type will have // runtime-determined signatures that we can use to make generic substitutions and check for interface matching. if (!openImplementationType.IsInterface) { @@ -105,7 +105,7 @@ private void AddGenericVirtualMethodImplementation(NodeFactory factory, MethodDe _interfaceImpls[openImplementationMethod] = new Dictionary>(); if (!_interfaceImpls[openImplementationMethod].ContainsKey(openImplementationType)) _interfaceImpls[openImplementationMethod][openImplementationType] = new HashSet(); - + int numIfacesAdded = 0; for (int index = 0; index < openImplementationType.RuntimeInterfaces.Length; index++) { @@ -190,10 +190,10 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) Debug.Assert(_interfaceImpls.ContainsKey(impl)); var ifaceImpls = _interfaceImpls[impl]; - + // First, emit how many types have method implementations for this interface method entry vertex = nativeFormatWriter.GetTuple(vertex, nativeFormatWriter.GetUnsignedConstant((uint)ifaceImpls.Count)); - + // Emit each type that implements the interface method, and the interface signatures for the interfaces implemented by the type foreach (var currentImpl in ifaceImpls) { @@ -201,7 +201,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) typeId = _externalReferences.GetIndex(factory.NecessaryTypeSymbol(implementationType)); vertex = nativeFormatWriter.GetTuple(vertex, nativeFormatWriter.GetUnsignedConstant(typeId)); - + // Emit information on which interfaces the current method entry provides implementations for vertex = nativeFormatWriter.GetTuple(vertex, nativeFormatWriter.GetUnsignedConstant((uint)currentImpl.Value.Count)); foreach (var ifaceId in currentImpl.Value) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/JumpStubNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/JumpStubNode.cs index 976f7d27e96d3f..89b28978f92785 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/JumpStubNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/JumpStubNode.cs @@ -14,7 +14,7 @@ public ISymbolNode Target return _target; } } - + public JumpStubNode(ISymbolNode target) { _target = target; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MetadataNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MetadataNode.cs index 427c67f93cdbe5..1ffe42a8a1cbdb 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MetadataNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MetadataNode.cs @@ -4,7 +4,6 @@ using System; using Internal.Text; -using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { @@ -14,7 +13,7 @@ namespace ILCompiler.DependencyAnalysis /// public sealed class MetadataNode : ObjectNode, ISymbolDefinitionNode { - ObjectAndOffsetSymbolNode _endSymbol; + private ObjectAndOffsetSymbolNode _endSymbol; public MetadataNode() { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MethodAssociatedDataNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MethodAssociatedDataNode.cs index d0f445af76419b..8cd6b03b563028 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MethodAssociatedDataNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MethodAssociatedDataNode.cs @@ -6,7 +6,6 @@ using Internal.Text; using Internal.TypeSystem; -using Internal.TypeSystem.Interop; namespace ILCompiler.DependencyAnalysis { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MethodExceptionHandlingInfoNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MethodExceptionHandlingInfoNode.cs index d2f867d5ee296a..5d76d571e37106 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MethodExceptionHandlingInfoNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MethodExceptionHandlingInfoNode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Diagnostics; using Internal.Text; @@ -53,4 +52,3 @@ public override int CompareToImpl(ISortableNode other, CompilerComparer comparer #endif } } - diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MethodMetadataNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MethodMetadataNode.cs index 427b589090fae2..723f9e08552a2d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MethodMetadataNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/MethodMetadataNode.cs @@ -18,7 +18,7 @@ namespace ILCompiler.DependencyAnalysis /// /// Only expected to be used during ILScanning when scanning for reflection. /// - internal class MethodMetadataNode : DependencyNodeCore + internal sealed class MethodMetadataNode : DependencyNodeCore { private readonly MethodDesc _method; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModuleInitializerListNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModuleInitializerListNode.cs index 888de7a5d9ffe2..a88d3893e6697d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModuleInitializerListNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModuleInitializerListNode.cs @@ -10,7 +10,7 @@ namespace ILCompiler.DependencyAnalysis { - internal class ModuleInitializerListNode : ObjectNode, ISymbolDefinitionNode + internal sealed class ModuleInitializerListNode : ObjectNode, ISymbolDefinitionNode { private readonly ObjectAndOffsetSymbolNode _endSymbol; @@ -41,7 +41,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) // This is a summary node that doesn't introduce dependencies. if (relocsOnly) return new ObjectData(Array.Empty(), Array.Empty(), 1, new ISymbolDefinitionNode[] { this }); - + var modulesWithCctor = new List(); foreach (var methodNode in factory.MetadataManager.GetCompiledMethodBodies()) @@ -152,7 +152,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) public override int ClassCode => 0x4732738; - private class ModuleGraphNode + private sealed class ModuleGraphNode { private readonly ModuleGraphFactory _factory; private readonly ModuleDesc[] _edges; @@ -168,7 +168,7 @@ public ModuleGraphNode[] Edges return _edgeNodes; } - var edgeNodes = new ArrayBuilder(); + var edgeNodes = default(ArrayBuilder); foreach (var edge in _edges) edgeNodes.Add(_factory.GetNode(edge)); return _edgeNodes = edgeNodes.ToArray(); @@ -185,7 +185,7 @@ public ModuleGraphNode(ModuleGraphFactory factory, ModuleDesc module, ModuleDesc => (_factory, Module, _edges) = (factory, module, edges); } - private class ModuleGraphFactory + private sealed class ModuleGraphFactory { private readonly Dictionary _nodes = new Dictionary(); @@ -196,7 +196,7 @@ public ModuleGraphNode GetNode(ModuleDesc module) if (module is EcmaModule ecmaModule) { - ArrayBuilder referencedAssemblies = new ArrayBuilder(); + ArrayBuilder referencedAssemblies = default(ArrayBuilder); var reader = ecmaModule.MetadataReader; foreach (var assemblyReferenceHandle in reader.AssemblyReferences) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModuleMetadataNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModuleMetadataNode.cs index 3f6318bae28962..aefc5ea2e9351d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModuleMetadataNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModuleMetadataNode.cs @@ -18,7 +18,7 @@ namespace ILCompiler.DependencyAnalysis /// /// Only expected to be used during ILScanning when scanning for reflection. /// - internal class ModuleMetadataNode : DependencyNodeCore + internal sealed class ModuleMetadataNode : DependencyNodeCore { private readonly ModuleDesc _module; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModuleUseBasedDependencyAlgorithm.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModuleUseBasedDependencyAlgorithm.cs index e5e217f87efaf7..c5409e8d882cec 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModuleUseBasedDependencyAlgorithm.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModuleUseBasedDependencyAlgorithm.cs @@ -7,7 +7,7 @@ namespace ILCompiler.DependencyAnalysis { - internal class ModuleUseBasedDependencyAlgorithm + internal static class ModuleUseBasedDependencyAlgorithm { internal static void AddDependenciesDueToModuleUse(ref DependencyList dependencyList, NodeFactory factory, ModuleDesc module) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModulesSectionNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModulesSectionNode.cs index 05d83408ae4b70..b48421341ad948 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModulesSectionNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ModulesSectionNode.cs @@ -1,8 +1,6 @@ // 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 Internal.Text; using Internal.TypeSystem; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NativeLayoutInfoNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NativeLayoutInfoNode.cs index c7f4bb4ecc06a7..03a231ec518d1c 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NativeLayoutInfoNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NativeLayoutInfoNode.cs @@ -6,7 +6,6 @@ using Internal.Text; using Internal.NativeFormat; -using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NativeLayoutVertexNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NativeLayoutVertexNode.cs index d3e4ec30779124..d4afc43b132f30 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NativeLayoutVertexNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NativeLayoutVertexNode.cs @@ -13,15 +13,15 @@ namespace ILCompiler.DependencyAnalysis { /// - /// Wrapper nodes for native layout vertex structures. These wrapper nodes are "abstract" as they do not + /// Wrapper nodes for native layout vertex structures. These wrapper nodes are "abstract" as they do not /// generate any data. They are used to keep track of the dependency nodes required by a Vertex structure. - /// + /// /// Any node in the graph that references data in the native layout blob needs to create one of these /// NativeLayoutVertexNode nodes, and track it as a dependency of itself. - /// Example: MethodCodeNodes that are saved to the table in the ExactMethodInstantiationsNode reference + /// Example: MethodCodeNodes that are saved to the table in the ExactMethodInstantiationsNode reference /// signatures stored in the native layout blob, so a NativeLayoutPlacedSignatureVertexNode node is created /// and returned as a static dependency of the associated MethodCodeNode (in the GetStaticDependencies API). - /// + /// /// Each NativeLayoutVertexNode that gets marked in the graph will register itself with the NativeLayoutInfoNode, /// so that the NativeLayoutInfoNode can write it later to the native layout blob during the call to its GetData API. /// @@ -66,17 +66,17 @@ protected NativeWriter GetNativeWriter(NodeFactory factory) /// /// Any NativeLayoutVertexNode that needs to expose the native layout Vertex after it has been saved /// needs to derive from this NativeLayoutSavedVertexNode class. - /// + /// /// A nativelayout Vertex should typically only be exposed for Vertex offset fetching purposes, after the native /// writer is saved (Vertex offsets get generated when the native writer gets saved). - /// + /// /// It is important for whoever derives from this class to produce unified Vertices. Calling the WriteVertex method /// multiple times should always produce the same exact unified Vertex each time (hence the assert in SetSavedVertex). /// All nativewriter.Getxyz methods return unified Vertices. - /// - /// When exposing a saved Vertex that is a result of a section placement operation (Section.Place(...)), always make - /// sure a unified Vertex is being placed in the section (Section.Place creates a PlacedVertex structure that wraps the - /// Vertex to be placed, so if the Vertex to be placed is unified, there will only be a single unified PlacedVertex + /// + /// When exposing a saved Vertex that is a result of a section placement operation (Section.Place(...)), always make + /// sure a unified Vertex is being placed in the section (Section.Place creates a PlacedVertex structure that wraps the + /// Vertex to be placed, so if the Vertex to be placed is unified, there will only be a single unified PlacedVertex /// structure created for that placed Vertex). /// public abstract class NativeLayoutSavedVertexNode : NativeLayoutVertexNode @@ -84,7 +84,7 @@ public abstract class NativeLayoutSavedVertexNode : NativeLayoutVertexNode public Vertex SavedVertex { get; private set; } protected Vertex SetSavedVertex(Vertex value) { - Debug.Assert(SavedVertex == null || Object.ReferenceEquals(SavedVertex, value)); + Debug.Assert(SavedVertex == null || ReferenceEquals(SavedVertex, value)); SavedVertex = value; return value; } @@ -148,8 +148,7 @@ public override IEnumerable GetStaticDependencies(NodeFacto if ((_flags & MethodEntryFlags.SaveEntryPoint) != 0) { - bool unboxingStub; - IMethodNode methodEntryPointNode = GetMethodEntrypointNode(context, out unboxingStub); + IMethodNode methodEntryPointNode = GetMethodEntrypointNode(context, out _); dependencies.Add(new DependencyListEntry(methodEntryPointNode, "NativeLayoutMethodEntryVertexNode entrypoint")); } @@ -431,7 +430,7 @@ public static NativeLayoutTypeSignatureVertexNode NewTypeSignatureVertexNode(Nod } } - sealed class NativeLayoutParameterizedTypeSignatureVertexNode : NativeLayoutTypeSignatureVertexNode + private sealed class NativeLayoutParameterizedTypeSignatureVertexNode : NativeLayoutTypeSignatureVertexNode { private NativeLayoutVertexNode _parameterTypeSig; @@ -475,7 +474,7 @@ public override Vertex WriteVertex(NodeFactory factory) } } - sealed class NativeLayoutGenericVarSignatureVertexNode : NativeLayoutTypeSignatureVertexNode + private sealed class NativeLayoutGenericVarSignatureVertexNode : NativeLayoutTypeSignatureVertexNode { public NativeLayoutGenericVarSignatureVertexNode(NodeFactory factory, TypeDesc type) : base(type) { @@ -502,7 +501,7 @@ public override Vertex WriteVertex(NodeFactory factory) } } - sealed class NativeLayoutInstantiatedTypeSignatureVertexNode : NativeLayoutTypeSignatureVertexNode + private sealed class NativeLayoutInstantiatedTypeSignatureVertexNode : NativeLayoutTypeSignatureVertexNode { private NativeLayoutTypeSignatureVertexNode _genericTypeDefSig; private NativeLayoutTypeSignatureVertexNode[] _instantiationArgs; @@ -540,7 +539,7 @@ public override Vertex WriteVertex(NodeFactory factory) } } - sealed class NativeLayoutEETypeSignatureVertexNode : NativeLayoutTypeSignatureVertexNode + private sealed class NativeLayoutEETypeSignatureVertexNode : NativeLayoutTypeSignatureVertexNode { public NativeLayoutEETypeSignatureVertexNode(NodeFactory factory, TypeDesc type) : base(type) { @@ -616,9 +615,9 @@ public override Vertex WriteVertex(NodeFactory factory) // This vertex doesn't need to assert as marked, as it simply represents the concept of an existing vertex which has been placed. // Always use the NativeLayoutInfo blob for names and sigs, even if the associated types/methods are written elsewhere. - // This saves space, since we can Unify more signatures, allows optimizations in comparing sigs in the same module, and - // prevents the dynamic type loader having to know about other native layout sections (since sigs contain types). If we are - // using a non-native layout info writer, write the sig to the native layout info, and refer to it by offset in its own + // This saves space, since we can Unify more signatures, allows optimizations in comparing sigs in the same module, and + // prevents the dynamic type loader having to know about other native layout sections (since sigs contain types). If we are + // using a non-native layout info writer, write the sig to the native layout info, and refer to it by offset in its own // section. At runtime, we will assume all names and sigs are in the native layout and find it. Vertex signature = _signatureToBePlaced.WriteVertex(factory); @@ -757,9 +756,8 @@ public sealed class NativeLayoutDictionarySignatureNode : NativeLayoutSavedVerte private TypeSystemEntity _owningMethodOrType; public NativeLayoutDictionarySignatureNode(NodeFactory nodeFactory, TypeSystemEntity owningMethodOrType) { - if (owningMethodOrType is MethodDesc) + if (owningMethodOrType is MethodDesc owningMethod) { - MethodDesc owningMethod = (MethodDesc)owningMethodOrType; Debug.Assert(owningMethod.IsCanonicalMethod(CanonicalFormKind.Universal) || nodeFactory.LazyGenericsPolicy.UsesLazyGenerics(owningMethod)); Debug.Assert(owningMethod.IsCanonicalMethod(CanonicalFormKind.Any)); Debug.Assert(owningMethod.HasInstantiation); @@ -776,9 +774,8 @@ public NativeLayoutDictionarySignatureNode(NodeFactory nodeFactory, TypeSystemEn private GenericContextKind ContextKind(NodeFactory factory) { - if (_owningMethodOrType is MethodDesc) + if (_owningMethodOrType is MethodDesc owningMethod) { - MethodDesc owningMethod = (MethodDesc)_owningMethodOrType; Debug.Assert(owningMethod.HasInstantiation); return GenericContextKind.FromMethodHiddenArg | GenericContextKind.NeedsUSGContext; } @@ -800,7 +797,7 @@ public override IEnumerable GetStaticDependencies(NodeFacto { if ((ContextKind(context) & GenericContextKind.HasDeclaringType) != 0) { - return new DependencyListEntry[] + return new DependencyListEntry[] { new DependencyListEntry(context.NativeLayout.TypeSignatureVertex((TypeDesc)_owningMethodOrType), "DeclaringType signature"), new DependencyListEntry(context.GenericDictionaryLayout(_owningMethodOrType), "Dictionary Layout") @@ -849,7 +846,7 @@ public override Vertex WriteVertex(NodeFactory factory) return SetSavedVertex(factory.MetadataManager.NativeLayoutInfo.SignaturesSection.Place(signatureWithContextKind)); } - protected override string GetName(NodeFactory factory) => $"Dictionary layout signature for {_owningMethodOrType.ToString()}"; + protected override string GetName(NodeFactory factory) => $"Dictionary layout signature for {_owningMethodOrType}"; } public sealed class NativeLayoutTemplateMethodLayoutVertexNode : NativeLayoutSavedVertexNode @@ -885,7 +882,7 @@ public override IEnumerable GetStaticDependencies(NodeFacto yield return new DependencyListEntry(context.GenericDictionaryLayout(_method), "Dictionary layout"); } - private int CompareDictionaryEntries(KeyValuePair left, KeyValuePair right) + private static int CompareDictionaryEntries(KeyValuePair left, KeyValuePair right) { return left.Key - right.Key; } @@ -898,7 +895,7 @@ public override Vertex WriteVertex(NodeFactory factory) DictionaryLayoutNode associatedLayout = factory.GenericDictionaryLayout(_method); ICollection templateLayout = associatedLayout.GetTemplateEntries(factory); - + if (!(_method.IsCanonicalMethod(CanonicalFormKind.Universal) || (factory.LazyGenericsPolicy.UsesLazyGenerics(_method))) && (templateLayout.Count > 0)) { List dictionaryVertices = new List(); @@ -1038,7 +1035,7 @@ public override IEnumerable GetStaticDependencies(NodeFacto if (_isUniversalCanon) { - // For universal canonical template types, we need to write out field layout information so that we + // For universal canonical template types, we need to write out field layout information so that we // can correctly compute the type sizes for dynamically created types at runtime, and construct // their GCDesc info foreach (FieldDesc field in _type.GetFields()) @@ -1087,13 +1084,11 @@ public override IEnumerable GetStaticDependencies(NodeFacto if (UniversalGenericParameterLayout.VTableMethodRequiresCallingConventionConverter(implMethod)) { - if (vtableSignatureNodeEntries == null) - vtableSignatureNodeEntries = new List(); + vtableSignatureNodeEntries ??= new List(); vtableSignatureNodeEntries.Add(context.NativeLayout.MethodSignatureVertex(declMethod.GetTypicalMethodDefinition().Signature)); } - } - , _type, _type, _type); + }, _type, _type, _type); if (vtableSignatureNodeEntries != null) { @@ -1124,16 +1119,14 @@ public override IEnumerable GetConditionalStaticDep if (UniversalGenericParameterLayout.VTableMethodRequiresCallingConventionConverter(implMethod)) { - if (conditionalDependencies == null) - conditionalDependencies = new List(); + conditionalDependencies ??= new List(); conditionalDependencies.Add( new CombinedDependencyListEntry(context.NativeLayout.MethodSignatureVertex(declMethod.GetTypicalMethodDefinition().Signature), context.VirtualMethodUse(declMethod), "conditional vtable cctor sig")); } - } - , _type, _type, _type); + }, _type, _type, _type); } if (conditionalDependencies != null) @@ -1142,7 +1135,7 @@ public override IEnumerable GetConditionalStaticDep return Array.Empty(); } - private int CompareDictionaryEntries(KeyValuePair left, KeyValuePair right) + private static int CompareDictionaryEntries(KeyValuePair left, KeyValuePair right) { return left.Key - right.Key; } @@ -1161,7 +1154,7 @@ public override Vertex WriteVertex(NodeFactory factory) DictionaryLayoutNode associatedLayout = factory.GenericDictionaryLayout(_type.ConvertToCanonForm(CanonicalFormKind.Specific).GetClosestDefType()); ICollection templateLayout = associatedLayout.GetTemplateEntries(factory); - + NativeWriter writer = GetNativeWriter(factory); // Interfaces @@ -1202,7 +1195,7 @@ public override Vertex WriteVertex(NodeFactory factory) uint cctorStaticsIndex = factory.MetadataManager.NativeLayoutInfo.StaticsReferences.GetIndex(cctorSymbol); layoutInfo.AppendUnsigned(BagElementKind.ClassConstructorPointer, cctorStaticsIndex); - typeFlags = typeFlags | Internal.NativeFormat.TypeFlags.HasClassConstructor; + typeFlags |= Internal.NativeFormat.TypeFlags.HasClassConstructor; } if (!_isUniversalCanon) @@ -1237,7 +1230,7 @@ public override Vertex WriteVertex(NodeFactory factory) // Determine if type has instantiation determined size if (!_type.IsInterface && HasInstantiationDeterminedSize()) { - typeFlags = typeFlags | Internal.NativeFormat.TypeFlags.HasInstantiationDeterminedSize; + typeFlags |= Internal.NativeFormat.TypeFlags.HasInstantiationDeterminedSize; } } @@ -1290,7 +1283,7 @@ public override Vertex WriteVertex(NodeFactory factory) if (_isUniversalCanon) { - // For universal canonical template types, we need to write out field layout information so that we + // For universal canonical template types, we need to write out field layout information so that we // can correctly compute the type sizes for dynamically created types at runtime, and construct // their GCDesc info VertexSequence fieldsSequence = null; @@ -1302,7 +1295,7 @@ public override Vertex WriteVertex(NodeFactory factory) continue; // NOTE: The order and contents of the signature vertices emitted here is what we consider a field ordinal for the - // purpose of NativeLayoutFieldOffsetGenericDictionarySlotNode. + // purpose of NativeLayoutFieldOffsetGenericDictionarySlotNode. FieldStorage fieldStorage = FieldStorage.Instance; if (field.IsStatic) @@ -1332,8 +1325,7 @@ public override Vertex WriteVertex(NodeFactory factory) Vertex staticFieldVertexData = writer.GetTuple(fieldTypeSignature.WriteVertex(factory), writer.GetUnsignedConstant((uint)fieldStorage)); - if (fieldsSequence == null) - fieldsSequence = new VertexSequence(); + fieldsSequence ??= new VertexSequence(); fieldsSequence.Append(staticFieldVertexData); } @@ -1348,7 +1340,7 @@ public override Vertex WriteVertex(NodeFactory factory) // get invoked. int currentVTableIndexUnused = 0; VertexSequence vtableSignaturesSequence = null; - + ProcessVTableEntriesForCallingConventionSignatureGeneration(factory, VTableEntriesToProcess.AllInVTable, ref currentVTableIndexUnused, (int vtableIndex, bool isSealedVTableSlot, MethodDesc declMethod, MethodDesc implMethod) => { @@ -1357,8 +1349,7 @@ public override Vertex WriteVertex(NodeFactory factory) if (UniversalGenericParameterLayout.VTableMethodRequiresCallingConventionConverter(implMethod)) { - if (vtableSignaturesSequence == null) - vtableSignaturesSequence = new VertexSequence(); + vtableSignaturesSequence ??= new VertexSequence(); NativeLayoutVertexNode methodSignature = factory.NativeLayout.MethodSignatureVertex(declMethod.GetTypicalMethodDefinition().Signature); Vertex signatureVertex = GetNativeWriter(factory).GetRelativeOffsetSignature(methodSignature.WriteVertex(factory)); @@ -1369,8 +1360,7 @@ public override Vertex WriteVertex(NodeFactory factory) vtableSignaturesSequence.Append(vtableSignatureEntry); } - } - , _type, _type, _type); + }, _type, _type, _type); if (vtableSignaturesSequence != null) { @@ -1417,7 +1407,7 @@ private static IEnumerable EnumVirtualSlotsDeclaredOnType(TypeDesc d /// /// Process the vtable entries of a type by calling operation with the vtable index, declaring method, and implementing method - /// Process them in order from 0th entry to last. + /// Process them in order from 0th entry to last. /// Skip generic virtual methods, as they are not present in the vtable itself /// Do not adjust vtable index for generic dictionary slot /// The vtable index is only actually valid if whichEntries is set to VTableEntriesToProcess.AllInVTable @@ -1528,8 +1518,8 @@ public override Vertex WriteVertex(NodeFactory factory) public abstract class NativeLayoutTypeSignatureBasedGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - NativeLayoutTypeSignatureVertexNode _signature; - TypeDesc _type; + private NativeLayoutTypeSignatureVertexNode _signature; + private TypeDesc _type; public NativeLayoutTypeSignatureBasedGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) { @@ -1658,8 +1648,8 @@ public NativeLayoutAllocateArrayGenericDictionarySlotNode(NodeFactory factory, T public abstract class NativeLayoutStaticsGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - NativeLayoutTypeSignatureVertexNode _signature; - TypeDesc _type; + private NativeLayoutTypeSignatureVertexNode _signature; + private TypeDesc _type; public NativeLayoutStaticsGenericDictionarySlotNode(NodeFactory factory, TypeDesc type) { @@ -1709,8 +1699,8 @@ public NativeLayoutNonGcStaticsGenericDictionarySlotNode(NodeFactory factory, Ty public sealed class NativeLayoutInterfaceDispatchGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - NativeLayoutTypeSignatureVertexNode _signature; - MethodDesc _method; + private NativeLayoutTypeSignatureVertexNode _signature; + private MethodDesc _method; public NativeLayoutInterfaceDispatchGenericDictionarySlotNode(NodeFactory factory, MethodDesc method) { @@ -1754,10 +1744,10 @@ protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeF public sealed class NativeLayoutMethodDictionaryGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - MethodDesc _method; - WrappedMethodDictionaryVertexNode _wrappedNode; + private MethodDesc _method; + private WrappedMethodDictionaryVertexNode _wrappedNode; - private class WrappedMethodDictionaryVertexNode : NativeLayoutMethodEntryVertexNode + private sealed class WrappedMethodDictionaryVertexNode : NativeLayoutMethodEntryVertexNode { public WrappedMethodDictionaryVertexNode(NodeFactory factory, MethodDesc method) : base(factory, method, default(MethodEntryFlags)) @@ -1812,7 +1802,7 @@ protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeF public sealed class NativeLayoutFieldOffsetGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - FieldDesc _field; + private FieldDesc _field; public NativeLayoutFieldOffsetGenericDictionarySlotNode(FieldDesc field) { @@ -1846,7 +1836,7 @@ protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeF public sealed class NativeLayoutFieldLdTokenGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - FieldDesc _field; + private FieldDesc _field; public NativeLayoutFieldLdTokenGenericDictionarySlotNode(FieldDesc field) { @@ -1876,8 +1866,8 @@ protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeF public sealed class NativeLayoutVTableOffsetGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - MethodDesc _method; - MethodDesc _slotDefiningMethod; + private MethodDesc _method; + private MethodDesc _slotDefiningMethod; public NativeLayoutVTableOffsetGenericDictionarySlotNode(MethodDesc method) { @@ -1917,7 +1907,7 @@ protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeF public sealed class NativeLayoutMethodLdTokenGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - MethodDesc _method; + private MethodDesc _method; public NativeLayoutMethodLdTokenGenericDictionarySlotNode(MethodDesc method) { @@ -1953,8 +1943,8 @@ protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeF public sealed class NativeLayoutCallingConventionConverterGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - Internal.TypeSystem.MethodSignature _signature; - CallingConventionConverterKind _converterKind; + private Internal.TypeSystem.MethodSignature _signature; + private CallingConventionConverterKind _converterKind; public NativeLayoutCallingConventionConverterGenericDictionarySlotNode(Internal.TypeSystem.MethodSignature signature, CallingConventionConverterKind converterKind) { @@ -1962,7 +1952,7 @@ public NativeLayoutCallingConventionConverterGenericDictionarySlotNode(Internal. _converterKind = converterKind; } - protected sealed override string GetName(NodeFactory factory) => + protected sealed override string GetName(NodeFactory factory) => "NativeLayoutCallingConventionConverterGenericDictionarySlotNode" + _converterKind.ToString() + _signature.GetName(); @@ -1994,9 +1984,9 @@ protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeF public sealed class NativeLayoutConstrainedMethodDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - MethodDesc _constrainedMethod; - TypeDesc _constraintType; - bool _directCall; + private MethodDesc _constrainedMethod; + private TypeDesc _constraintType; + private bool _directCall; public NativeLayoutConstrainedMethodDictionarySlotNode(MethodDesc constrainedMethod, TypeDesc constraintType, bool directCall) { @@ -2010,7 +2000,7 @@ public NativeLayoutConstrainedMethodDictionarySlotNode(MethodDesc constrainedMet protected sealed override string GetName(NodeFactory factory) => "NativeLayoutConstrainedMethodDictionarySlotNode_" + (_directCall ? "Direct" : "") - + factory.NameMangler.GetMangledMethodName(_constrainedMethod) + + factory.NameMangler.GetMangledMethodName(_constrainedMethod) + "," + factory.NameMangler.GetMangledTypeName(_constraintType); @@ -2092,10 +2082,10 @@ protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeF public sealed class NativeLayoutMethodEntrypointGenericDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - MethodDesc _method; - WrappedMethodEntryVertexNode _wrappedNode; + private MethodDesc _method; + private WrappedMethodEntryVertexNode _wrappedNode; - private class WrappedMethodEntryVertexNode : NativeLayoutMethodEntryVertexNode + private sealed class WrappedMethodEntryVertexNode : NativeLayoutMethodEntryVertexNode { public bool _unboxingStub; public IMethodNode _functionPointerNode; @@ -2155,7 +2145,7 @@ protected sealed override Vertex WriteSignatureVertex(NativeWriter writer, NodeF public sealed class NativeLayoutIntegerDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - int _value; + private int _value; public NativeLayoutIntegerDictionarySlotNode(int value) { @@ -2184,7 +2174,7 @@ public override void CheckIfMarkedEnoughToWrite() public sealed class NativeLayoutPointerToOtherSlotDictionarySlotNode : NativeLayoutGenericDictionarySlotNode { - int _otherSlotIndex; + private int _otherSlotIndex; public NativeLayoutPointerToOtherSlotDictionarySlotNode(int otherSlotIndex) { @@ -2221,7 +2211,7 @@ public override IEnumerable GetStaticDependencies(NodeFacto } protected override string GetName(NodeFactory context) => "NativeLayoutNotSupportedDictionarySlotNode"; - + protected override Vertex WriteSignatureVertex(NativeWriter writer, NodeFactory factory) { return writer.GetUnsignedConstant(0xDEADBEEF); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NecessaryCanonicalEETypeNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NecessaryCanonicalEETypeNode.cs index 92cb5e195498c3..d7d6671f0df9fa 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NecessaryCanonicalEETypeNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NecessaryCanonicalEETypeNode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Diagnostics; using Internal.TypeSystem; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NodeFactory.GenericLookups.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NodeFactory.GenericLookups.cs index 3ab46f5bb06681..3fd5291d643c30 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NodeFactory.GenericLookups.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NodeFactory.GenericLookups.cs @@ -8,7 +8,7 @@ namespace ILCompiler.DependencyAnalysis { /// Part of Node factory that deals with nodes describing results of generic lookups. /// See: . - partial class NodeFactory + public partial class NodeFactory { /// /// Helper class that provides a level of grouping for all the generic lookup result kinds. @@ -134,7 +134,7 @@ public GenericLookupResult Type(TypeDesc type) public GenericLookupResult UnwrapNullableType(TypeDesc type) { - // An actual unwrap nullable lookup is only required if the type is exactly a runtime + // An actual unwrap nullable lookup is only required if the type is exactly a runtime // determined type associated with System.__UniversalCanon itself, or if it's // a runtime determined instance of Nullable. if (type.IsRuntimeDeterminedType && ( diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NodeFactory.NativeLayout.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NodeFactory.NativeLayout.cs index b81a81c3064057..4d82b88c5d3022 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NodeFactory.NativeLayout.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NodeFactory.NativeLayout.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Runtime.CompilerServices; using Internal.Text; using Internal.TypeSystem; @@ -12,14 +11,14 @@ namespace ILCompiler.DependencyAnalysis { /// Part of Node factory that deals with nodes describing native layout information - partial class NodeFactory + public partial class NodeFactory { /// /// Helper class that provides a level of grouping for all the native layout lookups /// public class NativeLayoutHelper { - NodeFactory _factory; + private NodeFactory _factory; public NativeLayoutHelper(NodeFactory factory) { @@ -372,7 +371,7 @@ internal NativeLayoutPlacedVertexSequenceVertexNode PlacedVertexSequence(List> + private sealed class UIntSequenceComparer : IEqualityComparer> { bool IEqualityComparer>.Equals(List x, List y) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NodeFactory.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NodeFactory.cs index 9905dcdc255e2c..c5e5aef1e44541 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NodeFactory.cs @@ -209,7 +209,7 @@ private void CreateNodeCaches() _GCStaticsPreInitDataNodes = new NodeCache((MetadataType type) => { ISymbolNode gcStaticsNode = TypeGCStaticsSymbol(type); - Debug.Assert(gcStaticsNode is GCStaticsNode); + Debug.Assert(gcStaticsNode is GCStaticsNode); return ((GCStaticsNode)gcStaticsNode).NewPreInitDataNode(); }); @@ -907,8 +907,7 @@ public IMethodNode ShadowConcreteMethod(MethodDesc method, bool isUnboxingStub = public ISymbolNode HelperEntrypoint(HelperEntrypoint entrypoint) { - if (_helperEntrypointSymbols == null) - _helperEntrypointSymbols = new ISymbolNode[s_helperEntrypointNames.Length]; + _helperEntrypointSymbols ??= new ISymbolNode[s_helperEntrypointNames.Length]; int index = (int)entrypoint; @@ -932,10 +931,7 @@ public MetadataType ArrayOfTClass { get { - if (_systemArrayOfTClass == null) - { - _systemArrayOfTClass = _context.SystemModule.GetKnownType("System", "Array`1"); - } + _systemArrayOfTClass ??= _systemArrayOfTClass = _context.SystemModule.GetKnownType("System", "Array`1"); return _systemArrayOfTClass; } } @@ -945,10 +941,7 @@ public TypeDesc ArrayOfTEnumeratorType { get { - if (_systemArrayOfTEnumeratorType == null) - { - _systemArrayOfTEnumeratorType = ArrayOfTClass.GetNestedType("ArrayEnumerator"); - } + _systemArrayOfTEnumeratorType ??= _systemArrayOfTEnumeratorType = ArrayOfTClass.GetNestedType("ArrayEnumerator"); return _systemArrayOfTEnumeratorType; } } @@ -958,12 +951,9 @@ public MethodDesc InstanceMethodRemovedHelper { get { - if (_instanceMethodRemovedHelper == null) - { - // This helper is optional, but it's fine for this cache to be ineffective if that happens. - // Those scenarios are rare and typically deal with small compilations. - _instanceMethodRemovedHelper = TypeSystemContext.GetOptionalHelperEntryPoint("ThrowHelpers", "ThrowInstanceBodyRemoved"); - } + // This helper is optional, but it's fine for this cache to be ineffective if that happens. + // Those scenarios are rare and typically deal with small compilations. + _instanceMethodRemovedHelper ??= TypeSystemContext.GetOptionalHelperEntryPoint("ThrowHelpers", "ThrowInstanceBodyRemoved"); return _instanceMethodRemovedHelper; } @@ -985,21 +975,21 @@ public DependencyNodeCore VariantInterfaceMethodUse(MethodDesc decl private NodeCache _readyToRunHelpers; - public ISymbolNode ReadyToRunHelper(ReadyToRunHelperId id, Object target) + public ISymbolNode ReadyToRunHelper(ReadyToRunHelperId id, object target) { return _readyToRunHelpers.GetOrAdd(new ReadyToRunHelperKey(id, target)); } private NodeCache _genericReadyToRunHelpersFromDict; - public ISymbolNode ReadyToRunHelperFromDictionaryLookup(ReadyToRunHelperId id, Object target, TypeSystemEntity dictionaryOwner) + public ISymbolNode ReadyToRunHelperFromDictionaryLookup(ReadyToRunHelperId id, object target, TypeSystemEntity dictionaryOwner) { return _genericReadyToRunHelpersFromDict.GetOrAdd(new ReadyToRunGenericHelperKey(id, target, dictionaryOwner)); } private NodeCache _genericReadyToRunHelpersFromType; - public ISymbolNode ReadyToRunHelperFromTypeLookup(ReadyToRunHelperId id, Object target, TypeSystemEntity dictionaryOwner) + public ISymbolNode ReadyToRunHelperFromTypeLookup(ReadyToRunHelperId id, object target, TypeSystemEntity dictionaryOwner) { return _genericReadyToRunHelpersFromType.GetOrAdd(new ReadyToRunGenericHelperKey(id, target, dictionaryOwner)); } @@ -1113,7 +1103,7 @@ public string GetSymbolAlternateName(ISymbolNode node) } public ArrayOfEmbeddedPointersNode GCStaticsRegion = new ArrayOfEmbeddedPointersNode( - "__GCStaticRegionStart", + "__GCStaticRegionStart", "__GCStaticRegionEnd", new SortableDependencyNode.ObjectNodeComparer(CompilerComparer.Instance)); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NonGCStaticsNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NonGCStaticsNode.cs index 09ef4979526233..99b3e8da8ec167 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NonGCStaticsNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NonGCStaticsNode.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections.Generic; using Internal.Text; using Internal.TypeSystem; @@ -126,7 +125,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly) { ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); - // If the type has a class constructor, its non-GC statics section is prefixed + // If the type has a class constructor, its non-GC statics section is prefixed // by System.Runtime.CompilerServices.StaticClassConstructionContext struct. if (factory.PreinitializationManager.HasLazyStaticConstructor(_type)) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ObjectGetTypeFlowDependenciesNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ObjectGetTypeFlowDependenciesNode.cs index e179848db092d3..a30e1a7dc3c555 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ObjectGetTypeFlowDependenciesNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ObjectGetTypeFlowDependenciesNode.cs @@ -8,15 +8,13 @@ using Internal.TypeSystem; -using Debug = System.Diagnostics.Debug; - namespace ILCompiler.DependencyAnalysis { /// /// Represents dataflow dependencies from a call to Object.GetType on an instance statically /// typed as the given type. /// - internal class ObjectGetTypeFlowDependenciesNode : DependencyNodeCore + internal sealed class ObjectGetTypeFlowDependenciesNode : DependencyNodeCore { private readonly MetadataType _type; @@ -33,7 +31,7 @@ protected override string GetName(NodeFactory factory) public override IEnumerable GetStaticDependencies(NodeFactory factory) { var mdManager = (UsageBasedMetadataManager)factory.MetadataManager; - + // We don't mark any members on interfaces - these nodes are only used as conditional dependencies // of other nodes. Calling `object.GetType()` on something typed as an interface will return // something that implements the interface, not the interface itself. We're not reflecting on the @@ -50,6 +48,6 @@ public override IEnumerable GetStaticDependencies(NodeFacto public override bool StaticDependenciesAreComputed => true; public override IEnumerable GetConditionalStaticDependencies(NodeFactory factory) => null; public override IEnumerable SearchDynamicDependencies(List> markedNodes, int firstNode, NodeFactory factory) => null; - + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ObjectWriter.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ObjectWriter.cs index 5f195f34574732..fb1f38266fbb1e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ObjectWriter.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ObjectWriter.cs @@ -76,7 +76,7 @@ public class ObjectWriter : IDisposable, ITypesDebugInfoWriter private UserDefinedTypeDescriptor _userDefinedTypeDescriptor; #if DEBUG - static Dictionary _previouslyWrittenNodeNames = new Dictionary(); + private static Dictionary _previouslyWrittenNodeNames = new Dictionary(); #endif [DllImport(NativeObjectWriterFileName)] @@ -136,7 +136,7 @@ public enum CustomSectionAttributes /// /// Builds a set of CustomSectionAttributes flags from an ObjectNodeSection. /// - private CustomSectionAttributes GetCustomSectionAttributes(ObjectNodeSection section) + private static CustomSectionAttributes GetCustomSectionAttributes(ObjectNodeSection section) { CustomSectionAttributes attributes = 0; @@ -203,7 +203,7 @@ private int EmitSymbolRef(Utf8StringBuilder symbolName, RelocType relocType, int } [DllImport(NativeObjectWriterFileName)] - private static extern void EmitWinFrameInfo(IntPtr objWriter, byte[] methodName, int startOffset, int endOffset, + private static extern void EmitWinFrameInfo(IntPtr objWriter, byte[] methodName, int startOffset, int endOffset, byte[] blobSymbolName); public void EmitWinFrameInfo(int startOffset, int endOffset, int blobSize, byte[] blobSymbolName) { @@ -342,7 +342,7 @@ public string GetMangledName(TypeDesc type) } [DllImport(NativeObjectWriterFileName)] - private static extern void EmitDebugVar(IntPtr objWriter, string name, UInt32 typeIndex, bool isParam, Int32 rangeCount, ref NativeVarInfo range); + private static extern void EmitDebugVar(IntPtr objWriter, string name, uint typeIndex, bool isParam, int rangeCount, ref NativeVarInfo range); public void EmitDebugVar(INodeWithDebugInfo owningNode, in DebugVarInfoMetadata debugVar) { @@ -398,7 +398,7 @@ public void EmitDebugVarInfo(ObjectNode node) } [DllImport(NativeObjectWriterFileName)] - private static extern void EmitDebugEHClause(IntPtr objWriter, UInt32 TryOffset, UInt32 TryLength, UInt32 HandlerOffset, UInt32 HandlerLength); + private static extern void EmitDebugEHClause(IntPtr objWriter, uint TryOffset, uint TryLength, uint HandlerOffset, uint HandlerLength); public void EmitDebugEHClause(DebugEHClauseInfo ehClause) { @@ -422,7 +422,7 @@ public void EmitDebugEHClauseInfo(ObjectNode node) } [DllImport(NativeObjectWriterFileName)] - private static extern void EmitDebugFunctionInfo(IntPtr objWriter, byte[] methodName, int methodSize, UInt32 methodTypeIndex); + private static extern void EmitDebugFunctionInfo(IntPtr objWriter, byte[] methodName, int methodSize, uint methodTypeIndex); public void EmitDebugFunctionInfo(ObjectNode node, int methodSize) { uint methodTypeIndex = 0; @@ -526,7 +526,7 @@ public void PublishUnwindInfo(ObjectNode node) int end = frameInfo.EndOffset; int len = frameInfo.BlobData.Length; byte[] blob = frameInfo.BlobData; - + _sb.Clear().Append(_nodeFactory.NameMangler.CompilationUnitPrefix).Append("_unwind").Append(i.ToStringInvariant()); byte[] blobSymbolName = _sb.Append(_currentNodeZeroTerminatedName).ToUtf8String().UnderlyingArray; @@ -567,7 +567,7 @@ public void PublishUnwindInfo(ObjectNode node) // For window, just emit the frame blob (UNWIND_INFO) as a whole. EmitWinFrameInfo(start, end, len, blobSymbolName); - + EnsureCurrentSection(); } } @@ -777,7 +777,7 @@ private void AppendExternCPrefix(Utf8StringBuilder sb) { if (_targetPlatform.OperatingSystem == TargetOS.OSX) { - // On OSX, we need to prefix an extra underscore to account for correct linkage of + // On OSX, we need to prefix an extra underscore to account for correct linkage of // extern "C" functions. sb.Append('_'); } @@ -946,7 +946,7 @@ private bool ShouldShareSymbol(ObjectNode node) return true; } - private ObjectNodeSection GetSharedSection(ObjectNodeSection section, string key) + private static ObjectNodeSection GetSharedSection(ObjectNodeSection section, string key) { string standardSectionPrefix = ""; if (section.IsStandardSection) @@ -1017,8 +1017,7 @@ public static void EmitObject(string objectFilePath, IReadOnlyCollection instead once it's available to us in this repo @@ -1147,11 +1146,11 @@ public static void EmitObject(string objectFilePath, IReadOnlyCollection _id; - public Object Target => _target; + public object Target => _target; public TypeSystemEntity DictionaryOwner => _dictionaryOwner; public GenericLookupResult LookupSignature => _lookupSignature; @@ -258,10 +258,10 @@ public override IEnumerable GetConditionalStaticDep "Type loader template")); } } - + return conditionalDependencies; } - + public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { var compare = _id.CompareTo(((ReadyToRunGenericHelperNode)other)._id); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReadyToRunHeaderNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReadyToRunHeaderNode.cs index 49f9bafc032c12..243ff6c4769b73 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReadyToRunHeaderNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReadyToRunHeaderNode.cs @@ -1,7 +1,6 @@ // 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 Internal.Runtime; @@ -12,7 +11,7 @@ namespace ILCompiler.DependencyAnalysis { public class ReadyToRunHeaderNode : ObjectNode, ISymbolDefinitionNode { - struct HeaderItem + private struct HeaderItem { public HeaderItem(ReadyToRunSectionType id, ObjectNode node, ISymbolNode startSymbol, ISymbolNode endSymbol) { @@ -22,14 +21,14 @@ public HeaderItem(ReadyToRunSectionType id, ObjectNode node, ISymbolNode startSy EndSymbol = endSymbol; } - readonly public ReadyToRunSectionType Id; - readonly public ObjectNode Node; - readonly public ISymbolNode StartSymbol; - readonly public ISymbolNode EndSymbol; + public readonly ReadyToRunSectionType Id; + public readonly ObjectNode Node; + public readonly ISymbolNode StartSymbol; + public readonly ISymbolNode EndSymbol; } - List _items = new List(); - TargetDetails _target; + private List _items = new List(); + private TargetDetails _target; public ReadyToRunHeaderNode(TargetDetails target) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReadyToRunHelperNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReadyToRunHelperNode.cs index 3787039d53edb1..36cc3c5ec1eda3 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReadyToRunHelperNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReadyToRunHelperNode.cs @@ -46,9 +46,9 @@ public enum ReadyToRunHelperId public partial class ReadyToRunHelperNode : AssemblyStubNode, INodeWithDebugInfo { private readonly ReadyToRunHelperId _id; - private readonly Object _target; + private readonly object _target; - public ReadyToRunHelperNode(ReadyToRunHelperId id, Object target) + public ReadyToRunHelperNode(ReadyToRunHelperId id, object target) { _id = id; _target = target; @@ -86,7 +86,7 @@ public ReadyToRunHelperNode(ReadyToRunHelperId id, Object target) protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public ReadyToRunHelperId Id => _id; - public Object Target => _target; + public object Target => _target; public override void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { @@ -187,8 +187,8 @@ IEnumerable INodeWithDebugInfo.GetNativeSequencePoints() { return new NativeSequencePoint[] { - new NativeSequencePoint(0, String.Empty, WellKnownLineNumber.DebuggerStepThrough), - new NativeSequencePoint(debuggerStepInOffset, String.Empty, WellKnownLineNumber.DebuggerStepIn) + new NativeSequencePoint(0, string.Empty, WellKnownLineNumber.DebuggerStepThrough), + new NativeSequencePoint(debuggerStepInOffset, string.Empty, WellKnownLineNumber.DebuggerStepIn) }; } } @@ -224,7 +224,7 @@ public override int CompareToImpl(ISortableNode other, CompilerComparer comparer default: throw new NotImplementedException(); } - + } #endif } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectableFieldNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectableFieldNode.cs index dd5b429d104380..3fc33b7b03346e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectableFieldNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectableFieldNode.cs @@ -1,7 +1,6 @@ // 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 ILCompiler.DependencyAnalysisFramework; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectableMethodNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectableMethodNode.cs index 1da18b305c4af7..c15760007775d2 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectableMethodNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectableMethodNode.cs @@ -1,7 +1,6 @@ // 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 ILCompiler.DependencyAnalysisFramework; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionFieldMapNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionFieldMapNode.cs index 4c88bd1ffa4022..f1962ed6b3c0d0 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionFieldMapNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionFieldMapNode.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Diagnostics; using Internal.Text; using Internal.TypeSystem; @@ -27,7 +26,7 @@ public ReflectionFieldMapNode(ExternalReferencesTableNode externalReferences) } public ISymbolNode EndSymbol => _endSymbol; - + public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.CompilationUnitPrefix).Append("__field_to_offset_map"); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionInvokeMapNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionInvokeMapNode.cs index f0e9c47b7ea1a1..b8ef007f100407 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionInvokeMapNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionInvokeMapNode.cs @@ -51,8 +51,7 @@ public static void AddDependenciesDueToReflectability(ref DependencyList depende { Debug.Assert(factory.MetadataManager.IsReflectionInvokable(method)); - if (dependencies == null) - dependencies = new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.MaximallyConstructableType(method.OwningType), "Reflection invoke"); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionMethodBodyScanner.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionMethodBodyScanner.cs index 6c663d149b3283..22ca17d449a239 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionMethodBodyScanner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionMethodBodyScanner.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem; using AssemblyName = System.Reflection.AssemblyName; @@ -19,8 +17,6 @@ public static bool ResolveType(string name, ModuleDesc callingModule, TypeSystem // not for correctness, so this shortcut is okay. type = null; - referenceModule = null; - int i = 0; // Consume type name part @@ -75,7 +71,7 @@ public static bool ResolveType(string name, ModuleDesc callingModule, TypeSystem referenceModule = callingModule; if (assemblyName.Length > 0) { - referenceModule = context.ResolveAssembly(new AssemblyName(assemblyName.ToString()), false); + referenceModule = context.ResolveAssembly(new AssemblyName(assemblyName.ToString()), false); } if (referenceModule == null) @@ -96,7 +92,7 @@ public static bool ResolveType(string name, ModuleDesc callingModule, TypeSystem } type = mdType; - + return type != null; } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionVirtualInvokeMapNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionVirtualInvokeMapNode.cs index d724d02eda742d..dd18d08293d143 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionVirtualInvokeMapNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ReflectionVirtualInvokeMapNode.cs @@ -14,7 +14,7 @@ namespace ILCompiler.DependencyAnalysis { /// - /// Represents a map containing the necessary information needed to resolve + /// Represents a map containing the necessary information needed to resolve /// a virtual method target called through reflection. /// internal sealed class ReflectionVirtualInvokeMapNode : ObjectNode, ISymbolDefinitionNode @@ -73,7 +73,7 @@ public static MethodDesc GetDeclaringVirtualMethodAndHierarchyDistance(MethodDes if (containingTypeOfDeclaringMethodForSlot.HasInstantiation) { declaringMethodForSlot = method.Context.GetMethodForInstantiatedType( - declaringMethodForSlot.GetTypicalMethodDefinition(), + declaringMethodForSlot.GetTypicalMethodDefinition(), (InstantiatedType)containingTypeOfDeclaringMethodForSlot); } @@ -86,7 +86,7 @@ public static void GetVirtualInvokeMapDependencies(ref DependencyList dependenci { if (NeedsVirtualInvokeInfo(method)) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add( factory.NecessaryTypeSymbol(method.OwningType.ConvertToCanonForm(CanonicalFormKind.Specific)), @@ -143,12 +143,12 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) // // The vtable entries for each instantiated type might not necessarily exist. - // Example 1: + // Example 1: // If there's a call to Foo.Method1 and a call to Foo.Method2, Foo will // not have Method2 in its vtable and Foo will not have Method1. // Example 2: // If there's a call to Foo.Method1 and a call to Foo.Method2, given that both - // of these instantiations share the same canonical form, Foo<__Canon> will have both method + // of these instantiations share the same canonical form, Foo<__Canon> will have both method // entries, and therefore Foo and Foo will have both entries too. // For this reason, the entries that we write to the map in CoreRT will be based on the canonical form // of the method's containing type instead of the open type definition. @@ -165,21 +165,20 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) continue; // Grammar of an entry in the hash table: - // Virtual Method uses a normal slot + // Virtual Method uses a normal slot // TypeKey + NameAndSig metadata offset into the native layout metadata + (NumberOfStepsUpParentHierarchyToType << 1) + slot // OR - // Generic Virtual Method + // Generic Virtual Method // TypeKey + NameAndSig metadata offset into the native layout metadata + (NumberOfStepsUpParentHierarchyToType << 1 + 1) int parentHierarchyDistance; MethodDesc declaringMethodForSlot = GetDeclaringVirtualMethodAndHierarchyDistance(method, out parentHierarchyDistance); - - Vertex vertex = null; - ISymbolNode containingTypeKeyNode = factory.NecessaryTypeSymbol(containingTypeKey); NativeLayoutMethodNameAndSignatureVertexNode nameAndSig = factory.NativeLayout.MethodNameAndSignatureVertex(method.GetTypicalMethodDefinition()); NativeLayoutPlacedSignatureVertexNode placedNameAndSig = factory.NativeLayout.PlacedSignatureVertex(nameAndSig); + + Vertex vertex; if (method.HasInstantiation) { vertex = writer.GetTuple( diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ResourceDataNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ResourceDataNode.cs index 3b2e7577f4aac5..99165d639d03a2 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ResourceDataNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ResourceDataNode.cs @@ -9,7 +9,6 @@ using System.Reflection.PortableExecutable; using Internal.Text; -using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace ILCompiler.DependencyAnalysis @@ -19,7 +18,7 @@ namespace ILCompiler.DependencyAnalysis /// Resources are simply copied from the inputs and concatenated into this blob. /// All format information is provided by /// - internal class ResourceDataNode : ObjectNode, ISymbolDefinitionNode + internal sealed class ResourceDataNode : ObjectNode, ISymbolDefinitionNode { /// /// Resource index information generated while extracting resources into the data blob @@ -55,7 +54,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) // This node has no relocations. if (relocsOnly) return new ObjectData(Array.Empty(), Array.Empty(), 1, new ISymbolDefinitionNode[] { this }); - + byte[] blob = GenerateResourceBlob(factory); return new ObjectData( blob, @@ -105,7 +104,7 @@ public IReadOnlyList GetOrCreateIndexData(NodeFactory factory string assemblyName = module.GetName().FullName; BlobReader reader = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset); int length = (int)reader.ReadUInt32(); - ResourceIndexData indexData = new ResourceIndexData(assemblyName, resourceName, _totalLength, (int)resource.Offset + sizeof(Int32), module, length); + ResourceIndexData indexData = new ResourceIndexData(assemblyName, resourceName, _totalLength, (int)resource.Offset + sizeof(int), module, length); _indexData.Add(indexData); _totalLength += length; } @@ -153,7 +152,7 @@ private byte[] GenerateResourceBlob(NodeFactory factory) /// /// Data about individual manifest resources /// - internal class ResourceIndexData + internal sealed class ResourceIndexData { public ResourceIndexData(string assemblyName, string resourceName, int nativeOffset, int ecmaOffset, EcmaModule ecmaModule, int length) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ResourceIndexNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ResourceIndexNode.cs index e1e7b2d3af90c4..ffd0b98be601dd 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ResourceIndexNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ResourceIndexNode.cs @@ -5,14 +5,13 @@ using Internal.NativeFormat; using Internal.Text; -using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { /// /// Represents a hash table of resources within the resource blob in the image. /// - internal class ResourceIndexNode : ObjectNode, ISymbolDefinitionNode + internal sealed class ResourceIndexNode : ObjectNode, ISymbolDefinitionNode { private ResourceDataNode _resourceDataNode; @@ -71,7 +70,7 @@ private byte[] GenerateIndexBlob(NodeFactory factory) indexHashtableSection.Place(indexHashtable); // Build a table with a tuple of Assembly Full Name, Resource Name, Offset within the resource data blob, Length - // for each resource. + // for each resource. // This generates a hashtable for the convenience of managed code since there's // a reader for VertexHashtable, but not for VertexSequence. diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/RuntimeFieldHandleNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/RuntimeFieldHandleNode.cs index b681431bcae1ba..1f4aae6eaa5516 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/RuntimeFieldHandleNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/RuntimeFieldHandleNode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Diagnostics; using Internal.Text; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/RuntimeMethodHandleNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/RuntimeMethodHandleNode.cs index 5a12f283cd9950..673ee8c16813ed 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/RuntimeMethodHandleNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/RuntimeMethodHandleNode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Diagnostics; using Internal.Text; @@ -55,7 +54,7 @@ protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFact if (!_targetMethod.IsMethodDefinition && !_targetMethod.OwningType.IsGenericDefinition && _targetMethod.HasInstantiation && _targetMethod.IsVirtual) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.GVMDependencies(_targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific)), "GVM dependencies for runtime method handle"); } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ScannedMethodNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ScannedMethodNode.cs index b9d8d941163d01..b4391164b99dff 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ScannedMethodNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ScannedMethodNode.cs @@ -65,7 +65,7 @@ public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(nameMangler.GetMangledMethodName(_method)); } - + public override IEnumerable GetStaticDependencies(NodeFactory factory) { Debug.Assert(_dependencies != null); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/SealedVTableNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/SealedVTableNode.cs index 9330d03e8fe81d..bb04c7e0acac55 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/SealedVTableNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/SealedVTableNode.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using ILCompiler.DependencyAnalysisFramework; using Internal.Text; using Internal.TypeSystem; @@ -18,7 +17,7 @@ public class SealedVTableNode : ObjectNode, ISymbolDefinitionNode public SealedVTableNode(TypeDesc type) { - // Multidimensional arrays should not get a sealed vtable or a dispatch map. Runtime should use the + // Multidimensional arrays should not get a sealed vtable or a dispatch map. Runtime should use the // sealed vtable and dispatch map of the System.Array basetype instead. // Pointer arrays also follow the same path Debug.Assert(!type.IsArrayTypeWithoutGenericInterfaces()); @@ -42,7 +41,7 @@ public virtual void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder public override bool StaticDependenciesAreComputed => true; /// - /// Returns the number of sealed vtable slots on the type. This API should only be called after successfully + /// Returns the number of sealed vtable slots on the type. This API should only be called after successfully /// building the sealed vtable slots. /// public int NumSealedVTableEntries @@ -63,7 +62,7 @@ public override bool ShouldSkipEmittingObjectNode(NodeFactory factory) } /// - /// Returns the slot of a method in the sealed vtable, or -1 if not found. This API should only be called after + /// Returns the slot of a method in the sealed vtable, or -1 if not found. This API should only be called after /// successfully building the sealed vtable slots. /// public int ComputeSealedVTableSlot(MethodDesc method) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ShadowConcreteUnboxingThunkNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ShadowConcreteUnboxingThunkNode.cs index 40b7a2f450341e..3cc6c0ab953394 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ShadowConcreteUnboxingThunkNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ShadowConcreteUnboxingThunkNode.cs @@ -19,7 +19,7 @@ namespace ILCompiler.DependencyAnalysis /// thunk, as if it was generated. The node acts as a symbol for the canonical thunk /// method for convenience. /// - internal class ShadowConcreteUnboxingThunkNode : DependencyNodeCore, IMethodNode + internal sealed class ShadowConcreteUnboxingThunkNode : DependencyNodeCore, IMethodNode { private IMethodNode _canonicalThunk; @@ -60,7 +60,7 @@ public override IEnumerable GetStaticDependencies(NodeFacto return dependencies; } - protected override string GetName(NodeFactory factory) => $"{Method.ToString()} backed by {_canonicalThunk.GetMangledName(factory.NameMangler)}"; + protected override string GetName(NodeFactory factory) => $"{Method} backed by {_canonicalThunk.GetMangledName(factory.NameMangler)}"; public sealed override bool HasConditionalStaticDependencies => false; public sealed override bool HasDynamicDependencies => false; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StackTraceMethodMappingNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StackTraceMethodMappingNode.cs index 8f3389f584f6ab..71be4ee7c4f787 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StackTraceMethodMappingNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StackTraceMethodMappingNode.cs @@ -4,7 +4,6 @@ using System; using Internal.Text; -using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StaticsInfoHashtableNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StaticsInfoHashtableNode.cs index ba32d69a7d8dd7..306e5c225c8901 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StaticsInfoHashtableNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StaticsInfoHashtableNode.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Diagnostics; using Internal.Text; using Internal.TypeSystem; @@ -38,7 +37,7 @@ public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) public override ObjectNodeSection Section => _externalReferences.Section; public override bool StaticDependenciesAreComputed => true; protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); - + /// /// Helper method to compute the dependencies that would be needed by a hashtable entry for statics info lookup. @@ -60,7 +59,7 @@ public static void AddStaticsInfoDependencies(ref DependencyList dependencies, N if (metadataType.NonGCStaticFieldSize.AsInt > 0 || factory.PreinitializationManager.HasLazyStaticConstructor(type)) { - // The entry in the StaticsInfoHashtable points at the beginning of the static fields data, rather than the cctor + // The entry in the StaticsInfoHashtable points at the beginning of the static fields data, rather than the cctor // context offset. dependencies.Add(factory.TypeNonGCStaticsSymbol(metadataType), "Non-GC statics indirection for StaticsInfoHashtable"); } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StringAllocatorMethodNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StringAllocatorMethodNode.cs index 4d45bcf90aadaf..f5d5be045737f9 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StringAllocatorMethodNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StringAllocatorMethodNode.cs @@ -19,7 +19,7 @@ namespace ILCompiler.DependencyAnalysis /// This node is used to model the behavior. It represents the symbol for the target allocator /// method and makes sure the String type is marked as constructed. /// - class StringAllocatorMethodNode : DependencyNodeCore, IMethodNode + internal sealed class StringAllocatorMethodNode : DependencyNodeCore, IMethodNode { private readonly MethodDesc _allocationMethod; private readonly MethodDesc _constructorMethod; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMDebug.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMDebug.cs index d32b6a2e8d5270..e87f2dc6d353b4 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMDebug.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMDebug.cs @@ -1,7 +1,6 @@ // 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 ILCompiler.DependencyAnalysis.ARM; namespace ILCompiler.DependencyAnalysis @@ -15,7 +14,7 @@ public static void EmitNYIAssert(NodeFactory factory, ref ARMEmitter encoder, st [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0) { ISymbolNode NYI_Assert = factory.ExternSymbol("NYI_Assert"); - String CallInfoPrefix = " " + sourceFilePath + "(" + sourceLineNumber.ToString() + "): method " + memberName + ": "; + string CallInfoPrefix = " " + sourceFilePath + "(" + sourceLineNumber.ToString() + "): method " + memberName + ": "; ISymbolNode messageSymbol = factory.ConstantUtf8String(CallInfoPrefix + message); encoder.EmitMOV(encoder.TargetRegister.Arg0, messageSymbol); encoder.EmitJMP(NYI_Assert); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMInitialInterfaceDispatchStubNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMInitialInterfaceDispatchStubNode.cs index 8ba74c2aa06e19..13c7335323480a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMInitialInterfaceDispatchStubNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMInitialInterfaceDispatchStubNode.cs @@ -19,7 +19,7 @@ namespace ILCompiler.DependencyAnalysis /// cell. /// public partial class InitialInterfaceDispatchStubNode : AssemblyStubNode - { + { protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public override void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMNodeFactory.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMNodeFactory.cs index 3e1bf496dcf37a..3bcd30e2ddb407 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMNodeFactory.cs @@ -1,8 +1,6 @@ // 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 ILCompiler.DependencyAnalysis { public partial class NodeFactory @@ -13,10 +11,7 @@ public InitialInterfaceDispatchStubNode InitialInterfaceDispatchStub { get { - if (_initialInterfaceDispatchStubNode == null) - { - _initialInterfaceDispatchStubNode = new InitialInterfaceDispatchStubNode(); - } + _initialInterfaceDispatchStubNode ??= new InitialInterfaceDispatchStubNode(); return _initialInterfaceDispatchStubNode; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunGenericHelperNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunGenericHelperNode.cs index 2cee3ec3cf97e7..aab05e9597e13b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunGenericHelperNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunGenericHelperNode.cs @@ -11,7 +11,7 @@ namespace ILCompiler.DependencyAnalysis { - partial class ReadyToRunGenericHelperNode + public partial class ReadyToRunGenericHelperNode { protected Register GetContextRegister(ref /* readonly */ ARMEmitter encoder) { @@ -214,7 +214,7 @@ protected virtual void EmitLoadGenericContext(NodeFactory factory, ref ARMEmitte } } - partial class ReadyToRunGenericLookupFromTypeNode + public partial class ReadyToRunGenericLookupFromTypeNode { protected override void EmitLoadGenericContext(NodeFactory factory, ref ARMEmitter encoder, bool relocsOnly) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunHelperNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunHelperNode.cs index 44eada8ff9ae68..d2adbfd2217420 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunHelperNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMReadyToRunHelperNode.cs @@ -4,8 +4,6 @@ using System; using System.Diagnostics; using Internal.TypeSystem; - -using ILCompiler; using ILCompiler.DependencyAnalysis.ARM; namespace ILCompiler.DependencyAnalysis @@ -13,7 +11,7 @@ namespace ILCompiler.DependencyAnalysis /// /// ARM specific portions of ReadyToRunHelperNode /// - partial class ReadyToRunHelperNode + public partial class ReadyToRunHelperNode { protected override void EmitCode(NodeFactory factory, ref ARMEmitter encoder, bool relocsOnly) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMUnboxingStubNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMUnboxingStubNode.cs index 3968eb92af79b1..072121dfc635d1 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMUnboxingStubNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM/ARMUnboxingStubNode.cs @@ -9,7 +9,7 @@ public partial class UnboxingStubNode { protected override void EmitCode(NodeFactory factory, ref ARMEmitter encoder, bool relocsOnly) { - encoder.EmitADD(encoder.TargetRegister.Arg0, (byte)factory.Target.PointerSize); // add r0, sizeof(void*); + encoder.EmitADD(encoder.TargetRegister.Arg0, (byte)factory.Target.PointerSize); // add r0, sizeof(void*); encoder.EmitJMP(GetUnderlyingMethodEntrypoint(factory)); // b methodEntryPoint } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM64/ARM64ReadyToRunGenericHelperNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM64/ARM64ReadyToRunGenericHelperNode.cs index d126ad038c86d5..f0e3edc070cc2a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM64/ARM64ReadyToRunGenericHelperNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM64/ARM64ReadyToRunGenericHelperNode.cs @@ -11,7 +11,7 @@ namespace ILCompiler.DependencyAnalysis { - partial class ReadyToRunGenericHelperNode + public partial class ReadyToRunGenericHelperNode { protected Register GetContextRegister(ref /* readonly */ ARM64Emitter encoder) { @@ -227,7 +227,7 @@ protected virtual void EmitLoadGenericContext(NodeFactory factory, ref ARM64Emit } } - partial class ReadyToRunGenericLookupFromTypeNode + public partial class ReadyToRunGenericLookupFromTypeNode { protected override void EmitLoadGenericContext(NodeFactory factory, ref ARM64Emitter encoder, bool relocsOnly) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM64/ARM64ReadyToRunHelperNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM64/ARM64ReadyToRunHelperNode.cs index 3360ad8d71d656..8c309fef840fa2 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM64/ARM64ReadyToRunHelperNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM64/ARM64ReadyToRunHelperNode.cs @@ -171,7 +171,7 @@ protected override void EmitCode(NodeFactory factory, ref ARM64Emitter encoder, { // Not tested encoder.EmitINT3(); - + encoder.EmitMOV(encoder.TargetRegister.Arg1, factory.InterfaceDispatchCell(targetMethod)); encoder.EmitJMP(factory.ExternSymbol("RhpResolveInterfaceMethod")); } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM64/ARM64UnboxingStubNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM64/ARM64UnboxingStubNode.cs index 40596f8338c3d0..bfa8aa4512e1e9 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM64/ARM64UnboxingStubNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_ARM64/ARM64UnboxingStubNode.cs @@ -1,7 +1,6 @@ // 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 ILCompiler.DependencyAnalysis.ARM64; namespace ILCompiler.DependencyAnalysis @@ -10,7 +9,7 @@ public partial class UnboxingStubNode { protected override void EmitCode(NodeFactory factory, ref ARM64Emitter encoder, bool relocsOnly) { - encoder.EmitADD(encoder.TargetRegister.Arg0, (byte)factory.Target.PointerSize); // add r0, sizeof(void*); + encoder.EmitADD(encoder.TargetRegister.Arg0, (byte)factory.Target.PointerSize); // add r0, sizeof(void*); encoder.EmitJMP(GetUnderlyingMethodEntrypoint(factory)); // b methodEntryPoint } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_LoongArch64/LoongArch64ReadyToRunGenericHelperNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_LoongArch64/LoongArch64ReadyToRunGenericHelperNode.cs index eeb4cfe7c87f3f..095056b587f65b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_LoongArch64/LoongArch64ReadyToRunGenericHelperNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_LoongArch64/LoongArch64ReadyToRunGenericHelperNode.cs @@ -11,7 +11,7 @@ namespace ILCompiler.DependencyAnalysis { - partial class ReadyToRunGenericHelperNode + public partial class ReadyToRunGenericHelperNode { protected Register GetContextRegister(ref /* readonly */ LoongArch64Emitter encoder) { @@ -216,7 +216,7 @@ protected virtual void EmitLoadGenericContext(NodeFactory factory, ref LoongArch } } - partial class ReadyToRunGenericLookupFromTypeNode + public partial class ReadyToRunGenericLookupFromTypeNode { protected override void EmitLoadGenericContext(NodeFactory factory, ref LoongArch64Emitter encoder, bool relocsOnly) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_LoongArch64/LoongArch64UnboxingStubNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_LoongArch64/LoongArch64UnboxingStubNode.cs index 7f523d168ff6de..59e7a64abea2dd 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_LoongArch64/LoongArch64UnboxingStubNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_LoongArch64/LoongArch64UnboxingStubNode.cs @@ -1,7 +1,6 @@ // 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 ILCompiler.DependencyAnalysis.LoongArch64; namespace ILCompiler.DependencyAnalysis diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_X64/X64ReadyToRunGenericHelperNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_X64/X64ReadyToRunGenericHelperNode.cs index 7f9d0645799f9a..802d85ae18c232 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_X64/X64ReadyToRunGenericHelperNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_X64/X64ReadyToRunGenericHelperNode.cs @@ -11,7 +11,7 @@ namespace ILCompiler.DependencyAnalysis { - partial class ReadyToRunGenericHelperNode + public partial class ReadyToRunGenericHelperNode { protected Register GetContextRegister(ref /* readonly */ X64Emitter encoder) { @@ -65,7 +65,7 @@ protected void EmitDictionaryLookup(NodeFactory factory, ref X64Emitter encoder, throw new NotImplementedException(); default: - break; + break; } } @@ -238,7 +238,7 @@ protected virtual void EmitLoadGenericContext(NodeFactory factory, ref X64Emitte } } - partial class ReadyToRunGenericLookupFromTypeNode + public partial class ReadyToRunGenericLookupFromTypeNode { protected override void EmitLoadGenericContext(NodeFactory factory, ref X64Emitter encoder, bool relocsOnly) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_X86/X86ReadyToRunGenericHelperNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_X86/X86ReadyToRunGenericHelperNode.cs index 0367ef8a24a4eb..079a38cc7460a7 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_X86/X86ReadyToRunGenericHelperNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_X86/X86ReadyToRunGenericHelperNode.cs @@ -1,21 +1,15 @@ // 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 ILCompiler.DependencyAnalysis.X86; -using Internal.TypeSystem; - -using Debug = System.Diagnostics.Debug; - namespace ILCompiler.DependencyAnalysis { - partial class ReadyToRunGenericHelperNode - { + public partial class ReadyToRunGenericHelperNode + { protected sealed override void EmitCode(NodeFactory factory, ref X86Emitter encoder, bool relocsOnly) { - encoder.EmitINT3(); + encoder.EmitINT3(); } - } + } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TentativeInstanceMethodNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TentativeInstanceMethodNode.cs index cf6ff01f4297d9..601e594bd69df5 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TentativeInstanceMethodNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TentativeInstanceMethodNode.cs @@ -2,11 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; - -using ILCompiler.DependencyAnalysisFramework; - -using Internal.IL; -using Internal.Text; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TentativeMethodNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TentativeMethodNode.cs index 23d9201244526b..55e082c3409de6 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TentativeMethodNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TentativeMethodNode.cs @@ -18,7 +18,7 @@ namespace ILCompiler.DependencyAnalysis /// body at object emission phase if the real method body was marked. /// It the real method body wasn't marked, this stub will tail-call into a throw helper. /// - partial class TentativeMethodNode : AssemblyStubNode, IMethodNode, ISymbolNodeWithLinkage + public partial class TentativeMethodNode : AssemblyStubNode, IMethodNode, ISymbolNodeWithLinkage { private readonly IMethodBodyNode _methodNode; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ThreadStaticsNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ThreadStaticsNode.cs index e883af326548e6..b1b858022efaa4 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ThreadStaticsNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ThreadStaticsNode.cs @@ -39,7 +39,7 @@ public static string GetMangledName(TypeDesc type, NameMangler nameMangler) int ISymbolNode.Offset => 0; int ISymbolDefinitionNode.Offset => OffsetFromBeginningOfArray; - + public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(GetMangledName(_type, nameMangler)); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TrimmingDescriptorNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TrimmingDescriptorNode.cs index 6fe2a35ff093d9..dad7d0a8eceb50 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TrimmingDescriptorNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TrimmingDescriptorNode.cs @@ -1,14 +1,10 @@ //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.IO; -using System.Reflection.Metadata; -using System.Reflection.PortableExecutable; using ILCompiler.DependencyAnalysisFramework; -using Internal.TypeSystem.Ecma; namespace ILCompiler.DependencyAnalysis { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeGVMEntriesNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeGVMEntriesNode.cs index 12472274c917a4..e13fa43f59c89b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeGVMEntriesNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeGVMEntriesNode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Generic; using System.Diagnostics; @@ -27,7 +26,7 @@ public TypeGVMEntryInfo(MethodDesc callingMethod, MethodDesc implementationMetho public MethodDesc ImplementationMethod { get; } } - internal class InterfaceGVMEntryInfo : TypeGVMEntryInfo + internal sealed class InterfaceGVMEntryInfo : TypeGVMEntryInfo { public InterfaceGVMEntryInfo(MethodDesc callingMethod, MethodDesc implementationMethod, TypeDesc implementationType, DefaultInterfaceMethodResolution defaultResolution) @@ -40,7 +39,7 @@ public InterfaceGVMEntryInfo(MethodDesc callingMethod, MethodDesc implementation public TypeDesc ImplementationType { get; } public DefaultInterfaceMethodResolution DefaultResolution { get; } } - + private readonly TypeDesc _associatedType; private DependencyList _staticDependencies; @@ -89,7 +88,7 @@ public static bool TypeNeedsGVMTableEntries(TypeDesc type) return true; // - // Check if the type implements any interface with GVM methods, where the method implementations could be on + // Check if the type implements any interface with GVM methods, where the method implementations could be on // base types. // Example: // interface IFace { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeManagerIndirectionNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeManagerIndirectionNode.cs index 8e737fde4fb91c..9d1c3c37df35e6 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeManagerIndirectionNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeManagerIndirectionNode.cs @@ -1,10 +1,7 @@ // 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 Internal.Text; -using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeMetadataMapNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeMetadataMapNode.cs index ab69129df3f278..f0132ece3afa7b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeMetadataMapNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeMetadataMapNode.cs @@ -5,7 +5,6 @@ using Internal.NativeFormat; using Internal.Text; -using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { @@ -56,7 +55,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) // not unifying to the same System.Type at runtime. if (!factory.MetadataManager.TypeGeneratesEEType(mappingEntry.Entity) && !factory.CompilationModuleGroup.ShouldReferenceThroughImportTable(mappingEntry.Entity)) continue; - + // Go with a necessary type symbol. It will be upgraded to a constructed one if a constructed was emitted. IEETypeNode typeSymbol = factory.NecessaryTypeSymbol(mappingEntry.Entity); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeMetadataNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeMetadataNode.cs index 12b9913fabe97f..db8c11315b4b9b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeMetadataNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/TypeMetadataNode.cs @@ -1,7 +1,6 @@ // 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 ILCompiler.DependencyAnalysisFramework; @@ -19,7 +18,7 @@ namespace ILCompiler.DependencyAnalysis /// /// Only expected to be used during ILScanning when scanning for reflection. /// - internal class TypeMetadataNode : DependencyNodeCore + internal sealed class TypeMetadataNode : DependencyNodeCore { private readonly MetadataType _type; @@ -129,7 +128,7 @@ public static void GetMetadataDependencies(ref DependencyList dependencies, Node { if (mdManager.CanGenerateMetadata((MetadataType)typeDefinition)) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(nodeFactory.TypeMetadata((MetadataType)typeDefinition), reason); } @@ -142,7 +141,7 @@ public static void GetMetadataDependencies(ref DependencyList dependencies, Node { if (mdManager.CanGenerateMetadata((MetadataType)type)) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(nodeFactory.TypeMetadata((MetadataType)type), reason); } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/UnboxingStubNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/UnboxingStubNode.cs index 29f9222b3011b5..5bad84e227d3e9 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/UnboxingStubNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/UnboxingStubNode.cs @@ -1,13 +1,9 @@ // 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 Internal.Text; using Internal.TypeSystem; -using ILCompiler.DependencyAnalysisFramework; - using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis @@ -20,8 +16,8 @@ public partial class UnboxingStubNode : AssemblyStubNode, IMethodNode, ISymbolDe // Section name on Windows has to be alphabetically less than the ending WindowsUnboxingStubsRegionNode node, and larger than // the begining WindowsUnboxingStubsRegionNode node, in order to have proper delimiters to the begining/ending of the // stubs region, in order for the runtime to know where the region starts and ends. - internal static readonly string WindowsSectionName = ".unbox$M"; - internal static readonly string UnixSectionName = "__unbox"; + internal const string WindowsSectionName = ".unbox$M"; + internal const string UnixSectionName = "__unbox"; private readonly TargetDetails _targetDetails; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VTableSliceNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VTableSliceNode.cs index 8d80ea2f684e3b..02975e52407d60 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VTableSliceNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VTableSliceNode.cs @@ -11,7 +11,7 @@ namespace ILCompiler.DependencyAnalysis { /// - /// Represents the VTable for a type's slice. For example, System.String's VTableSliceNode includes virtual + /// Represents the VTable for a type's slice. For example, System.String's VTableSliceNode includes virtual /// slots added by System.String itself, System.Object's VTableSliceNode contains the virtuals it defines. /// public abstract class VTableSliceNode : DependencyNodeCore @@ -39,7 +39,7 @@ public abstract bool HasFixedSlots get; } - protected override string GetName(NodeFactory factory) => $"__vtable_{factory.NameMangler.GetMangledTypeName(_type).ToString()}"; + protected override string GetName(NodeFactory factory) => $"__vtable_{factory.NameMangler.GetMangledTypeName(_type)}"; public override bool StaticDependenciesAreComputed => true; @@ -104,7 +104,7 @@ public EagerlyBuiltVTableSliceNode(TypeDesc type) private static IReadOnlyList ComputeSlots(TypeDesc type) { - var slots = new ArrayBuilder(); + var slots = default(ArrayBuilder); bool isObjectType = type.IsObject; DefType defType = type.GetClosestDefType(); @@ -157,7 +157,7 @@ public override IReadOnlyList Slots // in GetAllMethods()). // This ensures that Foo and Foo will end up with the same vtable // no matter the order in which VirtualMethodUse nodes populated it. - ArrayBuilder slotsBuilder = new ArrayBuilder(); + ArrayBuilder slotsBuilder = default(ArrayBuilder); DefType defType = _type.GetClosestDefType(); foreach (var method in defType.GetAllMethods()) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VariantInterfaceMethodUseNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VariantInterfaceMethodUseNode.cs index 06135a1dfca122..a81bffeb0b785b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VariantInterfaceMethodUseNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VariantInterfaceMethodUseNode.cs @@ -1,7 +1,6 @@ // 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 ILCompiler.DependencyAnalysisFramework; @@ -20,7 +19,7 @@ namespace ILCompiler.DependencyAnalysis // There's a potential optimization opportunity because e.g. the fact that // IEnumerable.GetEnumerator() is used doesn't mean that // IEnumerable.GetEnumerator() is used, but this complicates the tracking. - internal class VariantInterfaceMethodUseNode : DependencyNodeCore + internal sealed class VariantInterfaceMethodUseNode : DependencyNodeCore { private readonly MethodDesc _decl; @@ -141,7 +140,7 @@ public static bool IsVariantMethodCall(NodeFactory factory, MethodDesc calledMet return result; } - protected override string GetName(NodeFactory factory) => $"VariantInterfaceMethodUse {_decl.ToString()}"; + protected override string GetName(NodeFactory factory) => $"VariantInterfaceMethodUse {_decl}"; public override bool HasConditionalStaticDependencies => false; public override bool HasDynamicDependencies => false; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VirtualMethodUseNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VirtualMethodUseNode.cs index b9f9e63a7d4be8..f97208602afddf 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VirtualMethodUseNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VirtualMethodUseNode.cs @@ -18,7 +18,7 @@ namespace ILCompiler.DependencyAnalysis // // It is used to keep track of uses of virtual methods to ensure that the // vtables are properly constructed - internal class VirtualMethodUseNode : DependencyNodeCore + internal sealed class VirtualMethodUseNode : DependencyNodeCore { private readonly MethodDesc _decl; @@ -38,15 +38,14 @@ public VirtualMethodUseNode(MethodDesc decl) _decl = decl; } - protected override string GetName(NodeFactory factory) => $"VirtualMethodUse {_decl.ToString()}"; + protected override string GetName(NodeFactory factory) => $"VirtualMethodUse {_decl}"; protected override void OnMarked(NodeFactory factory) { // If the VTable slice is getting built on demand, the fact that the virtual method is used means // that the slot is used. var lazyVTableSlice = factory.VTable(_decl.OwningType) as LazilyBuiltVTableSliceNode; - if (lazyVTableSlice != null) - lazyVTableSlice.AddEntry(factory, _decl); + lazyVTableSlice?.AddEntry(factory, _decl); } public override bool HasConditionalStaticDependencies => _decl.Context.SupportsUniversalCanon && _decl.OwningType.HasInstantiation && !_decl.OwningType.IsInterface; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DescriptorMarker.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DescriptorMarker.cs index 1de3b33c137707..1552bbf956e9de 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DescriptorMarker.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DescriptorMarker.cs @@ -8,13 +8,9 @@ using System.IO; using System.Linq; using System.Reflection.Metadata; -using System.Text; using System.Xml.XPath; - -using ILCompiler; using ILCompiler.Dataflow; using ILCompiler.DependencyAnalysis; -using ILLink.Shared; using Internal.TypeSystem; using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyList; @@ -25,14 +21,12 @@ namespace ILCompiler { internal sealed class DescriptorMarker : ProcessLinkerXmlBase { - const string NamespaceElementName = "namespace"; - - const string _required = "required"; - const string _preserve = "preserve"; - const string _accessors = "accessors"; - - static readonly string[] _accessorsAll = new string[] { "all" }; - static readonly char[] _accessorsSep = new char[] { ';' }; + private const string NamespaceElementName = "namespace"; + private const string _required = "required"; + private const string _preserve = "preserve"; + private const string _accessors = "accessors"; + private static readonly string[] _accessorsAll = new string[] { "all" }; + private static readonly char[] _accessorsSep = new char[] { ';' }; private NodeFactory _factory; @@ -60,7 +54,7 @@ protected override void ProcessAssembly(ModuleDesc assembly, XPathNavigator nav, { foreach (var type in assembly.GetAllTypes()) MarkAndPreserve(type, nav, TypePreserve.All); - + //foreach (var exportedType in assembly.MainModule.ExportedTypes) // _context.MarkingHelpers.MarkExportedType(exportedType, assembly.MainModule, new DependencyInfo(DependencyKind.XmlDescriptor, assembly.MainModule), GetMessageOriginForPosition(nav)); } @@ -71,7 +65,7 @@ protected override void ProcessAssembly(ModuleDesc assembly, XPathNavigator nav, } } - void ProcessNamespaces(ModuleDesc assembly, XPathNavigator nav) + private void ProcessNamespaces(ModuleDesc assembly, XPathNavigator nav) { foreach (XPathNavigator namespaceNav in nav.SelectChildren(NamespaceElementName, XmlNamespace)) { @@ -96,7 +90,7 @@ void ProcessNamespaces(ModuleDesc assembly, XPathNavigator nav) } } - void MarkAndPreserve(TypeDesc type, XPathNavigator nav, TypePreserve preserve) + private void MarkAndPreserve(TypeDesc type, XPathNavigator nav, TypePreserve preserve) { var bindingOptions = preserve switch { TypePreserve.Methods => DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods, @@ -200,7 +194,7 @@ protected override void ProcessType(TypeDesc type, XPathNavigator nav) #endif } - static TypePreserve GetTypePreserve(XPathNavigator nav) + private static TypePreserve GetTypePreserve(XPathNavigator nav) { string attribute = GetAttribute(nav, _preserve); if (string.IsNullOrEmpty(attribute)) @@ -242,7 +236,7 @@ protected override void ProcessMethod(TypeDesc type, MethodDesc method, XPathNav } } - void ProcessMethodIfNotNull(TypeDesc type, MethodDesc method, XPathNavigator nav, object? customData) + private void ProcessMethodIfNotNull(TypeDesc type, MethodDesc method, XPathNavigator nav, object? customData) { if (method == null) return; @@ -254,7 +248,7 @@ void ProcessMethodIfNotNull(TypeDesc type, MethodDesc method, XPathNavigator nav { foreach (MethodDesc meth in type.GetAllMethods()) { - if (signature == ProcessLinkerXmlBase.GetMethodSignature(meth, false)) + if (signature == GetMethodSignature(meth, false)) return meth; } return null; @@ -303,7 +297,7 @@ protected override void ProcessProperty(TypeDesc type, PropertyPseudoDesc proper } } - static bool IsRequired(XPathNavigator nav) + private static bool IsRequired(XPathNavigator nav) { string attribute = GetAttribute(nav, _required); if (attribute == null || attribute.Length == 0) @@ -312,7 +306,7 @@ static bool IsRequired(XPathNavigator nav) return bool.TryParse(attribute, out bool result) && result; } - static string[] GetAccessors(XPathNavigator nav) + private static string[] GetAccessors(XPathNavigator nav) { string accessorsValue = GetAttribute(nav, _accessors); @@ -324,7 +318,7 @@ static string[] GetAccessors(XPathNavigator nav) if (accessors.Length > 0) { for (int i = 0; i < accessors.Length; ++i) - accessors[i] = accessors[i].ToLower(); + accessors[i] = accessors[i].ToLowerInvariant(); return accessors; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Disassembler.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Disassembler.cs index fc45079be5f19f..e44fa04665bf08 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Disassembler.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Disassembler.cs @@ -64,7 +64,7 @@ public static string Disassemble(TargetArchitecture arch, byte[] bytes, Relocati return sb.ToString(); } - private class CoreDisassembler : IDisposable + private sealed class CoreDisassembler : IDisposable { private IntPtr _handle; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/EmptyInteropStubManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/EmptyInteropStubManager.cs index fa7a13b217d15a..53dc3e7143a53d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/EmptyInteropStubManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/EmptyInteropStubManager.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem; using ILCompiler.DependencyAnalysis; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSettings.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSettings.cs index 773c061081e459..29781b6448ed97 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSettings.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSettings.cs @@ -1,11 +1,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; using System.Collections.Generic; using System.Xml.XPath; -using ILLink.Shared; -using Internal.TypeSystem; namespace ILCompiler { @@ -46,7 +43,7 @@ public static bool ShouldProcessElement(XPathNavigator nav, IReadOnlyDictionary< public static string GetAttribute(XPathNavigator nav, string attribute) { - return nav.GetAttribute(attribute, String.Empty); + return nav.GetAttribute(attribute, string.Empty); } } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSwitchManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSwitchManager.cs index 9bc4741771bcf1..781c1f455940c5 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSwitchManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSwitchManager.cs @@ -3,14 +3,11 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.IO; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; -using System.Xml; using Internal.IL; -using Internal.IL.Stubs; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; @@ -102,7 +99,7 @@ public override MethodIL GetMethodIL(MethodDesc method) // Flags that we track for each byte of the IL instruction stream. [Flags] - enum OpcodeFlags : byte + private enum OpcodeFlags : byte { // This offset is an instruction boundary. InstructionStart = 0x1, @@ -447,7 +444,7 @@ public MethodIL GetMethodILWithInlinedSubstitutions(MethodIL method) // EH regions with unmarked handlers belong to unmarked basic blocks // Need to eliminate them because they're not usable. - ArrayBuilder newEHRegions = new ArrayBuilder(); + ArrayBuilder newEHRegions = default(ArrayBuilder); foreach (ILExceptionRegion ehRegion in ehRegions) { if ((flags[ehRegion.HandlerOffset] & OpcodeFlags.Mark) != 0) @@ -463,7 +460,7 @@ public MethodIL GetMethodILWithInlinedSubstitutions(MethodIL method) IEnumerable oldSequencePoints = debugInfo?.GetSequencePoints(); if (oldSequencePoints != null) { - ArrayBuilder sequencePoints = new ArrayBuilder(); + ArrayBuilder sequencePoints = default(ArrayBuilder); foreach (var sequencePoint in oldSequencePoints) { if (sequencePoint.Offset < flags.Length && (flags[sequencePoint.Offset] & OpcodeFlags.Mark) != 0) @@ -644,7 +641,7 @@ private bool TryGetConstantArgument(MethodIL methodIL, byte[] body, OpcodeFlags[ return false; } - private class SubstitutedMethodIL : MethodIL + private sealed class SubstitutedMethodIL : MethodIL { private readonly byte[] _body; private readonly ILExceptionRegion[] _ehRegions; @@ -669,7 +666,7 @@ public SubstitutedMethodIL(MethodIL wrapped, byte[] body, ILExceptionRegion[] eh public override MethodDebugInformation GetDebugInfo() => _debugInfo; } - private class SubstitutedDebugInformation : MethodDebugInformation + private sealed class SubstitutedDebugInformation : MethodDebugInformation { private readonly MethodDebugInformation _originalDebugInformation; private readonly ILSequencePoint[] _sequencePoints; @@ -685,7 +682,7 @@ public SubstitutedDebugInformation(MethodDebugInformation originalDebugInformati public override IEnumerable GetSequencePoints() => _sequencePoints; } - private class FeatureSwitchHashtable : LockFreeReaderHashtable + private sealed class FeatureSwitchHashtable : LockFreeReaderHashtable { private readonly Dictionary _switchValues; @@ -705,7 +702,7 @@ protected override AssemblyFeatureInfo CreateValueFromKey(EcmaModule key) } } - private class AssemblyFeatureInfo + private sealed class AssemblyFeatureInfo { public EcmaModule Module { get; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GeneratingMetadataManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GeneratingMetadataManager.cs index eff63e3867837b..3a462b4c9ee81e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GeneratingMetadataManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GeneratingMetadataManager.cs @@ -5,17 +5,12 @@ using System.IO; using System.Collections.Generic; using System.Text; - -using Internal.IL; -using Internal.IL.Stubs; using Internal.TypeSystem; using Internal.Metadata.NativeFormat.Writer; using ILCompiler.Metadata; using ILCompiler.DependencyAnalysis; -using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyList; - namespace ILCompiler { /// @@ -130,8 +125,7 @@ protected void ComputeMetadata( // Reflection requires that we maintain type identity. Even if we only generated a TypeReference record, // if there is an MethodTable for it, we also need a mapping table entry for it. - if (record == null) - record = transformed.GetTransformedTypeReference(definition); + record ??= transformed.GetTransformedTypeReference(definition); if (record != null) typeMappings.Add(new MetadataMapping(definition, writer.GetRecordHandle(record))); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GenericDictionaryLookup.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GenericDictionaryLookup.cs index 49005719c94cdb..a6e088fab7045d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GenericDictionaryLookup.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GenericDictionaryLookup.cs @@ -56,7 +56,7 @@ public ReadyToRunHelperId HelperId } /// - /// Gets a value indicating whether the lookup needs to be performed by calling a helper method. + /// Gets a value indicating whether the lookup needs to be performed by calling a helper method. /// public bool UseHelper { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GenericRootProvider.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GenericRootProvider.cs index 22a2029b3a189c..acbc3a1d16967d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GenericRootProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/GenericRootProvider.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Internal.TypeSystem.Ecma; -using Internal.TypeSystem; using System; namespace ILCompiler diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILAssemblyGeneratingMethodDebugInfoProvider.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILAssemblyGeneratingMethodDebugInfoProvider.cs index 91ef798d5b26d1..1732ce89956523 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILAssemblyGeneratingMethodDebugInfoProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILAssemblyGeneratingMethodDebugInfoProvider.cs @@ -61,7 +61,7 @@ private MethodDebugInformation GetDebugInformation(MethodIL methodIL) var disasm = new ILDisassembler(methodIL); var fmt = new ILDisassembler.ILTypeNameFormatter(null); - ArrayBuilder sequencePoints = new ArrayBuilder(); + ArrayBuilder sequencePoints = default(ArrayBuilder); _tw.Write(".method "); // TODO: accessibility, specialname, calling conventions etc. @@ -146,7 +146,7 @@ public void Dispose() _tw.Dispose(); } - private class SyntheticMethodDebugInformation : MethodDebugInformation + private sealed class SyntheticMethodDebugInformation : MethodDebugInformation { private readonly ILSequencePoint[] _sequencePoints; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScanner.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScanner.cs index 7c6d2ab6431d65..ab6c2b0b99d32d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScanner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScanner.cs @@ -149,7 +149,7 @@ public ISymbolNode GetHelperEntrypoint(ReadyToRunHelper helper) return _helperCache.GetOrCreateValue(helper).Symbol; } - class Helper + private sealed class Helper { public ReadyToRunHelper HelperID { get; } public ISymbolNode Symbol { get; } @@ -162,7 +162,8 @@ public Helper(ReadyToRunHelper id, ISymbolNode symbol) } private HelperCache _helperCache; - class HelperCache : LockFreeReaderHashtable + + private sealed class HelperCache : LockFreeReaderHashtable { private Compilation _compilation; @@ -199,7 +200,7 @@ public interface IILScanner ILScanResults Scan(); } - internal class ScannerFailedException : InternalCompilerErrorException + internal sealed class ScannerFailedException : InternalCompilerErrorException { public ScannerFailedException(string message) : base(message + " " + "You can work around by running the compilation with scanner disabled.") @@ -246,7 +247,7 @@ public MethodImportationErrorProvider GetMethodImportationErrorProvider() return new ScannedMethodImportationErrorProvider(MarkedNodes); } - private class ScannedVTableProvider : VTableSliceProvider + private sealed class ScannedVTableProvider : VTableSliceProvider { private Dictionary> _vtableSlices = new Dictionary>(); @@ -288,7 +289,7 @@ internal override VTableSliceNode GetSlice(TypeDesc type) } } - private class ScannedDictionaryLayoutProvider : DictionaryLayoutProvider + private sealed class ScannedDictionaryLayoutProvider : DictionaryLayoutProvider { private Dictionary> _layouts = new Dictionary>(); private HashSet _entitiesWithForcedLazyLookups = new HashSet(); @@ -362,7 +363,7 @@ public override DictionaryLayoutNode GetLayout(TypeSystemEntity methodOrType) } } - private class ScannedDevirtualizationManager : DevirtualizationManager + private sealed class ScannedDevirtualizationManager : DevirtualizationManager { private HashSet _constructedTypes = new HashSet(); private HashSet _canonConstructedTypes = new HashSet(); @@ -571,7 +572,7 @@ public override TypeDesc[] GetImplementingClasses(TypeDesc type) } } - private class ScannedInliningPolicy : IInliningPolicy + private sealed class ScannedInliningPolicy : IInliningPolicy { private readonly HashSet _constructedTypes = new HashSet(); private readonly CompilationModuleGroup _baseGroup; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScannerBuilder.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScannerBuilder.cs index 7eeabcb00ac4ab..887c90703daf7e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScannerBuilder.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILScannerBuilder.cs @@ -6,8 +6,6 @@ using ILCompiler.DependencyAnalysis; using ILCompiler.DependencyAnalysisFramework; - -using Internal.TypeSystem; using Internal.IL; namespace ILCompiler diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILStreamReader.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILStreamReader.cs index 1f1310d3d0653c..8238d72a3f8a33 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILStreamReader.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILStreamReader.cs @@ -11,7 +11,7 @@ namespace Internal.Compiler /// /// IL Opcode reader in external reader style where the reading is done by trying to read /// various opcodes, and the reader can indicate success or failure of reading a particular opcode - /// + /// /// Used by logic which is designed to encode information in il structure, but not used /// to support general compilation of IL. /// diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILogWriter.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILogWriter.cs index 400c87ef8853bf..8ac77016e1389a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILogWriter.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ILogWriter.cs @@ -1,8 +1,6 @@ // 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 ILCompiler.Logging; namespace ILCompiler diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/InteropStubManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/InteropStubManager.cs index 3c5c4b9d133393..3ea2357cda46cf 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/InteropStubManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/InteropStubManager.cs @@ -1,8 +1,6 @@ // 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 Internal.IL; using Internal.TypeSystem; using ILCompiler.DependencyAnalysis; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/JitHelper.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/JitHelper.cs index 3cbd44db0b3892..ceeffa099ce4b8 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/JitHelper.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/JitHelper.cs @@ -9,7 +9,7 @@ namespace ILCompiler { - internal class JitHelper + internal static class JitHelper { /// /// Returns JIT helper entrypoint. JIT helpers can be either implemented by entrypoint with given mangled name or diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/Graph.Cycles.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/Graph.Cycles.cs index 9819cd855c5e7a..718609d93fe1fd 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/Graph.Cycles.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/Graph.Cycles.cs @@ -14,12 +14,12 @@ internal static partial class LazyGenericsSupport private sealed partial class Graph

{ - class TarjanWorkerClass + private sealed class TarjanWorkerClass { - Stack _inProgress = new Stack(); - int _currentComponentIndex = 0; - Vertex[] _vertices; - List> _result = new List>(); + private Stack _inProgress = new Stack(); + private int _currentComponentIndex; + private Vertex[] _vertices; + private List> _result = new List>(); public TarjanWorkerClass(Vertex[] vertices, bool iterative) { @@ -48,7 +48,7 @@ public TarjanWorkerClass(Vertex[] vertices, bool iterative) } } - void StrongConnectRecursive(Vertex vertex) + private void StrongConnectRecursive(Vertex vertex) { vertex.Index = _currentComponentIndex; vertex.LowLink = _currentComponentIndex; @@ -89,7 +89,7 @@ void StrongConnectRecursive(Vertex vertex) } } - struct StrongConnectStackElement + private struct StrongConnectStackElement { public Vertex Vertex; public IEnumerator EdgeEnumeratorPosition; @@ -97,11 +97,13 @@ struct StrongConnectStackElement private Stack IterativeStrongConnectStack = new Stack(); - void StrongConnectIterative(Vertex vertex) + private void StrongConnectIterative(Vertex vertex) { +#pragma warning disable IDE0059 // Unnecessary assignment of a value IEnumerator currentEdgeEnumerator = null; +#pragma warning restore IDE0059 // Unnecessary assignment of a value -StartOfFunctionWithLogicalRecursion: + StartOfFunctionWithLogicalRecursion: vertex.Index = _currentComponentIndex; vertex.LowLink = _currentComponentIndex; @@ -130,13 +132,15 @@ void StrongConnectIterative(Vertex vertex) if (edge.Destination.Index == -1) { // Recurse if the destination has not begun processing yet - StrongConnectStackElement iterativeStackElement = new StrongConnectStackElement(); + StrongConnectStackElement iterativeStackElement = default(StrongConnectStackElement); iterativeStackElement.Vertex = vertex; iterativeStackElement.EdgeEnumeratorPosition = currentEdgeEnumerator; IterativeStrongConnectStack.Push(iterativeStackElement); +#pragma warning disable IDE0059 // Unnecessary assignment of a value currentEdgeEnumerator = null; +#pragma warning restore IDE0059 // Unnecessary assignment of a value vertex = edge.Destination; goto StartOfFunctionWithLogicalRecursion; } @@ -204,7 +208,7 @@ public IEnumerable

ComputeVerticesInvolvedInAFlaggedCycle() foreach (List stronglyConnectedComponent in stronglyConnectedComponents) { HashSet strongConnectedComponentVertexContainsChecker = new HashSet(stronglyConnectedComponent); - // Detect flags between elements of cycle. + // Detect flags between elements of cycle. // Walk all edges of the strongly connected component. // - If an edge is not flagged, it can't affect behavior // - If an edge is flagged, if it refers to another Vertex in the strongly connected component, then the cycle should be flagged. @@ -335,7 +339,7 @@ private void FindCyclesWorker(Edge edge, List alreadySeen, ref int operati // If this a vertex we've visited already on this path? bool flagged = edge.Flagged || vertex.ProvedToBeInvolvedInAFlaggedCycle; - + int idx = alreadySeen.Count - 1; while (idx != -1 && !(alreadySeen[idx].Destination == vertex)) { @@ -348,10 +352,10 @@ private void FindCyclesWorker(Edge edge, List alreadySeen, ref int operati { Debug.Assert(alreadySeen[idx].Destination == vertex); - // We've seen this vertex already in our path. We now know that this vertex is involved in a simple cycle. + // We've seen this vertex already in our path. We now know that this vertex is involved in a simple cycle. // - // At minimum, we need to mark the root vertex (alreadySeen[0].Destination) if the cycle includes the root and - // includes a flagged edge or a vertex that is itself known to be part of a flagged cycle. + // At minimum, we need to mark the root vertex (alreadySeen[0].Destination) if the cycle includes the root and + // includes a flagged edge or a vertex that is itself known to be part of a flagged cycle. // That's the primary answer our caller seeks. // // At minimum, we also need to stop recursing so that our caller gets an answer at all. @@ -387,4 +391,3 @@ private void FindCyclesWorker(Edge edge, List alreadySeen, ref int operati } } } - diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/Graph.Vertex.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/Graph.Vertex.cs index 1aaeaa191b6639..709113b27b392d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/Graph.Vertex.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/Graph.Vertex.cs @@ -1,7 +1,6 @@ // 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; namespace ILCompiler @@ -75,7 +74,7 @@ public void AddEdge(Vertex toVertex, bool flagged) ///

/// Flag used during Tarjan's algorithm /// - public bool OnStack = false; + public bool OnStack; /// /// Index used in Tarjan's algorithm @@ -87,7 +86,7 @@ public void AddEdge(Vertex toVertex, bool flagged) /// public int LowLink = -1; - public sealed override String ToString() + public sealed override string ToString() { return this.Payload.ToString(); } @@ -107,14 +106,13 @@ public Edge(Vertex destination, bool flagged) public readonly Vertex Destination; public bool Flagged; - public override String ToString() + public override string ToString() { return "[" + (Flagged ? "==>" : "-->") + Destination + "]"; } } - + private Dictionary _vertexMap = new Dictionary(); } } } - diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/Graph.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/Graph.cs index 12fcc14766cd4d..4bb4ff814c6600 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/Graph.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/Graph.cs @@ -10,7 +10,7 @@ internal static partial class LazyGenericsSupport { /// /// A weighted directed graph abstraction. For our purposes, we only use two weights, so our "weight" is a boolean: "Flagged" or "Not Flagged". - /// + /// /// The generic type "P" denotes the type that holds the payload data of graph vertices. Its overload of Object.Equals() is used /// to determine whether two "P"'s represent the same vertex. /// @@ -38,4 +38,3 @@ public IEnumerable

Vertices } } } - diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/GraphBuilder.ForEach.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/GraphBuilder.ForEach.cs index 5fa18aea5886ba..f69af25b836f5e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/GraphBuilder.ForEach.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/GraphBuilder.ForEach.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; using System.Diagnostics; using Internal.TypeSystem; @@ -18,10 +16,10 @@ private sealed partial class GraphBuilder /// Walk through the type expression and find any embedded generic parameter references. For each one found, /// invoke the collector delegate with that generic parameter and a boolean indicate whether this is /// a proper embedding (i.e. there is something actually nesting this.) - /// + /// /// Typically, the type expression is something that a generic type formal is being bound to, and we're /// looking to see if another other generic type formals are referenced within that type expression. - /// + /// /// This method also records bindings for any generic instances it finds inside the tree expression. /// Sometimes, this side-effect is all that's wanted - in such cases, invoke this method with a null collector. ///

@@ -31,8 +29,7 @@ private void ForEachEmbeddedGenericFormal(TypeDesc typeExpression, Instantiation delegate(EcmaGenericParameter embedded, int depth) { bool isProperEmbedding = (depth > 0); - if (collector != null) - collector(embedded, isProperEmbedding); + collector?.Invoke(embedded, isProperEmbedding); return; }; ForEachEmbeddedGenericFormalWorker(typeExpression, typeContext, methodContext, wrappedCollector, depth: 0); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/GraphBuilder.MethodCall.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/GraphBuilder.MethodCall.cs index 5ddd13772827a1..2eb785fb72ab44 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/GraphBuilder.MethodCall.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/GraphBuilder.MethodCall.cs @@ -1,7 +1,6 @@ // 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 Internal.TypeSystem; @@ -49,7 +48,7 @@ private void ProcessMethodCall(MethodDesc target, Instantiation typeContext, Ins delegate(EcmaGenericParameter embedded, bool isProperEmbedding) { // If we got here, we found a method with generic arity (either from itself or its declaring type or both) - // that invokes a generic method. The caller is binding one of the target's generic formals to a type expression + // that invokes a generic method. The caller is binding one of the target's generic formals to a type expression // involving one of the caller's own formals. // // e.g. diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/GraphBuilder.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/GraphBuilder.cs index 7d072ef4d3efb4..408d35fbe87a9d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/GraphBuilder.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/GraphBuilder.cs @@ -18,7 +18,7 @@ public GraphBuilder(EcmaModule assembly) { _graph = new Graph(); _metadataReader = assembly.MetadataReader; - + foreach (TypeDefinitionHandle typeHandle in _metadataReader.TypeDefinitions) { TypeDefinition typeDefinition = _metadataReader.GetTypeDefinition(typeHandle); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/ModuleCycleInfo.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/ModuleCycleInfo.cs index cfbfe6d7a5e476..9a3649c2038106 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/ModuleCycleInfo.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LazyGenerics/ModuleCycleInfo.cs @@ -16,7 +16,7 @@ namespace ILCompiler { internal static partial class LazyGenericsSupport { - private class ModuleCycleInfo + private sealed class ModuleCycleInfo { private readonly HashSet _entitiesInCycles; @@ -38,7 +38,7 @@ public bool FormsCycle(TypeSystemEntity owner) } } - private class CycleInfoHashtable : LockFreeReaderHashtable + private sealed class CycleInfoHashtable : LockFreeReaderHashtable { protected override bool CompareKeyToValue(EcmaModule key, ModuleCycleInfo value) => key == value.Module; protected override bool CompareValueToValue(ModuleCycleInfo value1, ModuleCycleInfo value2) => value1.Module == value2.Module; @@ -70,7 +70,7 @@ protected override ModuleCycleInfo CreateValueFromKey(EcmaModule key) } } - internal class GenericCycleDetector + internal sealed class GenericCycleDetector { private readonly CycleInfoHashtable _hashtable = new CycleInfoHashtable(); @@ -215,8 +215,6 @@ public void DetectCycle(TypeSystemEntity owner, TypeSystemEntity referent) public void LogWarnings(Logger logger) { - var problems = new List>(_actualProblems); - // Might need to sort these if we care about warning determinism, but we probably don't. var reportedProblems = new HashSet(); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LibraryRootProvider.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LibraryRootProvider.cs index 35ef0b337ce89c..00fb2285f85d5a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LibraryRootProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/LibraryRootProvider.cs @@ -47,7 +47,7 @@ public void AddCompilationRoots(IRootingServiceProvider rootProvider) } } - private void RootMethods(TypeDesc type, string reason, IRootingServiceProvider rootProvider) + private static void RootMethods(TypeDesc type, string reason, IRootingServiceProvider rootProvider) { foreach (MethodDesc method in type.GetAllMethods()) { @@ -77,7 +77,7 @@ private void RootMethods(TypeDesc type, string reason, IRootingServiceProvider r } /// - /// Validates that it will be possible to generate '' based on the types + /// Validates that it will be possible to generate '' based on the types /// in its signature. Unresolvable types in a method's signature prevent RyuJIT from generating /// even a stubbed out throwing implementation. /// @@ -101,10 +101,7 @@ private static void CheckTypeCanBeUsedInSignature(TypeDesc type) { MetadataType defType = type as MetadataType; - if (defType != null) - { - defType.ComputeTypeContainsGCPointers(); - } + defType?.ComputeTypeContainsGCPointers(); } } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logger.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logger.cs index fac33d4b58cbcf..84a67825644278 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logger.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logger.cs @@ -13,8 +13,6 @@ using ILCompiler.Dataflow; using ILCompiler.Logging; using ILLink.Shared; - -using ILSequencePoint = Internal.IL.ILSequencePoint; using MethodIL = Internal.IL.MethodIL; using Internal.IL; @@ -177,7 +175,7 @@ internal bool IsWarningSuppressed(int code, MessageOrigin origin) return false; } - bool IsSuppressed(int id, TypeSystemEntity warningOrigin) + private static bool IsSuppressed(int id, TypeSystemEntity warningOrigin) { TypeSystemEntity warningOriginMember = warningOrigin; while (warningOriginMember != null) @@ -193,7 +191,7 @@ bool IsSuppressed(int id, TypeSystemEntity warningOrigin) return false; } - bool IsSuppressedOnElement(int id, TypeSystemEntity provider) + private static bool IsSuppressedOnElement(int id, TypeSystemEntity provider) { if (provider == null) return false; @@ -223,7 +221,7 @@ bool IsSuppressedOnElement(int id, TypeSystemEntity provider) || warningId.Length < 6 || !warningId.StartsWith("IL") || (warningId.Length > 6 && warningId[6] != ':') - || !int.TryParse(warningId.Substring(2, 4), out int suppressedCode)) + || !int.TryParse(warningId.AsSpan(2, 4), out int suppressedCode)) { continue; } @@ -238,7 +236,7 @@ bool IsSuppressedOnElement(int id, TypeSystemEntity provider) return false; } - internal bool IsWarningAsError(int code) + internal static bool IsWarningAsError(int code) { // TODO: warnaserror return false; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/DocumentationSignatureGenerator.PartVisitor.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/DocumentationSignatureGenerator.PartVisitor.cs index fbb5ec5749ce20..10122ce083e07a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/DocumentationSignatureGenerator.PartVisitor.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/DocumentationSignatureGenerator.PartVisitor.cs @@ -1,6 +1,5 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Text; @@ -134,7 +133,7 @@ public override void AppendName(StringBuilder builder, GenericParameterDesc gene // If the containing type is nested within other types. // e.g. A.B.M(T t, U u, V v) should be M(`0, `1, ``0). - // Roslyn needs to add generic arities of parents, but the innermost type redeclares + // Roslyn needs to add generic arities of parents, but the innermost type redeclares // all generic parameters so we don't need to add them. builder.Append('`'); } @@ -178,7 +177,7 @@ protected override void AppendNameForInstantiatedType(StringBuilder builder, Def string unmangledName = type.Name; int totalArity = type.Instantiation.Length; - string expectedSuffix = $"`{totalArity.ToString()}"; + string expectedSuffix = $"`{totalArity}"; if (unmangledName.EndsWith(expectedSuffix)) unmangledName = unmangledName.Substring(0, unmangledName.Length - expectedSuffix.Length); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/DocumentationSignatureParser.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/DocumentationSignatureParser.cs index 3a9e7cf8768c30..640adbc7a84353 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/DocumentationSignatureParser.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/DocumentationSignatureParser.cs @@ -1,6 +1,5 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; @@ -54,7 +53,7 @@ public static TypeDesc GetTypeByDocumentationSignature(IAssemblyDesc assembly, s { int index = 0; var results = new List(); - DocumentationSignatureParser.ParseSignaturePart(signature, ref index, (ModuleDesc)assembly, DocumentationSignatureParser.MemberType.Type, results); + ParseSignaturePart(signature, ref index, (ModuleDesc)assembly, MemberType.Type, results); Debug.Assert(results.Count <= 1); return results.Count == 0 ? null : (TypeDesc)results[0]; } @@ -65,19 +64,19 @@ public static IEnumerable GetMembersByDocumentationSignature(M int index = 0; var results = new List(); var nameBuilder = new StringBuilder(); - var (name, arity) = DocumentationSignatureParser.ParseTypeOrNamespaceName(signature, ref index, nameBuilder); - DocumentationSignatureParser.GetMatchingMembers(signature, ref index, type.Module, type, name, arity, DocumentationSignatureParser.MemberType.All, results, acceptName); + var (name, arity) = ParseTypeOrNamespaceName(signature, ref index, nameBuilder); + GetMatchingMembers(signature, ref index, type.Module, type, name, arity, MemberType.All, results, acceptName); return results; } - static string GetSignaturePart(TypeDesc type) + private static string GetSignaturePart(TypeDesc type) { var builder = new StringBuilder(); DocumentationSignatureGenerator.PartVisitor.Instance.AppendName(builder, type); return builder.ToString(); } - static bool ParseDocumentationSignature(string id, ModuleDesc module, List results) + private static bool ParseDocumentationSignature(string id, ModuleDesc module, List results) { if (id == null) return false; @@ -91,7 +90,7 @@ static bool ParseDocumentationSignature(string id, ModuleDesc module, List 0; } - static void ParseSignature(string id, ref int index, ModuleDesc module, List results) + private static void ParseSignature(string id, ref int index, ModuleDesc module, List results) { Debug.Assert(results.Count == 0); var memberTypeChar = PeekNextChar(id, index); @@ -150,7 +149,7 @@ public static void ParseSignaturePart(string id, ref int index, ModuleDesc modul (name, arity) = ParseTypeOrNamespaceName(id, ref index, nameBuilder); // if we are at the end of the dotted name and still haven't resolved it to // a type, there are no results. - if (String.IsNullOrEmpty(name)) + if (string.IsNullOrEmpty(name)) return; // no more dots, so don't loop any more @@ -276,7 +275,7 @@ public static (string name, int arity) ParseTypeOrNamespaceName(string id, ref i // To avoid looking for types by name in all referenced assemblies, we just represent types // that are part of a signature by their doc comment strings, and we check for matching // strings when looking for matching member signatures. - static string ParseTypeSymbol(string id, ref int index, TypeSystemEntity typeParameterContext) + private static string ParseTypeSymbol(string id, ref int index, TypeSystemEntity typeParameterContext) { var results = new List(); ParseTypeSymbol(id, ref index, typeParameterContext, results); @@ -287,7 +286,7 @@ static string ParseTypeSymbol(string id, ref int index, TypeSystemEntity typePar return null; } - static void ParseTypeSymbol(string id, ref int index, TypeSystemEntity typeParameterContext, List results) + private static void ParseTypeSymbol(string id, ref int index, TypeSystemEntity typeParameterContext, List results) { // Note: Roslyn has a special case that deviates from the language spec, which // allows context expressions embedded in a type reference => : @@ -348,7 +347,7 @@ static void ParseTypeSymbol(string id, ref int index, TypeSystemEntity typeParam index = endIndex; } - static void ParseTypeParameterSymbol(string id, ref int index, TypeSystemEntity typeParameterContext, List results) + private static void ParseTypeParameterSymbol(string id, ref int index, TypeSystemEntity typeParameterContext, List results) { // skip the first ` Debug.Assert(PeekNextChar(id, index) == '`'); @@ -393,7 +392,7 @@ typeParameterContext is TypeDesc } } - static void ParseNamedTypeSymbol(string id, ref int index, TypeSystemEntity typeParameterContext, List results) + private static void ParseNamedTypeSymbol(string id, ref int index, TypeSystemEntity typeParameterContext, List results) { Debug.Assert(results.Count == 0); var nameBuilder = new StringBuilder(); @@ -401,7 +400,7 @@ static void ParseNamedTypeSymbol(string id, ref int index, TypeSystemEntity type while (true) { var name = ParseName(id, ref index); - if (String.IsNullOrEmpty(name)) + if (string.IsNullOrEmpty(name)) return; nameBuilder.Append(name); @@ -448,7 +447,7 @@ static void ParseNamedTypeSymbol(string id, ref int index, TypeSystemEntity type results.Add(nameBuilder.ToString()); } - static int ParseArrayBounds(string id, ref int index) + private static int ParseArrayBounds(string id, ref int index) { index++; // skip '[' @@ -491,7 +490,7 @@ static int ParseArrayBounds(string id, ref int index) return bounds; } - static bool ParseTypeArguments(string id, ref int index, TypeSystemEntity typeParameterContext, List typeArguments) + private static bool ParseTypeArguments(string id, ref int index, TypeSystemEntity typeParameterContext, List typeArguments) { index++; // skip over { @@ -526,7 +525,7 @@ static bool ParseTypeArguments(string id, ref int index, TypeSystemEntity typePa return true; } - static void GetMatchingTypes(ModuleDesc module, TypeDesc declaringType, string name, int arity, List results) + private static void GetMatchingTypes(ModuleDesc module, TypeDesc declaringType, string name, int arity, List results) { Debug.Assert(module != null); @@ -559,7 +558,7 @@ static void GetMatchingTypes(ModuleDesc module, TypeDesc declaringType, string n foreach (var nestedType in mdDeclaringType.GetNestedTypes()) { - Debug.Assert(String.IsNullOrEmpty(nestedType.Namespace)); + Debug.Assert(string.IsNullOrEmpty(nestedType.Namespace)); if (nestedType.Name != name) continue; @@ -575,7 +574,7 @@ static void GetMatchingTypes(ModuleDesc module, TypeDesc declaringType, string n } } - static void GetMatchingMethods(string id, ref int index, TypeDesc type, string memberName, int arity, List results, bool acceptName = false) + private static void GetMatchingMethods(string id, ref int index, TypeDesc type, string memberName, int arity, List results, bool acceptName = false) { if (type == null) return; @@ -677,7 +676,7 @@ static void GetMatchingProperties(string id, ref int index, TypeDesc type, strin } #endif - static void GetMatchingFields(TypeDesc type, string memberName, List results) + private static void GetMatchingFields(TypeDesc type, string memberName, List results) { if (type == null) return; @@ -703,7 +702,7 @@ static void GetMatchingEvents(TypeDesc type, string memberName, List expectedParameters) + private static bool AllParametersMatch(MethodSignature methodParameters, List expectedParameters) { if (methodParameters.Length != expectedParameters.Count) return false; @@ -717,9 +716,9 @@ static bool AllParametersMatch(MethodSignature methodParameters, List ex return true; } - static bool ParseParameterList(string id, ref int index, TypeSystemEntity typeParameterContext, List parameters) + private static bool ParseParameterList(string id, ref int index, TypeSystemEntity typeParameterContext, List parameters) { - System.Diagnostics.Debug.Assert(typeParameterContext != null); + Debug.Assert(typeParameterContext != null); index++; // skip over '(' @@ -756,14 +755,14 @@ static bool ParseParameterList(string id, ref int index, TypeSystemEntity typePa return true; } - static char PeekNextChar(string id, int index) + private static char PeekNextChar(string id, int index) { return index >= id.Length ? '\0' : id[index]; } - static readonly char[] s_nameDelimiters = { ':', '.', '(', ')', '{', '}', '[', ']', ',', '\'', '@', '*', '`', '~' }; + private static readonly char[] s_nameDelimiters = { ':', '.', '(', ')', '{', '}', '[', ']', ',', '\'', '@', '*', '`', '~' }; - static string ParseName(string id, ref int index) + private static string ParseName(string id, ref int index) { string name; @@ -783,12 +782,12 @@ static string ParseName(string id, ref int index) } // undoes dot encodings within names... - static string DecodeName(string name) + private static string DecodeName(string name) { return name.Replace('#', '.'); } - static int ReadNextInteger(string id, ref int index) + private static int ReadNextInteger(string id, ref int index) { int n = 0; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/MessageContainer.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/MessageContainer.cs index 8f6e4f33efd2fd..733347fe0b8f3f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/MessageContainer.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/MessageContainer.cs @@ -131,7 +131,7 @@ internal static MessageContainer CreateErrorMessage(MessageOrigin? origin, Diagn if (TryLogSingleWarning(context, code, origin, subcategory)) return null; - if (context.IsWarningAsError(code)) + if (Logger.IsWarningAsError(code)) return new MessageContainer(MessageCategory.WarningAsError, text, code, subcategory, origin); return new MessageContainer(MessageCategory.Warning, text, code, subcategory, origin); @@ -148,7 +148,7 @@ internal static MessageContainer CreateErrorMessage(MessageOrigin? origin, Diagn if (TryLogSingleWarning(context, (int)id, origin, subcategory)) return null; - if (context.IsWarningAsError((int)id)) + if (Logger.IsWarningAsError((int)id)) return new MessageContainer(MessageCategory.WarningAsError, id, subcategory, origin, args); return new MessageContainer(MessageCategory.Warning, id, subcategory, origin, args); @@ -265,10 +265,10 @@ public string ToMSBuildString() string origin = Origin?.ToString() ?? originApp; StringBuilder sb = new StringBuilder(); - sb.Append(origin).Append(":"); + sb.Append(origin).Append(':'); if (!string.IsNullOrEmpty(SubCategory)) - sb.Append(" ").Append(SubCategory); + sb.Append(' ').Append(SubCategory); string cat; switch (Category) @@ -287,7 +287,7 @@ public string ToMSBuildString() if (!string.IsNullOrEmpty(cat)) { - sb.Append(" ") + sb.Append(' ') .Append(cat) .Append(" IL") .Append(Code.Value.ToString("D4")) @@ -295,7 +295,7 @@ public string ToMSBuildString() } else { - sb.Append(" "); + sb.Append(' '); } if (Origin?.MemberDefinition != null) diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/MessageOrigin.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/MessageOrigin.cs index b2d002cca090fc..8590ab5b2fb6ef 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/MessageOrigin.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logging/MessageOrigin.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Reflection.Metadata; using System.Text; using Internal.IL; using Internal.TypeSystem; @@ -82,11 +81,11 @@ public MessageOrigin WithInstructionOffset(MethodIL methodBody, int ilOffset) StringBuilder sb = new StringBuilder(FileName); if (SourceLine.HasValue) { - sb.Append("(").Append(SourceLine); + sb.Append('(').Append(SourceLine); if (SourceColumn.HasValue) - sb.Append(",").Append(SourceColumn); + sb.Append(',').Append(SourceColumn); - sb.Append(")"); + sb.Append(')'); } return sb.ToString(); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ManifestResourceBlockingPolicy.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ManifestResourceBlockingPolicy.cs index 3b2b3a2e25384b..325368c2abe885 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ManifestResourceBlockingPolicy.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ManifestResourceBlockingPolicy.cs @@ -39,7 +39,7 @@ public virtual bool IsManifestResourceBlocked(ModuleDesc module, string resource || (resourceName.StartsWith("ILLink.") && resourceName.EndsWith(".xml"))); } - private class FeatureSwitchHashtable : LockFreeReaderHashtable + private sealed class FeatureSwitchHashtable : LockFreeReaderHashtable { private readonly Dictionary _switchValues; @@ -59,7 +59,7 @@ protected override AssemblyFeatureInfo CreateValueFromKey(EcmaModule key) } } - private class AssemblyFeatureInfo + private sealed class AssemblyFeatureInfo { public EcmaModule Module { get; } @@ -100,7 +100,7 @@ public AssemblyFeatureInfo(EcmaModule module, IReadOnlyDictionary } } - private class SubstitutionsReader : ProcessXmlBase + private sealed class SubstitutionsReader : ProcessXmlBase { private readonly HashSet _substitutions = new HashSet(); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataManager.cs index f2101a2e876a9d..b63026dae37a79 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MetadataManager.cs @@ -185,8 +185,7 @@ protected virtual void Graph_NewMarkedNode(DependencyNodeCore obj) _reflectableMethods.Add(methodNode.Method); } - if (methodNode == null) - methodNode = obj as ShadowConcreteMethodNode; + methodNode ??= obj as ShadowConcreteMethodNode; if (methodNode != null) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MstatObjectDumper.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MstatObjectDumper.cs index 0f0af381c2e6ed..d0d804dfd9ef20 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MstatObjectDumper.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MstatObjectDumper.cs @@ -14,7 +14,6 @@ using ObjectData = ILCompiler.DependencyAnalysis.ObjectNode.ObjectData; using AssemblyName = System.Reflection.AssemblyName; using System.Collections.Generic; -using static ILCompiler.DependencyAnalysis.ObjectNode; namespace ILCompiler { @@ -33,7 +32,7 @@ public class MstatObjectDumper : ObjectDumper private Dictionary _blobs = new(); private Utf8StringBuilder _utf8StringBuilder = new Utf8StringBuilder(); - + public MstatObjectDumper(string fileName, TypeSystemContext context) { _fileName = fileName; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MultiFileCompilationModuleGroup.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MultiFileCompilationModuleGroup.cs index ba9da7828607da..05888aebfef83e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MultiFileCompilationModuleGroup.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MultiFileCompilationModuleGroup.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Generic; using System.Diagnostics; @@ -111,7 +110,7 @@ public override bool ShouldPromoteToFullType(TypeDesc type) public override bool PresenceOfEETypeImpliesAllMethodsOnType(TypeDesc type) { - return (type.HasInstantiation || type.IsArray) && ShouldProduceFullVTable(type) && + return (type.HasInstantiation || type.IsArray) && ShouldProduceFullVTable(type) && type.ConvertToCanonForm(CanonicalFormKind.Specific).IsCanonicalSubtype(CanonicalFormKind.Any); } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/NativeLibraryInitializerRootProvider.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/NativeLibraryInitializerRootProvider.cs index 4b7c639400f647..759b9ca25ab5d0 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/NativeLibraryInitializerRootProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/NativeLibraryInitializerRootProvider.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; - -using Internal.TypeSystem.Ecma; using Internal.TypeSystem; using Internal.IL.Stubs.StartupCode; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/NodeMangler.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/NodeMangler.cs index ea9586de22de21..72110ed895d53b 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/NodeMangler.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/NodeMangler.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Internal.Text; using Internal.TypeSystem; namespace ILCompiler @@ -10,7 +9,7 @@ namespace ILCompiler // NodeMangler is responsible for producing mangled names for specific nodes // and for node-related purposes, where the name needs to be in a special format // on some platform - // + // public abstract class NodeMangler { public NameMangler NameMangler; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ObjectDumper.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ObjectDumper.cs index 10d229da90c47e..355f766040d87f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ObjectDumper.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ObjectDumper.cs @@ -1,11 +1,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; using System.Collections.Generic; -using Internal.Text; - using ILCompiler.DependencyAnalysis; using ObjectData = ILCompiler.DependencyAnalysis.ObjectNode.ObjectData; @@ -37,7 +34,7 @@ protected static string GetObjectNodeName(ObjectNode node) public static ObjectDumper Compose(IEnumerable dumpers) { - var dumpersList = new ArrayBuilder(); + var dumpersList = default(ArrayBuilder); foreach (var dumper in dumpers) dumpersList.Add(dumper); @@ -50,7 +47,7 @@ public static ObjectDumper Compose(IEnumerable dumpers) }; } - private class ComposedObjectDumper : ObjectDumper + private sealed class ComposedObjectDumper : ObjectDumper { private readonly ObjectDumper[] _dumpers; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/PreinitializationManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/PreinitializationManager.cs index 36630dccd29e91..c76c65e3a5ebbe 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/PreinitializationManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/PreinitializationManager.cs @@ -8,7 +8,7 @@ namespace ILCompiler { /// - /// Manages policies around static constructors (.cctors) and static data initialization. + /// Manages policies around static constructors (.cctors) and static data initialization. /// public class PreinitializationManager { @@ -76,7 +76,7 @@ public bool HasEagerStaticConstructor(TypeDesc type) private static bool HasEagerConstructorAttribute(TypeDesc type) { MetadataType mdType = type as MetadataType; - return mdType != null && + return mdType != null && mdType.HasCustomAttribute("System.Runtime.CompilerServices", "EagerStaticClassConstructionAttribute"); } @@ -88,7 +88,7 @@ public bool IsPreinitialized(MetadataType type) if (!type.HasStaticConstructor) return false; - + // The cctor on the Module type is the module constructor. That's special. if (type.IsModuleType) return false; @@ -133,7 +133,7 @@ public TypePreinit.PreinitializationInfo GetPreinitializationInfo(MetadataType t return _preinitHashTable.GetOrCreateValue(type); } - class PreinitializationInfoHashtable : LockFreeReaderHashtable + private sealed class PreinitializationInfoHashtable : LockFreeReaderHashtable { private readonly CompilationModuleGroup _compilationGroup; private readonly ILProvider _ilProvider; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessLinkerXmlBase.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessLinkerXmlBase.cs index ed595e1d808cdc..c72529b6dfdb68 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessLinkerXmlBase.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessLinkerXmlBase.cs @@ -32,20 +32,20 @@ public enum AllowedAssemblies public abstract class ProcessLinkerXmlBase { - const string FullNameAttributeName = "fullname"; - const string LinkerElementName = "linker"; - const string TypeElementName = "type"; - const string SignatureAttributeName = "signature"; - const string NameAttributeName = "name"; - const string FieldElementName = "field"; - const string MethodElementName = "method"; - const string EventElementName = "event"; - const string PropertyElementName = "property"; - const string AllAssembliesFullName = "*"; + private const string FullNameAttributeName = "fullname"; + private const string LinkerElementName = "linker"; + private const string TypeElementName = "type"; + private const string SignatureAttributeName = "signature"; + private const string NameAttributeName = "name"; + private const string FieldElementName = "field"; + private const string MethodElementName = "method"; + private const string EventElementName = "event"; + private const string PropertyElementName = "property"; + private const string AllAssembliesFullName = "*"; protected const string XmlNamespace = ""; protected readonly string _xmlDocumentLocation; - readonly XPathNavigator _document; + private readonly XPathNavigator _document; protected readonly ModuleDesc? _owningModule; private readonly IReadOnlyDictionary _featureSwitchValues; protected readonly TypeSystemContext _context; @@ -107,7 +107,7 @@ protected virtual void ProcessXml(bool ignoreResource) protected virtual AllowedAssemblies AllowedAssemblySelector { get => _owningModule != null ? AllowedAssemblies.ContainingAssembly : AllowedAssemblies.AnyAssembly; } - bool ShouldProcessAllAssemblies(XPathNavigator nav, [NotNullWhen(false)] out AssemblyName? assemblyName) + private bool ShouldProcessAllAssemblies(XPathNavigator nav, [NotNullWhen(false)] out AssemblyName? assemblyName) { assemblyName = null; if (GetFullName(nav) == AllAssembliesFullName) @@ -207,7 +207,7 @@ protected virtual void ProcessTypes(ModuleDesc assembly, XPathNavigator nav, boo } } - void MatchType(TypeDesc type, Regex regex, XPathNavigator nav) + private void MatchType(TypeDesc type, Regex regex, XPathNavigator nav) { StringBuilder sb = new StringBuilder(); CecilTypeNameFormatter.Instance.AppendName(sb, type); @@ -238,7 +238,7 @@ protected void ProcessTypeChildren(TypeDesc type, XPathNavigator nav, object? cu } } - void ProcessSelectedFields(XPathNavigator nav, TypeDesc type) + private void ProcessSelectedFields(XPathNavigator nav, TypeDesc type) { foreach (XPathNavigator fieldNav in nav.SelectChildren(FieldElementName, XmlNamespace)) { @@ -251,7 +251,7 @@ void ProcessSelectedFields(XPathNavigator nav, TypeDesc type) protected virtual void ProcessField(TypeDesc type, XPathNavigator nav) { string signature = GetSignature(nav); - if (!String.IsNullOrEmpty(signature)) + if (!string.IsNullOrEmpty(signature)) { FieldDesc? field = GetField(type, signature); if (field == null) @@ -264,7 +264,7 @@ protected virtual void ProcessField(TypeDesc type, XPathNavigator nav) } string name = GetName(nav); - if (!String.IsNullOrEmpty(name)) + if (!string.IsNullOrEmpty(name)) { bool foundMatch = false; foreach (FieldDesc field in type.GetFields()) @@ -300,7 +300,7 @@ protected virtual void ProcessField(TypeDesc type, XPathNavigator nav) protected virtual void ProcessField(TypeDesc type, FieldDesc field, XPathNavigator nav) { } - void ProcessSelectedMethods(XPathNavigator nav, TypeDesc type, object? customData) + private void ProcessSelectedMethods(XPathNavigator nav, TypeDesc type, object? customData) { foreach (XPathNavigator methodNav in nav.SelectChildren(MethodElementName, XmlNamespace)) { @@ -313,7 +313,7 @@ void ProcessSelectedMethods(XPathNavigator nav, TypeDesc type, object? customDat protected virtual void ProcessMethod(TypeDesc type, XPathNavigator nav, object? customData) { string signature = GetSignature(nav); - if (!String.IsNullOrEmpty(signature)) + if (!string.IsNullOrEmpty(signature)) { MethodDesc? method = GetMethod(type, signature); if (method == null) @@ -326,7 +326,7 @@ protected virtual void ProcessMethod(TypeDesc type, XPathNavigator nav, object? } string name = GetAttribute(nav, NameAttributeName); - if (!String.IsNullOrEmpty(name)) + if (!string.IsNullOrEmpty(name)) { bool foundMatch = false; foreach (MethodDesc method in type.GetAllMethods()) @@ -348,7 +348,7 @@ protected virtual void ProcessMethod(TypeDesc type, XPathNavigator nav, object? protected virtual void ProcessMethod(TypeDesc type, MethodDesc method, XPathNavigator nav, object? customData) { } - void ProcessSelectedEvents(XPathNavigator nav, TypeDesc type, object? customData) + private void ProcessSelectedEvents(XPathNavigator nav, TypeDesc type, object? customData) { foreach (XPathNavigator eventNav in nav.SelectChildren(EventElementName, XmlNamespace)) { @@ -361,7 +361,7 @@ void ProcessSelectedEvents(XPathNavigator nav, TypeDesc type, object? customData protected virtual void ProcessEvent(TypeDesc type, XPathNavigator nav, object? customData) { string signature = GetSignature(nav); - if (!String.IsNullOrEmpty(signature)) + if (!string.IsNullOrEmpty(signature)) { EventPseudoDesc? @event = GetEvent(type, signature); if (@event is null) @@ -374,7 +374,7 @@ protected virtual void ProcessEvent(TypeDesc type, XPathNavigator nav, object? c } string name = GetAttribute(nav, NameAttributeName); - if (!String.IsNullOrEmpty(name)) + if (!string.IsNullOrEmpty(name)) { bool foundMatch = false; if (type.GetTypeDefinition() is not EcmaType ecmaType) @@ -404,7 +404,7 @@ protected virtual void ProcessEvent(TypeDesc type, XPathNavigator nav, object? c protected virtual void ProcessEvent(TypeDesc type, EventPseudoDesc @event, XPathNavigator nav, object? customData) { } - void ProcessSelectedProperties(XPathNavigator nav, TypeDesc type, object? customData) + private void ProcessSelectedProperties(XPathNavigator nav, TypeDesc type, object? customData) { foreach (XPathNavigator propertyNav in nav.SelectChildren(PropertyElementName, XmlNamespace)) { @@ -417,7 +417,7 @@ void ProcessSelectedProperties(XPathNavigator nav, TypeDesc type, object? custom protected virtual void ProcessProperty(TypeDesc type, XPathNavigator nav, object? customData) { string signature = GetSignature(nav); - if (!String.IsNullOrEmpty(signature)) + if (!string.IsNullOrEmpty(signature)) { PropertyPseudoDesc? property = GetProperty(type, signature); if (property is null) @@ -430,7 +430,7 @@ protected virtual void ProcessProperty(TypeDesc type, XPathNavigator nav, object } string name = GetAttribute(nav, NameAttributeName); - if (!String.IsNullOrEmpty(name)) + if (!string.IsNullOrEmpty(name)) { bool foundMatch = false; foreach (PropertyPseudoDesc property in type.GetPropertiesOnTypeHierarchy(p => p.Name == name)) @@ -524,7 +524,7 @@ protected void LogWarning(XPathNavigator position, DiagnosticId id, params strin } #endif - class CecilTypeNameFormatter : TypeNameFormatter + private sealed class CecilTypeNameFormatter : TypeNameFormatter { public static readonly CecilTypeNameFormatter Instance = new CecilTypeNameFormatter(); @@ -550,22 +550,22 @@ public override void AppendName(StringBuilder sb, PointerType type) public override void AppendName(StringBuilder sb, FunctionPointerType type) { - sb.Append(" "); + sb.Append(' '); AppendName(sb, type.Signature.ReturnType); sb.Append(" *"); - sb.Append("("); + sb.Append('('); for (int i = 0; i < type.Signature.Length; i++) { var parameter = type.Signature[i]; if (i > 0) - sb.Append(","); + sb.Append(','); AppendName(sb, parameter); } - sb.Append(")"); + sb.Append(')'); } public override void AppendName(StringBuilder sb, GenericParameterDesc type) @@ -596,7 +596,7 @@ protected override void AppendNameForInstantiatedType(StringBuilder sb, DefType } protected override void AppendNameForNamespaceType(StringBuilder sb, DefType type) { - if (!String.IsNullOrEmpty(type.Namespace)) + if (!string.IsNullOrEmpty(type.Namespace)) { sb.Append(type.Namespace); sb.Append('.'); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessXmlBase.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessXmlBase.cs index b00f56a0c2ce47..11fb8e1c0c4647 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessXmlBase.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessXmlBase.cs @@ -175,7 +175,7 @@ private void ProcessMethod(TypeDesc type) if (ShouldProcessElement()) { string signature = _reader.GetAttribute("signature"); - if (!String.IsNullOrEmpty(signature)) + if (!string.IsNullOrEmpty(signature)) { MethodDesc method = GetMethod(type, signature); if (method == null) @@ -188,7 +188,7 @@ private void ProcessMethod(TypeDesc type) } string methodName = _reader.GetAttribute("name"); - if (!String.IsNullOrEmpty(methodName)) + if (!string.IsNullOrEmpty(methodName)) { bool foundMatch = false; foreach (MethodDesc method in type.GetMethods()) @@ -217,7 +217,7 @@ private void ProcessField(TypeDesc type) if (ShouldProcessElement()) { string fieldName = _reader.GetAttribute("name"); - if (!String.IsNullOrEmpty(fieldName)) + if (!string.IsNullOrEmpty(fieldName)) { FieldDesc field = type.GetField(fieldName); @@ -245,7 +245,7 @@ protected virtual void ProcessResource(ModuleDesc module) { } - protected MethodDesc GetMethod(TypeDesc type, string signature) + protected static MethodDesc GetMethod(TypeDesc type, string signature) { foreach (MethodDesc meth in type.GetMethods()) if (signature == GetMethodSignature(meth, false)) @@ -312,7 +312,7 @@ private bool ShouldProcessElement() return bValue == featureSetting; } - class CecilTypeNameFormatter : TypeNameFormatter + private sealed class CecilTypeNameFormatter : TypeNameFormatter { public static readonly CecilTypeNameFormatter Instance = new CecilTypeNameFormatter(); @@ -338,22 +338,22 @@ public override void AppendName(StringBuilder sb, PointerType type) public override void AppendName(StringBuilder sb, FunctionPointerType type) { - sb.Append(" "); + sb.Append(' '); AppendName(sb, type.Signature.ReturnType); sb.Append(" *"); - sb.Append("("); + sb.Append('('); for (int i = 0; i < type.Signature.Length; i++) { var parameter = type.Signature[i]; if (i > 0) - sb.Append(","); + sb.Append(','); AppendName(sb, parameter); } - sb.Append(")"); + sb.Append(')'); } public override void AppendName(StringBuilder sb, GenericParameterDesc type) @@ -384,7 +384,7 @@ protected override void AppendNameForInstantiatedType(StringBuilder sb, DefType } protected override void AppendNameForNamespaceType(StringBuilder sb, DefType type) { - if (!String.IsNullOrEmpty(type.Namespace)) + if (!string.IsNullOrEmpty(type.Namespace)) { sb.Append(type.Namespace); sb.Append('.'); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/RootingHelpers.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/RootingHelpers.cs index 987e31fc03c271..cfe769b60e97c8 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/RootingHelpers.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/RootingHelpers.cs @@ -1,14 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Collections.Generic; - using Internal.TypeSystem; using ILCompiler.DependencyAnalysis; using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyList; -using Debug = System.Diagnostics.Debug; namespace ILCompiler { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/RootingServiceProvider.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/RootingServiceProvider.cs index 8b105d762dab8f..4beb7bf6204b6e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/RootingServiceProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/RootingServiceProvider.cs @@ -12,7 +12,7 @@ namespace ILCompiler { internal delegate void RootAdder(object o, string reason); - internal class RootingServiceProvider : IRootingServiceProvider + internal sealed class RootingServiceProvider : IRootingServiceProvider { private readonly NodeFactory _factory; private readonly RootAdder _rootAdder; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/RuntimeConfigurationRootProvider.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/RuntimeConfigurationRootProvider.cs index 9a3facb6eeee17..122067c0587103 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/RuntimeConfigurationRootProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/RuntimeConfigurationRootProvider.cs @@ -27,7 +27,7 @@ protected byte[] GetRuntimeOptionsBlob() { const int HeaderSize = 4; - ArrayBuilder options = new ArrayBuilder(); + ArrayBuilder options = default(ArrayBuilder); // Reserve space for the header options.ZeroExtend(HeaderSize); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/TextLogWriter.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/TextLogWriter.cs index 7d04b75796490b..7cda3de39f71df 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/TextLogWriter.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/TextLogWriter.cs @@ -1,7 +1,6 @@ // 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 ILCompiler.Logging; @@ -9,7 +8,7 @@ namespace ILCompiler { public class TextLogWriter : ILogWriter { - TextWriter _writer; + private TextWriter _writer; public TextLogWriter(TextWriter writer) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/TypePreinit.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/TypePreinit.cs index 15baf60300503e..5d292226fbd720 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/TypePreinit.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/TypePreinit.cs @@ -1426,7 +1426,7 @@ private static Value NewUninitializedLocationValue(TypeDesc locationType) } } - private bool TryHandleIntrinsicCall(MethodDesc method, Value[] parameters, out Value retVal) + private static bool TryHandleIntrinsicCall(MethodDesc method, Value[] parameters, out Value retVal) { retVal = default; @@ -1450,7 +1450,7 @@ private bool TryHandleIntrinsicCall(MethodDesc method, Value[] parameters, out V return false; } - private TypeDesc GetArgType(MethodDesc method, int index) + private static TypeDesc GetArgType(MethodDesc method, int index) { var sig = method.Signature; int offset = 0; @@ -1467,7 +1467,7 @@ private TypeDesc GetArgType(MethodDesc method, int index) return sig[index - offset]; } - class Stack : Stack + private sealed class Stack : Stack { private readonly TargetDetails _target; @@ -1767,7 +1767,7 @@ public virtual bool TryCreateByRef(out Value value) public abstract void WriteFieldData(ref ObjectDataBuilder builder, NodeFactory factory); - private T ThrowInvalidProgram() + private static T ThrowInvalidProgram() { ThrowHelper.ThrowInvalidProgramException(); return default; @@ -1788,7 +1788,7 @@ private abstract class BaseValueTypeValue : Value } // Also represents pointers and function pointer. - private class ValueTypeValue : BaseValueTypeValue, IAssignableValue + private sealed class ValueTypeValue : BaseValueTypeValue, IAssignableValue { public readonly byte[] InstanceBytes; @@ -1878,7 +1878,7 @@ private byte[] AsExactByteCount(int size) public static ValueTypeValue FromDouble(double value) => new ValueTypeValue(BitConverter.GetBytes(value)); } - private class RuntimeFieldHandleValue : BaseValueTypeValue, IInternalModelingOnlyValue + private sealed class RuntimeFieldHandleValue : BaseValueTypeValue, IInternalModelingOnlyValue { public FieldDesc Field { get; private set; } @@ -1905,7 +1905,7 @@ public override void WriteFieldData(ref ObjectDataBuilder builder, NodeFactory f } } - private class MethodPointerValue : BaseValueTypeValue, IInternalModelingOnlyValue + private sealed class MethodPointerValue : BaseValueTypeValue, IInternalModelingOnlyValue { public MethodDesc PointedToMethod { get; } @@ -1932,7 +1932,7 @@ public override void WriteFieldData(ref ObjectDataBuilder builder, NodeFactory f } } - private class ByRefValue : Value, IHasInstanceFields + private sealed class ByRefValue : Value, IHasInstanceFields { public readonly byte[] PointedToBytes; public readonly int PointedToOffset; @@ -2024,7 +2024,9 @@ public override ReferenceTypeValue ToForeignInstance(int baseInstructionCounter) this); } +#pragma warning disable CA1852 private class DelegateInstance : AllocatedReferenceTypeValue, ISerializableReference +#pragma warning restore CA1852 { private readonly MethodDesc _methodPointed; private readonly ReferenceTypeValue _firstParameter; @@ -2095,7 +2097,9 @@ public override void WriteFieldData(ref ObjectDataBuilder builder, NodeFactory f } } +#pragma warning disable CA1852 private class ArrayInstance : AllocatedReferenceTypeValue, ISerializableReference +#pragma warning restore CA1852 { private readonly int _elementCount; private readonly int _elementSize; @@ -2181,7 +2185,7 @@ public virtual void WriteContent(ref ObjectDataBuilder builder, ISymbolNode this } } - private class ForeignTypeInstance : AllocatedReferenceTypeValue + private sealed class ForeignTypeInstance : AllocatedReferenceTypeValue { public ReferenceTypeValue Data { get; } @@ -2206,7 +2210,7 @@ public override void WriteFieldData(ref ObjectDataBuilder builder, NodeFactory f public override ReferenceTypeValue ToForeignInstance(int baseInstructionCounter) => this; } - private class StringInstance : ReferenceTypeValue + private sealed class StringInstance : ReferenceTypeValue { private readonly string _value; @@ -2224,7 +2228,9 @@ public override void WriteFieldData(ref ObjectDataBuilder builder, NodeFactory f public override ReferenceTypeValue ToForeignInstance(int baseInstructionCounter) => this; } +#pragma warning disable CA1852 private class ObjectInstance : AllocatedReferenceTypeValue, IHasInstanceFields, ISerializableReference +#pragma warning restore CA1852 { private readonly byte[] _data; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UniversalGenericsRootProvider.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UniversalGenericsRootProvider.cs index 8788f375b65e5d..19494506f7be30 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UniversalGenericsRootProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UniversalGenericsRootProvider.cs @@ -11,7 +11,7 @@ namespace ILCompiler ///
public class UniversalGenericsRootProvider : ICompilationRootProvider { - TypeSystemContext _context; + private TypeSystemContext _context; public UniversalGenericsRootProvider(TypeSystemContext context) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UnixNodeMangler.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UnixNodeMangler.cs index 877f8da545d08e..242759b0c91484 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UnixNodeMangler.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UnixNodeMangler.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Internal.Text; using Internal.TypeSystem; using System.Diagnostics; using System.Globalization; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedInteropStubManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedInteropStubManager.cs index fb80ee36e2d7b8..822dfa2052740f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedInteropStubManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedInteropStubManager.cs @@ -4,14 +4,10 @@ using Internal.IL; using Internal.TypeSystem; using Internal.TypeSystem.Interop; - -using ILCompiler.Dataflow; using ILCompiler.DependencyAnalysis; -using ILLink.Shared; using Debug = System.Diagnostics.Debug; using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyList; -using System.Runtime.InteropServices; namespace ILCompiler { @@ -32,7 +28,7 @@ public override void AddDependenciesDueToMethodCodePresence(ref DependencyList d { if (method.HasInstantiation) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); AddMarshalAPIsGenericDependencies(ref dependencies, factory, method); } } @@ -44,7 +40,7 @@ public override void AddInterestingInteropConstructedTypeDependencies(ref Depend var delegateType = (MetadataType)type; if (delegateType.HasCustomAttribute("System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute")) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.DelegateMarshallingData(delegateType), "Delegate marshalling"); } } @@ -74,7 +70,7 @@ public override void AddMarshalAPIsGenericDependencies(ref DependencyList depend { foreach (TypeDesc type in method.Instantiation) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); if (type.IsDelegate) { dependencies.Add(factory.DelegateMarshallingData((DefType)type), "Delegate marshlling"); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedMetadataManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedMetadataManager.cs index 53b92c2eaaee31..b194f265944859 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedMetadataManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedMetadataManager.cs @@ -26,7 +26,6 @@ using EcmaModule = Internal.TypeSystem.Ecma.EcmaModule; using EcmaType = Internal.TypeSystem.Ecma.EcmaType; using FlowAnnotations = ILLink.Shared.TrimAnalysis.FlowAnnotations; -using MetadataExtensions = Internal.TypeSystem.Ecma.MetadataExtensions; namespace ILCompiler { @@ -211,13 +210,13 @@ protected override void ComputeMetadata(NodeFactory factory, protected override void GetMetadataDependenciesDueToReflectability(ref DependencyList dependencies, NodeFactory factory, MethodDesc method) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.MethodMetadata(method.GetTypicalMethodDefinition()), "Reflectable method"); } protected override void GetMetadataDependenciesDueToReflectability(ref DependencyList dependencies, NodeFactory factory, FieldDesc field) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.FieldMetadata(field.GetTypicalFieldDefinition()), "Reflectable field"); } @@ -230,8 +229,6 @@ internal override void GetDependenciesDueToModuleUse(ref DependencyList dependen } if (module is EcmaModule ecmaModule) { - PEMemoryBlock resourceDirectory = ecmaModule.PEReader.GetSectionData(ecmaModule.PEReader.PEHeaders.CorHeader.ResourcesDirectory.RelativeVirtualAddress); - foreach (var resourceHandle in ecmaModule.MetadataReader.ManifestResources) { ManifestResource resource = ecmaModule.MetadataReader.GetManifestResource(resourceHandle); @@ -287,7 +284,7 @@ protected override void GetMetadataDependenciesDueToReflectability(ref Dependenc { if (!method.Signature.IsStatic && method.IsSpecialName) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.CanonicalEntrypoint(method), "Anonymous type accessor"); } } @@ -335,7 +332,7 @@ protected override void GetMetadataDependenciesDueToReflectability(ref Dependenc if (fullyRoot) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); var rootProvider = new RootingServiceProvider(factory, dependencies.Add); foreach (TypeDesc t in mdType.Module.GetAllTypes()) { @@ -351,12 +348,12 @@ protected override void GetMetadataDependenciesDueToReflectability(ref Dependenc AddEventSourceSpecialTypeDependencies(ref dependencies, factory, mdType.GetNestedType("Tasks")); AddEventSourceSpecialTypeDependencies(ref dependencies, factory, mdType.GetNestedType("Opcodes")); - void AddEventSourceSpecialTypeDependencies(ref DependencyList dependencies, NodeFactory factory, MetadataType type) + static void AddEventSourceSpecialTypeDependencies(ref DependencyList dependencies, NodeFactory factory, MetadataType type) { if (type != null) { const string reason = "Event source"; - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.TypeMetadata(type), reason); foreach (FieldDesc field in type.GetFields()) { @@ -507,14 +504,14 @@ public override void GetDependenciesDueToLdToken(ref DependencyList dependencies { if (!IsReflectionBlocked(field)) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.ReflectableField(field), "LDTOKEN field"); } } public override void GetDependenciesDueToLdToken(ref DependencyList dependencies, NodeFactory factory, MethodDesc method) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); if (!IsReflectionBlocked(method)) dependencies.Add(factory.ReflectableMethod(method), "LDTOKEN method"); @@ -524,7 +521,7 @@ public override void GetDependenciesDueToDelegateCreation(ref DependencyList dep { if (!IsReflectionBlocked(target)) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.ReflectableMethod(target), "Target of a delegate"); } } @@ -646,7 +643,7 @@ public override void GetDependenciesDueToVirtualMethodReflectability(ref Depende // for the metadata manager. Metadata manager treats that node the same as a body. if (method.IsAbstract && GetMetadataCategory(method) != 0) { - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.ReflectableMethod(method), "Abstract reflectable method"); } } @@ -739,7 +736,7 @@ public override void GetDependenciesDueToAccess(ref DependencyList dependencies, } } - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.ReflectableField(fieldToReport), reason); } } @@ -983,7 +980,7 @@ private void AddDataflowDependency(ref DependencyList dependencies, NodeFactory if (CompilerGeneratedState.IsNestedFunctionOrStateMachineMember(methodILDefinition.OwningMethod)) return; - dependencies = dependencies ?? new DependencyList(); + dependencies ??= new DependencyList(); dependencies.Add(factory.DataflowAnalyzedMethod(methodILDefinition), reason); } @@ -1078,7 +1075,7 @@ public bool IsBlocked(MethodDesc methodDef) } } - private class FeatureSwitchHashtable : LockFreeReaderHashtable + private sealed class FeatureSwitchHashtable : LockFreeReaderHashtable { private readonly Dictionary _switchValues; @@ -1098,7 +1095,7 @@ protected override AssemblyFeatureInfo CreateValueFromKey(EcmaModule key) } } - private class AssemblyFeatureInfo + private sealed class AssemblyFeatureInfo { public EcmaModule Module { get; } @@ -1139,7 +1136,7 @@ public AssemblyFeatureInfo(EcmaModule module, IReadOnlyDictionary } } - private class LinkAttributesReader : ProcessXmlBase + private sealed class LinkAttributesReader : ProcessXmlBase { private readonly HashSet _removedAttributes; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UserDefinedTypeDescriptor.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UserDefinedTypeDescriptor.cs index 6dd4e08ff2e33b..68cae05dd66f30 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UserDefinedTypeDescriptor.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UserDefinedTypeDescriptor.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Reflection.Metadata; -using System.Reflection.Metadata.Ecma335; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; @@ -17,14 +16,14 @@ namespace ILCompiler { public class UserDefinedTypeDescriptor { - object _lock = new object(); - NodeFactory _nodeFactory; + private object _lock = new object(); + private NodeFactory _nodeFactory; - NodeFactory NodeFactory => _nodeFactory; + private NodeFactory NodeFactory => _nodeFactory; - bool Is64Bit => NodeFactory.Target.PointerSize == 8; + private bool Is64Bit => NodeFactory.Target.PointerSize == 8; - TargetAbi Abi => NodeFactory.Target.Abi; + private TargetAbi Abi => NodeFactory.Target.Abi; public UserDefinedTypeDescriptor(ITypesDebugInfoWriter objectWriter, NodeFactory nodeFactory) { @@ -66,7 +65,7 @@ public uint GetStateMachineThisVariableTypeIndex(TypeDesc type) InstanceSize = defType.InstanceByteCount.IsIndeterminate ? 0 : (ulong)defType.InstanceByteCount.AsInt, }; - var fieldsDescs = new ArrayBuilder(); + var fieldsDescs = default(ArrayBuilder); foreach (var fieldDesc in defType.GetFields()) { @@ -166,7 +165,7 @@ public uint GetThisTypeIndex(TypeDesc type) if (_thisTypes.TryGetValue(type, out typeIndex)) return typeIndex; - PointerTypeDescriptor descriptor = new PointerTypeDescriptor(); + PointerTypeDescriptor descriptor = default(PointerTypeDescriptor); // Note the use of GetTypeIndex here instead of GetVariableTypeIndex (We need the type exactly, not a reference to the type (as would happen for arrays/classes), and not a primitive value (as would happen for primitives)) descriptor.ElementType = GetTypeIndex(type, true); descriptor.Is64Bit = Is64Bit ? 1 : 0; @@ -189,7 +188,7 @@ public uint GetMethodTypeIndex(MethodDesc method) if (_methodIndices.TryGetValue(method, out typeIndex)) return typeIndex; - MemberFunctionTypeDescriptor descriptor = new MemberFunctionTypeDescriptor(); + MemberFunctionTypeDescriptor descriptor = default(MemberFunctionTypeDescriptor); MethodSignature signature = method.Signature; descriptor.ReturnType = GetVariableTypeIndex(DebuggerCanonicalize(signature.ReturnType)); @@ -230,7 +229,7 @@ public uint GetMethodFunctionIdTypeIndex(MethodDesc method) if (_methodIdIndices.TryGetValue(method, out typeIndex)) return typeIndex; - MemberFunctionIdTypeDescriptor descriptor = new MemberFunctionIdTypeDescriptor(); + MemberFunctionIdTypeDescriptor descriptor = default(MemberFunctionIdTypeDescriptor); descriptor.MemberFunction = GetMethodTypeIndex(method); descriptor.ParentClass = GetTypeIndex(method.OwningType, true); @@ -242,7 +241,7 @@ public uint GetMethodFunctionIdTypeIndex(MethodDesc method) } } - private TypeDesc DebuggerCanonicalize(TypeDesc type) + private static TypeDesc DebuggerCanonicalize(TypeDesc type) { if (type.IsCanonicalSubtype(CanonicalFormKind.Any)) return type.ConvertToCanonForm(CanonicalFormKind.Specific); @@ -252,7 +251,7 @@ private TypeDesc DebuggerCanonicalize(TypeDesc type) private uint GetVariableTypeIndex(TypeDesc type, bool needsCompleteIndex) { - uint variableTypeIndex = 0; + uint variableTypeIndex; if (type.IsPrimitive) { variableTypeIndex = GetPrimitiveTypeIndex(type); @@ -263,9 +262,8 @@ private uint GetVariableTypeIndex(TypeDesc type, bool needsCompleteIndex) if ((type.IsDefType && !type.IsValueType) || type.IsArray) { - // The type index of a variable/field of a reference type is wrapped + // The type index of a variable/field of a reference type is wrapped // in a pointer, as these fields are really pointer fields, and the data is on the heap - variableTypeIndex = 0; if (_knownReferenceWrappedTypes.TryGetValue(type, out variableTypeIndex)) { return variableTypeIndex; @@ -274,7 +272,7 @@ private uint GetVariableTypeIndex(TypeDesc type, bool needsCompleteIndex) { uint typeindex = GetTypeIndex(type, false); - PointerTypeDescriptor descriptor = new PointerTypeDescriptor(); + PointerTypeDescriptor descriptor = default(PointerTypeDescriptor); descriptor.ElementType = typeindex; descriptor.Is64Bit = Is64Bit ? 1 : 0; descriptor.IsConst = 0; @@ -315,7 +313,7 @@ private uint GetVariableTypeIndex(TypeDesc type, bool needsCompleteIndex) /// public uint GetTypeIndex(TypeDesc type, bool needsCompleteType) { - uint typeIndex = 0; + uint typeIndex; if (needsCompleteType ? _completeKnownTypes.TryGetValue(type, out typeIndex) : _knownTypes.TryGetValue(type, out typeIndex)) @@ -362,7 +360,7 @@ private uint GetPointerTypeIndex(TypeDesc pointeeType) if (_pointerTypes.TryGetValue(pointeeType, out typeIndex)) return typeIndex; - PointerTypeDescriptor descriptor = new PointerTypeDescriptor(); + PointerTypeDescriptor descriptor = default(PointerTypeDescriptor); descriptor.ElementType = GetVariableTypeIndex(pointeeType, false); descriptor.Is64Bit = Is64Bit ? 1 : 0; descriptor.IsConst = 0; @@ -384,7 +382,7 @@ private uint GetByRefTypeIndex(TypeDesc pointeeType) if (_byRefTypes.TryGetValue(pointeeType, out typeIndex)) return typeIndex; - PointerTypeDescriptor descriptor = new PointerTypeDescriptor(); + PointerTypeDescriptor descriptor = default(PointerTypeDescriptor); descriptor.ElementType = GetVariableTypeIndex(pointeeType, false); descriptor.Is64Bit = Is64Bit ? 1 : 0; descriptor.IsConst = 0; @@ -401,9 +399,9 @@ private uint GetByRefTypeIndex(TypeDesc pointeeType) private uint GetEnumTypeIndex(TypeDesc type) { - System.Diagnostics.Debug.Assert(type.IsEnum, "GetEnumTypeIndex was called with wrong type"); + Debug.Assert(type.IsEnum, "GetEnumTypeIndex was called with wrong type"); DefType defType = type as DefType; - System.Diagnostics.Debug.Assert(defType != null, "GetEnumTypeIndex was called with non def type"); + Debug.Assert(defType != null, "GetEnumTypeIndex was called with non def type"); List fieldsDescriptors = new List(); foreach (var field in defType.GetFields()) { @@ -433,7 +431,7 @@ private uint GetEnumTypeIndex(TypeDesc type) private uint GetArrayTypeIndex(TypeDesc type) { - System.Diagnostics.Debug.Assert(type.IsArray, "GetArrayTypeIndex was called with wrong type"); + Debug.Assert(type.IsArray, "GetArrayTypeIndex was called with wrong type"); ArrayType arrayType = (ArrayType)type; uint elementSize = (uint)type.Context.Target.PointerSize; @@ -462,7 +460,7 @@ private uint GetArrayTypeIndex(TypeDesc type) return typeIndex; } - private ulong GetEnumRecordValue(FieldDesc field) + private static ulong GetEnumRecordValue(FieldDesc field) { var ecmaField = field as EcmaField; if (ecmaField != null) @@ -478,7 +476,7 @@ private ulong GetEnumRecordValue(FieldDesc field) return 0; } - private ulong HandleConstant(EcmaModule module, ConstantHandle constantHandle) + private static ulong HandleConstant(EcmaModule module, ConstantHandle constantHandle) { MetadataReader reader = module.MetadataReader; Constant constant = reader.GetConstant(constantHandle); @@ -502,17 +500,17 @@ private ulong HandleConstant(EcmaModule module, ConstantHandle constantHandle) case ConstantTypeCode.UInt64: return (ulong)blob.ReadUInt64(); } - System.Diagnostics.Debug.Assert(false); + Debug.Assert(false); return 0; } - bool ShouldUseCanonicalTypeRecord(TypeDesc type) + private bool ShouldUseCanonicalTypeRecord(TypeDesc type) { // TODO: check the type's generic complexity return type.GetGenericDepth() > NodeFactory.TypeSystemContext.GenericsConfig.MaxGenericDepthOfDebugRecord; } - TypeDesc GetDebugType(TypeDesc type) + private TypeDesc GetDebugType(TypeDesc type) { TypeDesc typeGenericComplexityInfo = type; @@ -522,7 +520,7 @@ TypeDesc GetDebugType(TypeDesc type) } // Types that have some canonical subtypes types should always be represented in normalized canonical form to the binder. - // Also, to avoid infinite generic recursion issues, attempt to use canonical form for fields with high generic complexity. + // Also, to avoid infinite generic recursion issues, attempt to use canonical form for fields with high generic complexity. if (type.IsCanonicalSubtype(CanonicalFormKind.Specific) || (typeGenericComplexityInfo is DefType defType) && ShouldUseCanonicalTypeRecord(defType)) { type = type.ConvertToCanonForm(CanonicalFormKind.Specific); @@ -543,7 +541,7 @@ TypeDesc GetDebugType(TypeDesc type) return type; } - TypeDesc GetFieldDebugType(FieldDesc field) + private TypeDesc GetFieldDebugType(FieldDesc field) { return GetDebugType(field.FieldType); } @@ -552,7 +550,7 @@ private uint GetClassTypeIndex(TypeDesc type, bool needsCompleteType) { TypeDesc debugType = GetDebugType(type); DefType defType = debugType as DefType; - System.Diagnostics.Debug.Assert(defType != null, "GetClassTypeIndex was called with non def type"); + Debug.Assert(defType != null, "GetClassTypeIndex was called with non def type"); ClassTypeDescriptor classTypeDescriptor = new ClassTypeDescriptor { IsStruct = type.IsValueType ? 1 : 0, @@ -795,7 +793,7 @@ private void InsertStaticFieldRegionMember(List fieldDescs, } else if (staticDataInObject)// This means that access to this static region is done via indirection { - PointerTypeDescriptor pointerTypeDescriptor = new PointerTypeDescriptor(); + PointerTypeDescriptor pointerTypeDescriptor = default(PointerTypeDescriptor); pointerTypeDescriptor.Is64Bit = Is64Bit ? 1 : 0; pointerTypeDescriptor.IsConst = 0; pointerTypeDescriptor.IsReference = 0; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/VectorOfTFieldLayoutAlgorithm.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/VectorOfTFieldLayoutAlgorithm.cs index 9b608cab136ddb..e0e175c0dcefea 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/VectorOfTFieldLayoutAlgorithm.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/VectorOfTFieldLayoutAlgorithm.cs @@ -52,7 +52,7 @@ public override ComputedInstanceFieldLayout ComputeInstanceLayout(DefType defTyp }; } - public unsafe override ComputedStaticFieldLayout ComputeStaticFieldLayout(DefType defType, StaticLayoutKind layoutKind) + public override unsafe ComputedStaticFieldLayout ComputeStaticFieldLayout(DefType defType, StaticLayoutKind layoutKind) { return _fallbackAlgorithm.ComputeStaticFieldLayout(defType, layoutKind); } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/VirtualMethodCallHelper.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/VirtualMethodCallHelper.cs index 2261d59239d0fc..a9de1fce5e3a52 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/VirtualMethodCallHelper.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/VirtualMethodCallHelper.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Generic; using System.Diagnostics; using Internal.TypeSystem; @@ -146,7 +145,7 @@ private static int GetNumberOfBaseSlots(NodeFactory factory, TypeDesc owningType // class Derived : Middle { } // -> Template is Derived<__UniversalCanon> and needs a dictionary slot // // -> Basetype tempalte is Middle<__UniversalCanon, MyStruct>. It's a partial // Universal canonical type, so we need to fully canonicalize it. - // + // // class Middle : Base { } // -> Template is Middle<__UniversalCanon, __UniversalCanon> and needs a dictionary slot // // -> Basetype template is Base<__UniversalCanon> // @@ -193,7 +192,7 @@ public static int GetGenericDictionarySlot(NodeFactory factory, TypeDesc type) public static bool HasGenericDictionarySlot(this TypeDesc type) { // Dictionary slots on generic interfaces are necessary to support static methods on interfaces - // The reason behind making this unconditional is simplicity, and keeping method slot indices for methods on IFoo + // The reason behind making this unconditional is simplicity, and keeping method slot indices for methods on IFoo // and IFoo identical. That won't change. if (type.IsInterface) return type.HasInstantiation; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/WindowsNodeMangler.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/WindowsNodeMangler.cs index 3cbcd19ca39888..ee4117679432fc 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/WindowsNodeMangler.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/WindowsNodeMangler.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using Internal.Text; using Internal.TypeSystem; using System.Diagnostics; @@ -9,7 +8,7 @@ namespace ILCompiler { // // The naming format of these names is known to the debugger - // + // public class WindowsNodeMangler : NodeMangler { public const string NonGCStaticMemberName = "__NONGCSTATICS"; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/XmlObjectDumper.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/XmlObjectDumper.cs index b1fa747348f296..2320aa663617a5 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/XmlObjectDumper.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/XmlObjectDumper.cs @@ -70,7 +70,7 @@ protected override void DumpObjectNode(NameMangler mangler, ObjectNode node, Obj private string HashData(byte[] data) { - return BitConverter.ToString(_sha256.ComputeHash(data)).Replace("-", "").ToLower(); + return BitConverter.ToString(_sha256.ComputeHash(data)).Replace("-", "").ToLowerInvariant(); } internal override void End() diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs index 9f9c877fbed5db..cb55f2e02feafa 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem; using Internal.ReadyToRunConstants; @@ -16,7 +14,7 @@ namespace Internal.IL { // Implements an IL scanner that scans method bodies to be compiled by the code generation // backend before the actual compilation happens to gain insights into the code. - partial class ILImporter + internal partial class ILImporter { private readonly MethodIL _methodIL; private readonly MethodIL _canonMethodIL; @@ -32,7 +30,7 @@ partial class ILImporter private readonly byte[] _ilBytes; - private class BasicBlock + private sealed class BasicBlock { // Common fields public enum ImportState : byte @@ -57,7 +55,7 @@ public enum ImportState : byte private int _currentInstructionOffset; private int _previousInstructionOffset; - private class ExceptionRegion + private sealed class ExceptionRegion { public ILExceptionRegion ILRegion; } @@ -181,8 +179,8 @@ private ISymbolNode GetHelperEntrypoint(ReadyToRunHelper helper) return _compilation.GetHelperEntrypoint(helper); } - private void MarkInstructionBoundary() { } - private void EndImportingBasicBlock(BasicBlock basicBlock) { } + private static void MarkInstructionBoundary() { } + private static void EndImportingBasicBlock(BasicBlock basicBlock) { } private void StartImportingBasicBlock(BasicBlock basicBlock) { @@ -983,12 +981,12 @@ private void ImportLdToken(int token) } } - private void ImportRefAnyType() + private static void ImportRefAnyType() { // TODO } - private void ImportArgList() + private static void ImportArgList() { } @@ -1228,27 +1226,27 @@ private int ReadILTokenAt(int ilOffset) + (_ilBytes[ilOffset + 3] << 24)); } - private void ReportInvalidBranchTarget(int targetOffset) + private static void ReportInvalidBranchTarget(int targetOffset) { ThrowHelper.ThrowInvalidProgramException(); } - private void ReportFallthroughAtEndOfMethod() + private static void ReportFallthroughAtEndOfMethod() { ThrowHelper.ThrowInvalidProgramException(); } - private void ReportMethodEndInsideInstruction() + private static void ReportMethodEndInsideInstruction() { ThrowHelper.ThrowInvalidProgramException(); } - private void ReportInvalidInstruction(ILOpcode opcode) + private static void ReportInvalidInstruction(ILOpcode opcode) { ThrowHelper.ThrowInvalidProgramException(); } - private bool IsRuntimeHelpersInitializeArrayOrCreateSpan(MethodDesc method) + private static bool IsRuntimeHelpersInitializeArrayOrCreateSpan(MethodDesc method) { if (method.IsIntrinsic) { @@ -1266,7 +1264,7 @@ private bool IsRuntimeHelpersInitializeArrayOrCreateSpan(MethodDesc method) return false; } - private bool IsTypeGetTypeFromHandle(MethodDesc method) + private static bool IsTypeGetTypeFromHandle(MethodDesc method) { if (method.IsIntrinsic && method.Name == "GetTypeFromHandle") { @@ -1280,7 +1278,7 @@ private bool IsTypeGetTypeFromHandle(MethodDesc method) return false; } - private bool IsTypeEquals(MethodDesc method) + private static bool IsTypeEquals(MethodDesc method) { if (method.IsIntrinsic && method.Name == "op_Equality") { @@ -1294,7 +1292,7 @@ private bool IsTypeEquals(MethodDesc method) return false; } - private bool IsActivatorDefaultConstructorOf(MethodDesc method) + private static bool IsActivatorDefaultConstructorOf(MethodDesc method) { if (method.IsIntrinsic && method.Name == "DefaultConstructorOf" && method.Instantiation.Length == 1) { @@ -1308,7 +1306,7 @@ private bool IsActivatorDefaultConstructorOf(MethodDesc method) return false; } - private bool IsActivatorAllocatorOf(MethodDesc method) + private static bool IsActivatorAllocatorOf(MethodDesc method) { if (method.IsIntrinsic && method.Name == "AllocatorOf" && method.Instantiation.Length == 1) { @@ -1322,7 +1320,7 @@ private bool IsActivatorAllocatorOf(MethodDesc method) return false; } - private bool IsEETypePtrOf(MethodDesc method) + private static bool IsEETypePtrOf(MethodDesc method) { if (method.IsIntrinsic && (method.Name == "EETypePtrOf" || method.Name == "Of") && method.Instantiation.Length == 1) { @@ -1342,40 +1340,40 @@ private TypeDesc GetWellKnownType(WellKnownType wellKnownType) return _compilation.TypeSystemContext.GetWellKnownType(wellKnownType); } - private void ImportNop() { } - private void ImportBreak() { } - private void ImportLoadVar(int index, bool argument) { } - private void ImportStoreVar(int index, bool argument) { } - private void ImportAddressOfVar(int index, bool argument) { } - private void ImportDup() { } - private void ImportPop() { } - private void ImportLoadNull() { } - private void ImportReturn() { } - private void ImportLoadInt(long value, StackValueKind kind) { } - private void ImportLoadFloat(double value) { } - private void ImportLoadIndirect(int token) { } - private void ImportLoadIndirect(TypeDesc type) { } - private void ImportStoreIndirect(int token) { } - private void ImportStoreIndirect(TypeDesc type) { } - private void ImportShiftOperation(ILOpcode opcode) { } - private void ImportCompareOperation(ILOpcode opcode) { } - private void ImportConvert(WellKnownType wellKnownType, bool checkOverflow, bool unsigned) { } - private void ImportUnaryOperation(ILOpcode opCode) { } - private void ImportCpOpj(int token) { } - private void ImportCkFinite() { } - private void ImportLocalAlloc() { } - private void ImportEndFilter() { } - private void ImportCpBlk() { } - private void ImportInitBlk() { } - private void ImportRethrow() { } - private void ImportSizeOf(int token) { } - private void ImportUnalignedPrefix(byte alignment) { } - private void ImportVolatilePrefix() { } - private void ImportTailPrefix() { } - private void ImportNoPrefix(byte mask) { } - private void ImportThrow() { } - private void ImportInitObj(int token) { } - private void ImportLoadLength() { } - private void ImportEndFinally() { } + private static void ImportNop() { } + private static void ImportBreak() { } + private static void ImportLoadVar(int index, bool argument) { } + private static void ImportStoreVar(int index, bool argument) { } + private static void ImportAddressOfVar(int index, bool argument) { } + private static void ImportDup() { } + private static void ImportPop() { } + private static void ImportLoadNull() { } + private static void ImportReturn() { } + private static void ImportLoadInt(long value, StackValueKind kind) { } + private static void ImportLoadFloat(double value) { } + private static void ImportLoadIndirect(int token) { } + private static void ImportLoadIndirect(TypeDesc type) { } + private static void ImportStoreIndirect(int token) { } + private static void ImportStoreIndirect(TypeDesc type) { } + private static void ImportShiftOperation(ILOpcode opcode) { } + private static void ImportCompareOperation(ILOpcode opcode) { } + private static void ImportConvert(WellKnownType wellKnownType, bool checkOverflow, bool unsigned) { } + private static void ImportUnaryOperation(ILOpcode opCode) { } + private static void ImportCpOpj(int token) { } + private static void ImportCkFinite() { } + private static void ImportLocalAlloc() { } + private static void ImportEndFilter() { } + private static void ImportCpBlk() { } + private static void ImportInitBlk() { } + private static void ImportRethrow() { } + private static void ImportSizeOf(int token) { } + private static void ImportUnalignedPrefix(byte alignment) { } + private static void ImportVolatilePrefix() { } + private static void ImportTailPrefix() { } + private static void ImportNoPrefix(byte mask) { } + private static void ImportThrow() { } + private static void ImportInitObj(int token) { } + private static void ImportLoadLength() { } + private static void ImportEndFinally() { } } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/PInvokeILProvider.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/PInvokeILProvider.cs index 93fb4cc376c07e..945284e43abc53 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/PInvokeILProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/PInvokeILProvider.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem; using Internal.IL.Stubs; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/AppContextInitializerMethod.Sorting.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/AppContextInitializerMethod.Sorting.cs index 8222352a9159c3..27d6287aef7e73 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/AppContextInitializerMethod.Sorting.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/AppContextInitializerMethod.Sorting.cs @@ -7,7 +7,7 @@ namespace Internal.IL.Stubs.StartupCode { - partial class AppContextInitializerMethod + public partial class AppContextInitializerMethod { protected override int ClassCode => 15749517; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/AppContextInitializerMethod.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/AppContextInitializerMethod.cs index ed40a5f6fcc75c..92d9eccdaee950 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/AppContextInitializerMethod.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/AppContextInitializerMethod.cs @@ -87,12 +87,9 @@ public override MethodSignature Signature { get { - if (_signature == null) - { - _signature = new MethodSignature(MethodSignatureFlags.Static, 0, + _signature ??= new MethodSignature(MethodSignatureFlags.Static, 0, Context.GetWellKnownType(WellKnownType.Void), TypeDesc.EmptyTypes); - } return _signature; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/NativeLibraryStartupMethod.Sorting.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/NativeLibraryStartupMethod.Sorting.cs index be6be0bb39eb7b..05d929146c3ac2 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/NativeLibraryStartupMethod.Sorting.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/NativeLibraryStartupMethod.Sorting.cs @@ -1,16 +1,13 @@ // 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 Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace Internal.IL.Stubs.StartupCode { - partial class NativeLibraryStartupMethod + public partial class NativeLibraryStartupMethod { protected override int ClassCode => -304225482; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/NativeLibraryStartupMethod.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/NativeLibraryStartupMethod.cs index 4240af2427d154..160a06bb441a2d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/NativeLibraryStartupMethod.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/NativeLibraryStartupMethod.cs @@ -1,7 +1,6 @@ // 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 Internal.TypeSystem; @@ -87,12 +86,9 @@ public override MethodSignature Signature { get { - if (_signature == null) - { - _signature = new MethodSignature(MethodSignatureFlags.Static | MethodSignatureFlags.UnmanagedCallingConvention, 0, + _signature ??= new MethodSignature(MethodSignatureFlags.Static | MethodSignatureFlags.UnmanagedCallingConvention, 0, Context.GetWellKnownType(WellKnownType.Void), - new TypeDesc[0]); - } + System.Array.Empty()); return _signature; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/StartupCodeMainMethod.Sorting.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/StartupCodeMainMethod.Sorting.cs index d33a2de6a007f9..59d582451c80ae 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/StartupCodeMainMethod.Sorting.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/StartupCodeMainMethod.Sorting.cs @@ -1,17 +1,12 @@ // 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 Internal.TypeSystem; - -using AssemblyName = System.Reflection.AssemblyName; using Debug = System.Diagnostics.Debug; namespace Internal.IL.Stubs.StartupCode { - partial class StartupCodeMainMethod + public partial class StartupCodeMainMethod { protected override int ClassCode => -304225481; @@ -22,7 +17,7 @@ protected override int CompareToImpl(MethodDesc other, TypeSystemComparer compar return 0; } - partial class MainMethodWrapper + private partial class MainMethodWrapper { protected override int ClassCode => -215672259; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/StartupCodeMainMethod.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/StartupCodeMainMethod.cs index 1741ffdd61dd7c..7d197f85e08d52 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/StartupCodeMainMethod.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/Stubs/StartupCode/StartupCodeMainMethod.cs @@ -5,8 +5,6 @@ using System.Collections.Generic; using Internal.TypeSystem; - -using AssemblyName = System.Reflection.AssemblyName; using Debug = System.Diagnostics.Debug; namespace Internal.IL.Stubs.StartupCode @@ -175,14 +173,11 @@ public override MethodSignature Signature { get { - if (_signature == null) - { - _signature = new MethodSignature(MethodSignatureFlags.Static | MethodSignatureFlags.UnmanagedCallingConvention, 0, + _signature ??= new MethodSignature(MethodSignatureFlags.Static | MethodSignatureFlags.UnmanagedCallingConvention, 0, Context.GetWellKnownType(WellKnownType.Int32), new TypeDesc[2] { Context.GetWellKnownType(WellKnownType.Int32), Context.GetWellKnownType(WellKnownType.IntPtr) }); - } return _signature; } @@ -204,7 +199,7 @@ public override bool IsUnmanagedCallersOnly /// environment without it being fully initialized. (In particular, the unhandled exception experience /// won't be initialized, making this difficult to diagnose.) /// - private partial class MainMethodWrapper : ILStubMethod + private sealed partial class MainMethodWrapper : ILStubMethod { public MainMethodWrapper(TypeDesc owningType, MethodDesc mainMethod) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj index 214570667ca971..6d4dc52700414a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj @@ -16,6 +16,7 @@ Debug;Release;Checked $(NoWarn);CS8524 + true diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/ComputedStaticDependencyNode.cs b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/ComputedStaticDependencyNode.cs index 224f4182b5b68c..8e043a74a3916f 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/ComputedStaticDependencyNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/ComputedStaticDependencyNode.cs @@ -3,9 +3,6 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Diagnostics; namespace ILCompiler.DependencyAnalysisFramework diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyAnalyzer.cs b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyAnalyzer.cs index d81c5e5c66a725..78d4a640245580 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyAnalyzer.cs +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyAnalyzer.cs @@ -24,9 +24,11 @@ namespace ILCompiler.DependencyAnalysisFramework /// public sealed class DependencyAnalyzer : DependencyAnalyzerBase where MarkStrategy : struct, IDependencyAnalysisMarkStrategy { - private MarkStrategy _marker = new MarkStrategy(); +#pragma warning disable SA1129 // Do not use default value type constructor + private readonly MarkStrategy _marker = new MarkStrategy(); +#pragma warning restore SA1129 // Do not use default value type constructor private DependencyContextType _dependencyContext; - private IComparer> _resultSorter = null; + private IComparer> _resultSorter; private RandomInsertStack> _markStack; private List> _markedNodes = new List>(); @@ -35,12 +37,12 @@ public sealed class DependencyAnalyzer : De private Dictionary>> _deferredStaticDependencies = new Dictionary>>(); private List> _dynamicDependencyInterestingList = new List>(); private List _markedNodesWithDynamicDependencies = new List(); - private bool _newDynamicDependenciesMayHaveAppeared = false; + private bool _newDynamicDependenciesMayHaveAppeared; private Dictionary, HashSet.CombinedDependencyListEntry>> _conditional_dependency_store = new Dictionary, HashSet.CombinedDependencyListEntry>>(); - private bool _markingCompleted = false; + private bool _markingCompleted; - private class RandomInsertStack + private sealed class RandomInsertStack { private List _nodes = new List(); private readonly Random _randomizer; @@ -115,7 +117,7 @@ public DependencyAnalyzer(DependencyContextType dependencyContext, IComparer /// Add a root node /// - public override sealed void AddRoot(DependencyNodeCore rootNode, string reason) + public sealed override void AddRoot(DependencyNodeCore rootNode, string reason) { if (AddToMarkStack(rootNode, reason, null, null)) { @@ -123,7 +125,7 @@ public override sealed void AddRoot(DependencyNodeCore ro } } - public override sealed ImmutableArray> MarkedNodeList + public sealed override ImmutableArray> MarkedNodeList { get { @@ -136,11 +138,11 @@ public override sealed ImmutableArray> } } - public override sealed event Action> NewMarkedNode; + public sealed override event Action> NewMarkedNode; - public override sealed event Action>> ComputeDependencyRoutine; + public sealed override event Action>> ComputeDependencyRoutine; - public override sealed event Action ComputingDependencyPhaseChange; + public sealed override event Action ComputingDependencyPhaseChange; private IEnumerable> MarkedNodesEnumerable() { @@ -150,7 +152,7 @@ private IEnumerable> MarkedNodesEnumer return _markedNodes; } - public override sealed void VisitLogNodes(IDependencyAnalyzerLogNodeVisitor logNodeVisitor) + public sealed override void VisitLogNodes(IDependencyAnalyzerLogNodeVisitor logNodeVisitor) { foreach (DependencyNodeCore node in MarkedNodesEnumerable()) { @@ -159,7 +161,7 @@ public override sealed void VisitLogNodes(IDependencyAnalyzerLogNodeVisitor logEdgeVisitor) + public sealed override void VisitLogEdges(IDependencyAnalyzerLogEdgeVisitor logEdgeVisitor) { _marker.VisitLogEdges(MarkedNodesEnumerable(), logEdgeVisitor); } @@ -171,8 +173,7 @@ public override sealed void VisitLogEdges(IDependencyAnalyzerLogEdgeVisitorList of nodes which must have static dependencies computed private void ComputeDependencies(List> deferredStaticDependencies) { - if (ComputeDependencyRoutine != null) - ComputeDependencyRoutine(deferredStaticDependencies); + ComputeDependencyRoutine?.Invoke(deferredStaticDependencies); } // Internal details @@ -197,7 +198,7 @@ private void GetStaticDependenciesImpl(DependencyNodeCore } else { - HashSet.CombinedDependencyListEntry> storedDependencySet = null; + HashSet.CombinedDependencyListEntry> storedDependencySet; if (!_conditional_dependency_store.TryGetValue(dependency.OtherReasonNode, out storedDependencySet)) { storedDependencySet = new HashSet.CombinedDependencyListEntry>(); @@ -212,7 +213,7 @@ private void GetStaticDependenciesImpl(DependencyNodeCore } } - int _currentDependencyPhase = 0; + private int _currentDependencyPhase; private void GetStaticDependencies(DependencyNodeCore node) { @@ -264,7 +265,7 @@ private void ProcessMarkStack() // If this new node satisfies any stored conditional dependencies, // add them to the mark stack - HashSet.CombinedDependencyListEntry> storedDependencySet = null; + HashSet.CombinedDependencyListEntry> storedDependencySet; if (_conditional_dependency_store.TryGetValue(currentNode, out storedDependencySet)) { foreach (DependencyNodeCore.CombinedDependencyListEntry newlySatisfiedDependency in storedDependencySet) @@ -336,8 +337,7 @@ public override void ComputeMarkedNodes() _currentDependencyPhase++; // 3. Notify that new dependency phase has been entered - if (ComputingDependencyPhaseChange != null) - ComputingDependencyPhaseChange(_currentDependencyPhase); + ComputingDependencyPhaseChange?.Invoke(_currentDependencyPhase); } } while ((_markStack.Count != 0) || (_deferredStaticDependencies.Count != 0)); @@ -362,8 +362,7 @@ private bool AddToMarkStack(DependencyNodeCore node, stri node.CallOnMarked(_dependencyContext); - if (NewMarkedNode != null) - NewMarkedNode(node); + NewMarkedNode?.Invoke(node); return true; } diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyAnalyzerBase.cs b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyAnalyzerBase.cs index d4ee7616c31839..38d3e7c7023586 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyAnalyzerBase.cs +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyAnalyzerBase.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.IO; namespace ILCompiler.DependencyAnalysisFramework { @@ -14,12 +13,12 @@ namespace ILCompiler.DependencyAnalysisFramework /// so that if MarkedNodeList is called, it can produce the complete graph. For the case /// where nodes have deferred computation the ComputeDependencyRoutine even will be triggered /// to fill in data. - /// - /// The Log visitor logic can be called at any time, and should log the current set of marked + /// + /// The Log visitor logic can be called at any time, and should log the current set of marked /// nodes and edges in the analysis. (Notably, if its called before MarkedNodeList is evaluated /// it will contain only roots, if its called during, the edges/nodes may be incomplete, and /// if called after MarkedNodeList is computed it will be a complete graph. - /// + /// /// /// public abstract class DependencyAnalyzerBase diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyNode.cs b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyNode.cs index fdee41a043e8d1..d8913b8022c48d 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyNode.cs @@ -1,7 +1,6 @@ // 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; namespace ILCompiler.DependencyAnalysisFramework @@ -36,7 +35,7 @@ public bool Marked public sealed override bool Equals(object obj) { - return Object.ReferenceEquals(this, obj); + return ReferenceEquals(this, obj); } public sealed override int GetHashCode() diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyNodeCore.cs b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyNodeCore.cs index 3ef331e3698c48..3f50135eeb868a 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyNodeCore.cs +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DependencyNodeCore.cs @@ -3,9 +3,6 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace ILCompiler.DependencyAnalysisFramework { @@ -98,9 +95,9 @@ public override int GetHashCode() public bool Equals(CombinedDependencyListEntry other) { - return Object.ReferenceEquals(Node, other.Node) - && Object.ReferenceEquals(OtherReasonNode, other.OtherReasonNode) - && Object.Equals(Reason, other.Reason); + return ReferenceEquals(Node, other.Node) + && ReferenceEquals(OtherReasonNode, other.OtherReasonNode) + && Equals(Reason, other.Reason); } } @@ -124,7 +121,7 @@ public abstract bool StaticDependenciesAreComputed get; } - public virtual int DependencyPhaseForDeferredStaticComputation { get; } = 0; + public virtual int DependencyPhaseForDeferredStaticComputation { get; } public abstract IEnumerable GetStaticDependencies(DependencyContextType context); diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DgmlWriter.cs b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DgmlWriter.cs index a1c1dbe57d5489..a6018ed51056bc 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DgmlWriter.cs +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/DgmlWriter.cs @@ -17,10 +17,10 @@ public static void WriteDependencyGraphToStream(Stream st } } - internal class DgmlWriter : IDisposable, IDependencyAnalyzerLogEdgeVisitor, IDependencyAnalyzerLogNodeVisitor + internal sealed class DgmlWriter : IDisposable, IDependencyAnalyzerLogEdgeVisitor, IDependencyAnalyzerLogNodeVisitor { private XmlWriter _xmlWrite; - private bool _done = false; + private bool _done; private DependencyContextType _context; public DgmlWriter(XmlWriter xmlWrite, DependencyContextType context) @@ -101,7 +101,7 @@ void IDisposable.Dispose() } private Dictionary _nodeMappings = new Dictionary(); - private int _nodeNextId = 0; + private int _nodeNextId; private void AddNode(DependencyNodeCore node) { diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/EventSourceLogStrategy.cs b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/EventSourceLogStrategy.cs index e7615ad545fbfa..a5f70a0fa0bcf2 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/EventSourceLogStrategy.cs +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/EventSourceLogStrategy.cs @@ -1,13 +1,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; using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Threading; using System.Diagnostics.Tracing; using System.Runtime.InteropServices; @@ -15,18 +10,18 @@ namespace ILCompiler.DependencyAnalysisFramework { [EventSource(Name = "Microsoft-ILCompiler-DependencyGraph")] - class GraphEventSource : EventSource + internal sealed class GraphEventSource : EventSource { - public class Keywords + public static class Keywords { public const EventKeywords Graph = (EventKeywords)1; } - // Notice that the bodies of the events follow a pattern: WriteEvent(ID, ) where + // Notice that the bodies of the events follow a pattern: WriteEvent(ID, ) where // ID is a unique ID starting at 1 and incrementing for each new event method. and - // is every argument for the method. + // is every argument for the method. // WriteEvent then takes care of all the details of actually writing out the values complete - // with the name of the event (method name) as well as the names and types of all the parameters. + // with the name of the event (method name) as well as the names and types of all the parameters. [Event(1, Keywords = Keywords.Graph, Level = EventLevel.Informational)] public void Graph(int id, string name) { WriteEvent(1, id, name); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", @@ -42,13 +37,13 @@ public class Keywords [Event(4, Keywords = Keywords.Graph, Level = EventLevel.Informational)] public void ConditionalEdge(int id, int dependentIndex1, int dependentIndex2, int dependencyIndex, string reason) { WriteEvent(4, id, dependentIndex1, dependentIndex2, dependencyIndex, reason); } - // Typically you only create one EventSource and use it throughout your program. Thus a static field makes sense. + // Typically you only create one EventSource and use it throughout your program. Thus a static field makes sense. public static GraphEventSource Log = new GraphEventSource(); } public struct EventSourceLogStrategy : IDependencyAnalysisMarkStrategy { - private static int s_GraphIds = 0; + private static int s_GraphIds; private int GraphId; private int RootIndex; @@ -59,7 +54,7 @@ public static bool IsEventSourceEnabled { get { - return + return #if !ALWAYS_SUPPORT_EVENTSOURCE_LOG RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && // Processing these event source events is only implemented on Windows #endif diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/FirstMarkLogStrategy.cs b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/FirstMarkLogStrategy.cs index 3d1c439dd40106..655fb43a35c1cf 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/FirstMarkLogStrategy.cs +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/FirstMarkLogStrategy.cs @@ -3,18 +3,13 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Xml; -using System.IO; using System.Diagnostics; namespace ILCompiler.DependencyAnalysisFramework { public struct FirstMarkLogStrategy : IDependencyAnalysisMarkStrategy { - private class MarkData + private sealed class MarkData { public MarkData(string reason, DependencyNodeCore reason1, DependencyNodeCore reason2) { @@ -53,8 +48,7 @@ bool IDependencyAnalysisMarkStrategy.MarkNode( if ((reasonNode == null) && (reasonNode2 == null)) { Debug.Assert(reason != null); - if (_reasonStringOnlyNodes == null) - _reasonStringOnlyNodes = new HashSet(); + _reasonStringOnlyNodes ??= new HashSet(); _reasonStringOnlyNodes.Add(reason); } diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/FullGraphLogStrategy.cs b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/FullGraphLogStrategy.cs index 421ee4fd314b34..4847782fd3f78f 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/FullGraphLogStrategy.cs +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/FullGraphLogStrategy.cs @@ -3,11 +3,6 @@ using System; using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Xml; using System.Diagnostics; namespace ILCompiler.DependencyAnalysisFramework @@ -124,8 +119,7 @@ bool IDependencyAnalysisMarkStrategy.MarkNode( if ((reasonNode == null) && (reasonNode2 == null)) { Debug.Assert(reason != null); - if (_reasonStringOnlyNodes == null) - _reasonStringOnlyNodes = new HashSet(); + _reasonStringOnlyNodes ??= new HashSet(); _reasonStringOnlyNodes.Add(reason); } diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyAnalysisMarkStrategy.cs b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyAnalysisMarkStrategy.cs index 61faf7e624ad40..23b4384ea64677 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyAnalysisMarkStrategy.cs +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyAnalysisMarkStrategy.cs @@ -1,7 +1,6 @@ // 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; namespace ILCompiler.DependencyAnalysisFramework diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyAnalyzerLogEdgeVisitor.cs b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyAnalyzerLogEdgeVisitor.cs index 422471119d96d4..4c55ba328b4e03 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyAnalyzerLogEdgeVisitor.cs +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyAnalyzerLogEdgeVisitor.cs @@ -1,12 +1,6 @@ // 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.Text; -using System.Threading.Tasks; - namespace ILCompiler.DependencyAnalysisFramework { public interface IDependencyAnalyzerLogEdgeVisitor diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyNode.cs b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyNode.cs index 6ae00bd7eec7d2..76365d9c68bc59 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyNode.cs @@ -36,7 +36,7 @@ bool StaticDependenciesAreComputed } IEnumerable.DependencyListEntry> GetStaticDependencies(DependencyContextType context); - + IEnumerable.CombinedDependencyListEntry> GetConditionalStaticDependencies(DependencyContextType context); IEnumerable.CombinedDependencyListEntry> SearchDynamicDependencies(List> markedNodes, int firstNode, DependencyContextType context); diff --git a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/ILCompiler.DependencyAnalysisFramework.csproj b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/ILCompiler.DependencyAnalysisFramework.csproj index 28aa33b5afe733..2df31ad2b810c9 100644 --- a/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/ILCompiler.DependencyAnalysisFramework.csproj +++ b/src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/ILCompiler.DependencyAnalysisFramework.csproj @@ -8,6 +8,7 @@ x64;x86 AnyCPU false + true false Debug;Release;Checked + true diff --git a/src/coreclr/tools/aot/ILCompiler.RyuJit/JitInterface/CorInfoImpl.RyuJit.cs b/src/coreclr/tools/aot/ILCompiler.RyuJit/JitInterface/CorInfoImpl.RyuJit.cs index b29b104f41d708..efc9c60ac8cc09 100644 --- a/src/coreclr/tools/aot/ILCompiler.RyuJit/JitInterface/CorInfoImpl.RyuJit.cs +++ b/src/coreclr/tools/aot/ILCompiler.RyuJit/JitInterface/CorInfoImpl.RyuJit.cs @@ -23,7 +23,7 @@ namespace Internal.JitInterface { - unsafe partial class CorInfoImpl + internal unsafe partial class CorInfoImpl { private const CORINFO_RUNTIME_ABI TargetABI = CORINFO_RUNTIME_ABI.CORINFO_NATIVEAOT_ABI; @@ -55,8 +55,7 @@ public void CompileMethod(MethodCodeNode methodCodeNodeNeedingCode, MethodIL met _methodCodeNode = methodCodeNodeNeedingCode; _isFallbackBodyCompilation = methodIL != null; - if (methodIL == null) - methodIL = _compilation.GetMethodIL(MethodBeingCompiled); + methodIL ??= _compilation.GetMethodIL(MethodBeingCompiled); try { @@ -94,7 +93,7 @@ private enum CFI_OPCODE // - Combine in one single block for the whole prolog instead of one CFI block per assembler instruction // - Store CFA definition first // - Store all used registers in ascending order - private byte[] CompressARM64CFI(byte[] blobData) + private static byte[] CompressARM64CFI(byte[] blobData) { if (blobData == null || blobData.Length == 0) { @@ -223,7 +222,7 @@ private byte[] CompressARM64CFI(byte[] blobData) } } - private CORINFO_RUNTIME_LOOKUP_KIND GetLookupKindFromContextSource(GenericContextSource contextSource) + private static CORINFO_RUNTIME_LOOKUP_KIND GetLookupKindFromContextSource(GenericContextSource contextSource) { switch (contextSource) { @@ -825,7 +824,7 @@ private InfoAccessType constructStringLiteral(CORINFO_MODULE_STRUCT_* module, md return stringObject.RepresentsIndirectionCell ? InfoAccessType.IAT_PVALUE : InfoAccessType.IAT_VALUE; } - enum RhEHClauseKind + private enum RhEHClauseKind { RH_EH_CLAUSE_TYPED = 0, RH_EH_CLAUSE_FAULT = 1, @@ -834,7 +833,7 @@ enum RhEHClauseKind private ObjectNode.ObjectData EncodeEHInfo() { - var builder = new ObjectDataBuilder(); + var builder = default(ObjectDataBuilder); builder.RequireInitialAlignment(1); int totalClauses = _ehClauses.Length; @@ -950,7 +949,7 @@ private void setVars(CORINFO_METHOD_STRUCT_* ftn, uint cVars, NativeVarInfo* var debugVarInfoBuilders[varNumber].Add(new DebugVarRangeInfo(vars[i].startOffset, vars[i].endOffset, vars[i].varLoc)); } - var debugVarInfos = new ArrayBuilder(); + var debugVarInfos = default(ArrayBuilder); for (uint i = 0; i < debugVarInfoBuilders.Length; i++) { if (debugVarInfoBuilders[i].Count > 0) @@ -984,7 +983,7 @@ private void setBoundaries(CORINFO_METHOD_STRUCT_* ftn, uint cMap, OffsetMapping } } - ArrayBuilder debugLocInfos = new ArrayBuilder(); + ArrayBuilder debugLocInfos = default(ArrayBuilder); for (int i = 0; i < cMap; i++) { OffsetMapping* nativeToILInfo = &pMap[i]; @@ -1554,12 +1553,14 @@ private void getCallInfo(ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_RESO { pResult->codePointerOrStubLookup.lookupKind.needsRuntimeLookup = false; pResult->codePointerOrStubLookup.constLookup.accessType = InfoAccessType.IAT_PVALUE; +#pragma warning disable SA1001, SA1113, SA1115 // Commas should be spaced correctly pResult->codePointerOrStubLookup.constLookup.addr = (void*)ObjectToHandle( _compilation.NodeFactory.InterfaceDispatchCell(targetMethod #if !SUPPORT_JIT , _compilation.NameMangler.GetMangledMethodName(MethodBeingCompiled).ToString() #endif )); +#pragma warning restore SA1001, SA1113, SA1115 // Commas should be spaced correctly } pResult->nullInstanceCheck = false; @@ -1862,7 +1863,9 @@ private unsafe HRESULT allocPgoInstrumentationBySchema(CORINFO_METHOD_STRUCT_* f throw new NotImplementedException("allocPgoInstrumentationBySchema"); } +#pragma warning disable CA1822 // Mark members as static private CORINFO_CLASS_STRUCT_* getLikelyClass(CORINFO_METHOD_STRUCT_* ftnHnd, CORINFO_CLASS_STRUCT_* baseHnd, uint IlOffset, ref uint pLikelihood, ref uint pNumberOfClasses) +#pragma warning restore CA1822 // Mark members as static { return null; } @@ -1980,7 +1983,9 @@ private int SizeOfPInvokeTransitionFrame private bool canGetCookieForPInvokeCalliSig(CORINFO_SIG_INFO* szMetaSig) { throw new NotImplementedException("canGetCookieForPInvokeCalliSig"); } +#pragma warning disable CA1822 // Mark members as static private void classMustBeLoadedBeforeCodeIsRun(CORINFO_CLASS_STRUCT_* cls) +#pragma warning restore CA1822 // Mark members as static { } @@ -1994,15 +1999,21 @@ private void setEHinfo(uint EHnumber, ref CORINFO_EH_CLAUSE clause) _ehClauses[EHnumber] = clause; } +#pragma warning disable CA1822 // Mark members as static private void beginInlining(CORINFO_METHOD_STRUCT_* inlinerHnd, CORINFO_METHOD_STRUCT_* inlineeHnd) +#pragma warning restore CA1822 // Mark members as static { } +#pragma warning disable CA1822 // Mark members as static private void reportInliningDecision(CORINFO_METHOD_STRUCT_* inlinerHnd, CORINFO_METHOD_STRUCT_* inlineeHnd, CorInfoInline inlineResult, byte* reason) +#pragma warning restore CA1822 // Mark members as static { } +#pragma warning disable CA1822 // Mark members as static private void updateEntryPointForTailCall(ref CORINFO_CONST_LOOKUP entryPoint) +#pragma warning restore CA1822 // Mark members as static { } diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ArchitectureSpecificFieldLayoutTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ArchitectureSpecificFieldLayoutTests.cs index f9fe3b7687439d..38a3595f6c085f 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ArchitectureSpecificFieldLayoutTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ArchitectureSpecificFieldLayoutTests.cs @@ -2,11 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -using Internal.TypeSystem.Ecma; using Internal.TypeSystem; using Xunit; @@ -15,19 +10,18 @@ namespace TypeSystemTests { public class ArchitectureSpecificFieldLayoutTests { - TestTypeSystemContext _contextX86; - ModuleDesc _testModuleX86; - TestTypeSystemContext _contextX64; - ModuleDesc _testModuleX64; - TestTypeSystemContext _contextX64Windows; - ModuleDesc _testModuleX64Windows; - TestTypeSystemContext _contextX64Linux; - ModuleDesc _testModuleX64Linux; - TestTypeSystemContext _contextARM; - ModuleDesc _testModuleARM; - - TestTypeSystemContext _contextARM64; - ModuleDesc _testModuleARM64; + private TestTypeSystemContext _contextX86; + private ModuleDesc _testModuleX86; + private TestTypeSystemContext _contextX64; + private ModuleDesc _testModuleX64; + private TestTypeSystemContext _contextX64Windows; + private ModuleDesc _testModuleX64Windows; + private TestTypeSystemContext _contextX64Linux; + private ModuleDesc _testModuleX64Linux; + private TestTypeSystemContext _contextARM; + private ModuleDesc _testModuleARM; + private TestTypeSystemContext _contextARM64; + private ModuleDesc _testModuleARM64; public ArchitectureSpecificFieldLayoutTests() { @@ -344,20 +338,20 @@ public void TestAlignmentBehavior_IntShortEnumStructAuto() Assert.Equal(0x4, tX86.InstanceByteAlignment.AsInt); Assert.Equal(0x10, tX64.InstanceByteCountUnaligned.AsInt); - Assert.Equal(0xC, tARM.InstanceByteCountUnaligned.AsInt); - Assert.Equal(0xC, tX86.InstanceByteCountUnaligned.AsInt); + Assert.Equal(0xC, tARM.InstanceByteCountUnaligned.AsInt); + Assert.Equal(0xC, tX86.InstanceByteCountUnaligned.AsInt); Assert.Equal(0x10, tX64.InstanceByteCount.AsInt); - Assert.Equal(0xC, tARM.InstanceByteCount.AsInt); - Assert.Equal(0xC, tX86.InstanceByteCount.AsInt); + Assert.Equal(0xC, tARM.InstanceByteCount.AsInt); + Assert.Equal(0xC, tX86.InstanceByteCount.AsInt); Assert.Equal(0x8, tX64.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tARM.InstanceFieldAlignment.AsInt); Assert.Equal(0x4, tX86.InstanceFieldAlignment.AsInt); Assert.Equal(0x10, tX64.InstanceFieldSize.AsInt); - Assert.Equal(0xC, tARM.InstanceFieldSize.AsInt); - Assert.Equal(0xC, tX86.InstanceFieldSize.AsInt); + Assert.Equal(0xC, tARM.InstanceFieldSize.AsInt); + Assert.Equal(0xC, tX86.InstanceFieldSize.AsInt); Assert.Equal(0x0, tX64.GetField("_1").Offset.AsInt); Assert.Equal(0x0, tARM.GetField("_1").Offset.AsInt); @@ -468,13 +462,13 @@ public void TestAlignmentBehavior_StructStructByte_StructByteAuto() } [Theory] - [InlineData("StructStructByte_StructByteAuto", new int[]{1,1,1}, new int[]{2,2,2})] - [InlineData("StructStructByte_Struct2BytesAuto", new int[]{2,2,2}, new int[]{4,4,4})] - [InlineData("StructStructByte_Struct3BytesAuto", new int[]{4,4,4}, new int[]{8,8,8})] - [InlineData("StructStructByte_Struct4BytesAuto", new int[]{4,4,4}, new int[]{8,8,8})] - [InlineData("StructStructByte_Struct5BytesAuto", new int[]{8,4,4}, new int[]{16,12,12})] - [InlineData("StructStructByte_Struct8BytesAuto", new int[]{8,4,4}, new int[]{16,12,12})] - [InlineData("StructStructByte_Struct9BytesAuto", new int[]{8,4,4}, new int[]{24,16,16})] + [InlineData("StructStructByte_StructByteAuto", new int[] { 1, 1, 1 }, new int[] { 2, 2, 2 })] + [InlineData("StructStructByte_Struct2BytesAuto", new int[] { 2, 2, 2 }, new int[] { 4, 4, 4 })] + [InlineData("StructStructByte_Struct3BytesAuto", new int[] { 4, 4, 4 }, new int[] { 8, 8, 8 })] + [InlineData("StructStructByte_Struct4BytesAuto", new int[] { 4, 4, 4 }, new int[] { 8, 8, 8 })] + [InlineData("StructStructByte_Struct5BytesAuto", new int[] { 8, 4, 4 }, new int[] { 16, 12, 12 })] + [InlineData("StructStructByte_Struct8BytesAuto", new int[] { 8, 4, 4 }, new int[] { 16, 12, 12 })] + [InlineData("StructStructByte_Struct9BytesAuto", new int[] { 8, 4, 4 }, new int[] { 24, 16, 16 })] public void TestAlignmentBehavior_AutoAlignmentRules(string wrapperType, int[] alignment, int[] size) { string _namespace = "Sequential"; diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/CanonicalizationTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/CanonicalizationTests.cs index d3f2c6c6036d67..c42cacbe3bfe42 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/CanonicalizationTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/CanonicalizationTests.cs @@ -1,8 +1,6 @@ // 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 Internal.TypeSystem; using Xunit; diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/CastingTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/CastingTests.cs index 4bcf3432f522f3..fdf12612f40037 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/CastingTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/CastingTests.cs @@ -54,7 +54,7 @@ public void TestInterfaceCasting() Assert.False(objectType.CanCastTo(iFooType)); } - + [Fact] public void TestSameSizeArrayTypeCasting() { @@ -148,8 +148,6 @@ public void TestGenericParameterCasting() TypeDesc valueTypeType = _context.GetWellKnownType(WellKnownType.ValueType); TypeDesc iFooType = _testModule.GetType("Casting", "IFoo"); TypeDesc classImplementingIFooType = _testModule.GetType("Casting", "ClassImplementingIFoo"); - TypeDesc classImplementingIFooIndirectlyType = - _testModule.GetType("Casting", "ClassImplementingIFooIndirectly"); Assert.True(paramWithNoConstraint.CanCastTo(objectType)); Assert.False(paramWithNoConstraint.CanCastTo(valueTypeType)); diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ConstraintsValidationTest.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ConstraintsValidationTest.cs index 3ea1408a96c102..555504eecad05b 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ConstraintsValidationTest.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ConstraintsValidationTest.cs @@ -44,7 +44,7 @@ public ConstraintsValidationTest() _context = new TestTypeSystemContext(TargetArchitecture.Unknown); var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly"); _context.SetSystemModule(systemModule); - + _testModule = systemModule; _iNonGenType = _testModule.GetType("GenericConstraints", "INonGen"); @@ -178,7 +178,7 @@ public void TestTypeConstraints() } // SimpleTypeConstraint and DoubleSimpleTypeConstraint - foreach(var genType in new MetadataType[] { _simpleTypeConstraintType , _doubleSimpleTypeConstraintType }) + foreach(var genType in new MetadataType[] { _simpleTypeConstraintType, _doubleSimpleTypeConstraintType }) { instantiatedType = genType.MakeInstantiatedType(_arg1Type); Assert.True(instantiatedType.CheckConstraints()); diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ExceptionStringTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ExceptionStringTests.cs index d40bdf774126d8..776dc296442af4 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ExceptionStringTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ExceptionStringTests.cs @@ -23,4 +23,4 @@ public void TestAllExceptionIdsHaveMessages() } } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/GCPointerMapTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/GCPointerMapTests.cs index 51578a171105a8..de3fc50334146c 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/GCPointerMapTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/GCPointerMapTests.cs @@ -9,8 +9,8 @@ namespace TypeSystemTests { public partial class GCPointerMapTests { - TestTypeSystemContext _context; - ModuleDesc _testModule; + private TestTypeSystemContext _context; + private ModuleDesc _testModule; public GCPointerMapTests() { diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/GenericTypeAndMethodTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/GenericTypeAndMethodTests.cs index c9224fa7d9dbd6..73233b17df43f9 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/GenericTypeAndMethodTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/GenericTypeAndMethodTests.cs @@ -113,7 +113,7 @@ public void TestMethodLookup() { MetadataType t = _testModule.GetType("GenericTypes", "GenericClass`1").MakeInstantiatedType(_context.GetWellKnownType(WellKnownType.Int32)); - MethodSignature sig = new MethodSignature(MethodSignatureFlags.None, 0, _context.GetSignatureVariable(0, false), new TypeDesc[0] { }); + MethodSignature sig = new MethodSignature(MethodSignatureFlags.None, 0, _context.GetSignatureVariable(0, false), System.Array.Empty()); MethodDesc fooMethod = t.GetMethod("Foo", sig); Assert.NotNull(fooMethod); } @@ -222,8 +222,6 @@ public void TestConstructedMethodAdjustment() MetadataType genericOpenType = _testModule.GetType("GenericTypes", "TwoParamGenericClass`2"); MetadataType nonGenericType = _testModule.GetType("GenericTypes", "NonGenericClass"); - MethodDesc nonGenericOnGeneric = genericOpenType.GetMethod("NonGenericFunction", null); - MethodDesc genericOnGeneric = genericOpenType.GetMethod("GenericFunction", null); MethodDesc genericOnNonGeneric = nonGenericType.GetMethod("GenericFunction", null); InstantiatedType genericIntString = genericOpenType.MakeInstantiatedType(intType, stringType); diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/HashcodeTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/HashcodeTests.cs index a9451752da9b98..a57216950e0b7d 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/HashcodeTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/HashcodeTests.cs @@ -12,8 +12,8 @@ namespace TypeSystemTests { public class HashcodeTests { - TestTypeSystemContext _context; - ModuleDesc _testModule; + private TestTypeSystemContext _context; + private ModuleDesc _testModule; public HashcodeTests() { @@ -27,7 +27,6 @@ public HashcodeTests() [Fact] public void TestMultidimensionalArrays() { - DefType systemArrayType = _context.GetWellKnownType(WellKnownType.Array); TypeDesc objectType = _context.GetWellKnownType(WellKnownType.Object); ArrayType objectMDArrayRank1 = _context.GetArrayType(objectType, 1); @@ -42,8 +41,6 @@ public void TestMultidimensionalArrays() [Fact] public void TestSingleDimensionalArrays() { - DefType systemArrayType = _context.GetWellKnownType(WellKnownType.Array); - TypeDesc objectType = _context.GetWellKnownType(WellKnownType.Object); ArrayType objectArray = _context.GetArrayType(objectType); @@ -54,7 +51,6 @@ public void TestSingleDimensionalArrays() [Fact] public void TestNonGenericTypes() { - DefType systemArrayType = _context.GetWellKnownType(WellKnownType.Array); MetadataType nonNestedType = (MetadataType)_testModule.GetType("Hashcode", "NonNestedType"); TypeDesc nestedType = nonNestedType.GetNestedType("NestedType"); @@ -67,7 +63,7 @@ public void TestNonGenericTypes() } [Fact] - void TestGenericTypes() + public void TestGenericTypes() { MetadataType ilistType = (MetadataType)_testModule.GetType("System.Collections.Generic", "IList`1"); DefType systemArrayType = _context.GetWellKnownType(WellKnownType.Array); diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ILCompiler.TypeSystem.Tests.csproj b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ILCompiler.TypeSystem.Tests.csproj index 1f6b33ff18ba39..6d58717c7cbba9 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ILCompiler.TypeSystem.Tests.csproj +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ILCompiler.TypeSystem.Tests.csproj @@ -17,6 +17,7 @@ READYTORUN;$(DefineConstants) + true diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/InstanceFieldLayoutTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/InstanceFieldLayoutTests.cs index 083a4e65af3844..e846cbfe31af93 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/InstanceFieldLayoutTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/InstanceFieldLayoutTests.cs @@ -11,9 +11,9 @@ namespace TypeSystemTests { public class InstanceFieldLayoutTests { - TestTypeSystemContext _context; - ModuleDesc _testModule; - ModuleDesc _ilTestModule; + private TestTypeSystemContext _context; + private ModuleDesc _testModule; + private ModuleDesc _ilTestModule; public InstanceFieldLayoutTests() { diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/InterfacesTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/InterfacesTests.cs index 8e6d96f2cffd6d..03377d5fb03613 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/InterfacesTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/InterfacesTests.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Linq; using Internal.TypeSystem; @@ -11,8 +10,8 @@ namespace TypeSystemTests { public class InterfacesTests { - TestTypeSystemContext _context; - ModuleDesc _testModule; + private TestTypeSystemContext _context; + private ModuleDesc _testModule; public InterfacesTests() { diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/RuntimeDeterminedTypesTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/RuntimeDeterminedTypesTests.cs index a394a562af9f5f..210df8937bfe9e 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/RuntimeDeterminedTypesTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/RuntimeDeterminedTypesTests.cs @@ -26,7 +26,7 @@ public RuntimeDeterminedTypesTests() _context = new TestTypeSystemContext(TargetArchitecture.Unknown); var systemModule = _context.CreateModuleForSimpleName("CoreTestAssembly"); _context.SetSystemModule(systemModule); - + _testModule = systemModule; _referenceType = _testModule.GetType("Canonicalization", "ReferenceType"); @@ -140,7 +140,7 @@ public void TestSignatureInstantiation() var grtOverRtStRtShared = grtOverRtStRt.ConvertToSharedRuntimeDeterminedForm(); // GenericReferenceTypeWithThreeParams substituted over - // an instantiation of is + // an instantiation of is // GenericReferenceTypeWithThreeParams var grtOverRtStRtSharedInstantiated = grtOverRtStRtShared.GetNonRuntimeDeterminedTypeFromRuntimeDeterminedSubtypeViaSubstitution( new Instantiation(_referenceType, _structType, _otherReferenceType), diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/SignatureTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/SignatureTests.cs index 23e1a9f58cfe2b..767f7d760d4a85 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/SignatureTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/SignatureTests.cs @@ -6,9 +6,6 @@ using System.Linq; using System.Text; -using System.Reflection.Metadata; -using System.Reflection.Metadata.Ecma335; - using Internal.IL; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; @@ -253,7 +250,7 @@ public void TestMDArrayFunctionReading() { successes++; } - _output.WriteLine($"call {tokenReferenceResult.ToString()}"); + _output.WriteLine($"call {tokenReferenceResult}"); break; } } diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/StaticFieldLayoutTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/StaticFieldLayoutTests.cs index 2133c7429cc1b4..e5855d624672c7 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/StaticFieldLayoutTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/StaticFieldLayoutTests.cs @@ -14,8 +14,8 @@ namespace TypeSystemTests { public class StaticFieldLayoutTests { - TestTypeSystemContext _context; - ModuleDesc _testModule; + private TestTypeSystemContext _context; + private ModuleDesc _testModule; public StaticFieldLayoutTests() { diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/SyntheticVirtualOverrideTests.DiagnosticName.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/SyntheticVirtualOverrideTests.DiagnosticName.cs index 0ffbdd8a4c0a09..3c6496f2a30909 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/SyntheticVirtualOverrideTests.DiagnosticName.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/SyntheticVirtualOverrideTests.DiagnosticName.cs @@ -1,14 +1,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; -using System.Collections.Generic; -using System.Linq; - using Internal.TypeSystem; -using Xunit; - namespace TypeSystemTests { diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/SyntheticVirtualOverrideTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/SyntheticVirtualOverrideTests.cs index 25be615490fbc3..b23806c7072f86 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/SyntheticVirtualOverrideTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/SyntheticVirtualOverrideTests.cs @@ -14,8 +14,8 @@ namespace TypeSystemTests { public partial class SyntheticVirtualOverrideTests { - TestTypeSystemContext _context; - ModuleDesc _testModule; + private TestTypeSystemContext _context; + private ModuleDesc _testModule; public SyntheticVirtualOverrideTests() { @@ -50,7 +50,7 @@ public void TestStructEqualsAndGetHashCode() Assert.All(virtualSlots, s => { Assert.True(s.OwningType.IsObject); }); Assert.Equal(4, virtualSlots.Count); - List vtable = virtualSlots.Select(s => t.FindVirtualFunctionTargetMethodOnObjectType(s)).ToList(); + List vtable = virtualSlots.Select(t.FindVirtualFunctionTargetMethodOnObjectType).ToList(); Assert.Contains(vtable, m => m.Name == "Equals" && m.OwningType == t); Assert.Contains(vtable, m => m.Name == "GetHashCode" && m.OwningType == t); @@ -73,7 +73,7 @@ public void TestUnoverriddenSyntheticEqualsAndGetHashCode() Assert.All(virtualSlots, s => { Assert.True(s.OwningType.IsObject); }); Assert.Equal(4, virtualSlots.Count); - List vtable = virtualSlots.Select(s => t.FindVirtualFunctionTargetMethodOnObjectType(s)).ToList(); + List vtable = virtualSlots.Select(t.FindVirtualFunctionTargetMethodOnObjectType).ToList(); Assert.Contains(vtable, m => m.Name == "Equals" && m.OwningType == baseType); Assert.Contains(vtable, m => m.Name == "GetHashCode" && m.OwningType == baseType); @@ -96,7 +96,7 @@ public void TestOverriddenSyntheticEqualsAndGetHashCode() Assert.All(virtualSlots, s => { Assert.True(s.OwningType.IsObject); }); Assert.Equal(4, virtualSlots.Count); - List vtable = virtualSlots.Select(s => t.FindVirtualFunctionTargetMethodOnObjectType(s)).ToList(); + List vtable = virtualSlots.Select(t.FindVirtualFunctionTargetMethodOnObjectType).ToList(); Assert.Contains(vtable, m => m.Name == "Equals" && m.OwningType == t); Assert.Contains(vtable, m => m.Name == "GetHashCode" && m.OwningType == t); @@ -104,7 +104,7 @@ public void TestOverriddenSyntheticEqualsAndGetHashCode() Assert.Contains(vtable, m => m.Name == "ToString" && m.OwningType.IsObject); } - private class SyntheticVirtualOverrideTypeSystemContext : TestTypeSystemContext + private sealed class SyntheticVirtualOverrideTypeSystemContext : TestTypeSystemContext { private Dictionary _getHashCodeMethods = new Dictionary(); private Dictionary _equalsMethods = new Dictionary(); @@ -170,7 +170,7 @@ protected override IEnumerable GetAllVirtualMethods(TypeDesc type) } } - private partial class SyntheticMethod : MethodDesc + private sealed partial class SyntheticMethod : MethodDesc { private TypeDesc _owningType; private MethodSignature _signature; diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/TestMetadataFieldLayoutAlgorithm.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/TestMetadataFieldLayoutAlgorithm.cs index fdd8382a5bdcfa..da423b43cb2803 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/TestMetadataFieldLayoutAlgorithm.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/TestMetadataFieldLayoutAlgorithm.cs @@ -1,14 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; -using System.Collections.Generic; - using Internal.TypeSystem; namespace TypeSystemTests { - class TestMetadataFieldLayoutAlgorithm : MetadataFieldLayoutAlgorithm + internal sealed class TestMetadataFieldLayoutAlgorithm : MetadataFieldLayoutAlgorithm { protected override void PrepareRuntimeSpecificStaticFieldLayout(TypeSystemContext context, ref ComputedStaticFieldLayout layout) { diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/TestTypeSystemContext.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/TestTypeSystemContext.cs index 3f963c24104eb1..83cc977d22945a 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/TestTypeSystemContext.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/TestTypeSystemContext.cs @@ -19,18 +19,18 @@ public enum CanonicalizationMode RuntimeDetermined, } - class TestTypeSystemContext : MetadataTypeSystemContext + internal class TestTypeSystemContext : MetadataTypeSystemContext { - Dictionary _modules = new Dictionary(StringComparer.OrdinalIgnoreCase); + private Dictionary _modules = new Dictionary(StringComparer.OrdinalIgnoreCase); private VectorFieldLayoutAlgorithm _vectorFieldLayoutAlgorithm; private Int128FieldLayoutAlgorithm _int128FieldLayoutAlgorithm; - MetadataFieldLayoutAlgorithm _metadataFieldLayout = new TestMetadataFieldLayoutAlgorithm(); - MetadataRuntimeInterfacesAlgorithm _metadataRuntimeInterfacesAlgorithm = new MetadataRuntimeInterfacesAlgorithm(); - ArrayOfTRuntimeInterfacesAlgorithm _arrayOfTRuntimeInterfacesAlgorithm; - VirtualMethodAlgorithm _virtualMethodAlgorithm = new MetadataVirtualMethodAlgorithm(); - + private MetadataFieldLayoutAlgorithm _metadataFieldLayout = new TestMetadataFieldLayoutAlgorithm(); + private MetadataRuntimeInterfacesAlgorithm _metadataRuntimeInterfacesAlgorithm = new MetadataRuntimeInterfacesAlgorithm(); + private ArrayOfTRuntimeInterfacesAlgorithm _arrayOfTRuntimeInterfacesAlgorithm; + private VirtualMethodAlgorithm _virtualMethodAlgorithm = new MetadataVirtualMethodAlgorithm(); + public CanonicalizationMode CanonMode { get; set; } = CanonicalizationMode.RuntimeDetermined; public TestTypeSystemContext(TargetArchitecture arch, TargetOS targetOS = TargetOS.Unknown) @@ -54,10 +54,7 @@ public ModuleDesc CreateModuleForSimpleName(string simpleName, Stream preLoadedF string bindingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string filePath = Path.Combine(bindingDirectory, simpleName + ".dll"); Stream peStream = preLoadedFile; - if (peStream == null) - { - peStream = File.OpenRead(filePath); - } + peStream ??= File.OpenRead(filePath); ModuleDesc module = Internal.TypeSystem.Ecma.EcmaModule.Create(this, new PEReader(peStream), containingAssembly: null); _modules.Add(simpleName, module); @@ -87,10 +84,7 @@ public override FieldLayoutAlgorithm GetLayoutAlgorithmForType(DefType type) protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForNonPointerArrayType(ArrayType type) { - if (_arrayOfTRuntimeInterfacesAlgorithm == null) - { - _arrayOfTRuntimeInterfacesAlgorithm = new ArrayOfTRuntimeInterfacesAlgorithm(SystemModule.GetType("System", "Array`1")); - } + _arrayOfTRuntimeInterfacesAlgorithm ??= new ArrayOfTRuntimeInterfacesAlgorithm(SystemModule.GetType("System", "Array`1")); return _arrayOfTRuntimeInterfacesAlgorithm; } diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/TypeNameParsingTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/TypeNameParsingTests.cs index d7a08bf583d505..a426730a784bbd 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/TypeNameParsingTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/TypeNameParsingTests.cs @@ -1,7 +1,6 @@ // 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 Internal.TypeSystem; @@ -12,22 +11,17 @@ namespace TypeSystemTests { public class TypeNameParsingTests { - TestTypeSystemContext _context; - ModuleDesc _testModule; - - string _coreAssemblyQualifier; - - MetadataType _simpleType; - MetadataType _nestedType; - MetadataType _nestedTwiceType; - - MetadataType _genericType; - MetadataType _nestedNongenericType; - MetadataType _nestedGenericType; - - MetadataType _veryGenericType; - - MetadataType _structType; + private TestTypeSystemContext _context; + private ModuleDesc _testModule; + private string _coreAssemblyQualifier; + private MetadataType _simpleType; + private MetadataType _nestedType; + private MetadataType _nestedTwiceType; + private MetadataType _genericType; + private MetadataType _nestedNongenericType; + private MetadataType _nestedGenericType; + private MetadataType _veryGenericType; + private MetadataType _structType; public TypeNameParsingTests() { @@ -164,21 +158,21 @@ public void TestInstantiatedTypes() _simpleType, _context.GetWellKnownType(WellKnownType.Int32) ); - TypeDesc result = _testModule.GetTypeByCustomAttributeTypeName(String.Format( + TypeDesc result = _testModule.GetTypeByCustomAttributeTypeName(string.Format( "TypeNameParsing.VeryGeneric`3[[System.Object, {0}],TypeNameParsing.Simple,[System.Int32, {0}]]", _coreAssemblyQualifier)); Assert.Equal(expected, result); } { TypeDesc expected = nullableType.MakeInstantiatedType(_structType); - TypeDesc result = _testModule.GetTypeByCustomAttributeTypeName(String.Format( + TypeDesc result = _testModule.GetTypeByCustomAttributeTypeName(string.Format( "System.Nullable`1[TypeNameParsing.Struct], {0}", _coreAssemblyQualifier)); Assert.Equal(expected, result); } { TypeDesc expected = nullableType.MakeInstantiatedType(_context.GetWellKnownType(WellKnownType.Int32)); - TypeDesc result = _testModule.GetTypeByCustomAttributeTypeName(String.Format( + TypeDesc result = _testModule.GetTypeByCustomAttributeTypeName(string.Format( "System.Nullable`1[[System.Int32, {0}]], {0}", _coreAssemblyQualifier)); Assert.Equal(expected, result); } @@ -205,7 +199,7 @@ public void TestMixed() TypeDesc expected = _nestedNongenericType.MakeInstantiatedType( nullableType.MakeInstantiatedType(_structType) ); - TypeDesc result = _testModule.GetTypeByCustomAttributeTypeName(String.Format( + TypeDesc result = _testModule.GetTypeByCustomAttributeTypeName(string.Format( "TypeNameParsing.Generic`1+NestedNongeneric[[System.Nullable`1[TypeNameParsing.Struct], {0}]]", _coreAssemblyQualifier)); Assert.Equal(expected, result); } @@ -215,7 +209,7 @@ public void TestMixed() nullableType.MakeInstantiatedType(_context.GetWellKnownType(WellKnownType.Int32)), _nestedType.MakeArrayType() ); - TypeDesc result = _testModule.GetTypeByCustomAttributeTypeName(String.Format( + TypeDesc result = _testModule.GetTypeByCustomAttributeTypeName(string.Format( "TypeNameParsing.Generic`1+NestedGeneric`1[[System.Nullable`1[[System.Int32, {0}]], {0}],TypeNameParsing.Simple+Nested[]]", _coreAssemblyQualifier)); Assert.Equal(expected, result); } diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/UniversalGenericFieldLayoutTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/UniversalGenericFieldLayoutTests.cs index 6b81314b9f9765..8b430b4d72c651 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/UniversalGenericFieldLayoutTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/UniversalGenericFieldLayoutTests.cs @@ -12,12 +12,12 @@ namespace TypeSystemTests { public class UniversalGenericFieldLayoutTests { - TestTypeSystemContext _contextX86; - ModuleDesc _testModuleX86; - TestTypeSystemContext _contextX64; - ModuleDesc _testModuleX64; - TestTypeSystemContext _contextARM; - ModuleDesc _testModuleARM; + private TestTypeSystemContext _contextX86; + private ModuleDesc _testModuleX86; + private TestTypeSystemContext _contextX64; + private ModuleDesc _testModuleX64; + private TestTypeSystemContext _contextARM; + private ModuleDesc _testModuleARM; public UniversalGenericFieldLayoutTests() { @@ -44,8 +44,8 @@ public UniversalGenericFieldLayoutTests() [Fact] public void LayoutIntTests() { - Assert.Throws(() => { return new LayoutInt(int.MinValue); }); - Assert.Throws(() => { return new LayoutInt(-1); }); + Assert.Throws(() => { return new LayoutInt(int.MinValue); }); + Assert.Throws(() => { return new LayoutInt(-1); }); Assert.Equal(LayoutInt.Zero, new LayoutInt(0)); Assert.Equal(LayoutInt.One, new LayoutInt(1)); @@ -68,7 +68,7 @@ public void LayoutIntTests() Assert.Equal(0, new LayoutInt(0).AsInt); Assert.Equal(1, new LayoutInt(1).AsInt); - Assert.Equal(Int32.MaxValue, new LayoutInt(Int32.MaxValue).AsInt); + Assert.Equal(int.MaxValue, new LayoutInt(int.MaxValue).AsInt); Assert.Throws(() => { return LayoutInt.Indeterminate.AsInt; }); Assert.Equal(LayoutInt.Indeterminate, LayoutInt.Indeterminate + LayoutInt.Indeterminate); @@ -209,7 +209,7 @@ public void TestLayoutIntAlignUp(TargetDetails target) } - private void TestLayoutOfUniversalCanonTypeOnArchitecture(TypeSystemContext context) + private static void TestLayoutOfUniversalCanonTypeOnArchitecture(TypeSystemContext context) { // Assert all of the various layout information about the universal canon type itself Assert.Equal(LayoutInt.Indeterminate, context.UniversalCanonType.InstanceFieldAlignment); @@ -289,7 +289,7 @@ public void TestAllFieldsStructUniversalGeneric() Assert.Equal(LayoutInt.Indeterminate, genOfUUU.GetFields().ElementAt(2).Offset); } - private void TestIndeterminatedNestedStructFieldPerContext(TypeSystemContext context, ModuleDesc testModule, out InstantiatedType genOfIntNestedInt, out InstantiatedType genOfLongNestedInt) + private static void TestIndeterminatedNestedStructFieldPerContext(TypeSystemContext context, ModuleDesc testModule, out InstantiatedType genOfIntNestedInt, out InstantiatedType genOfLongNestedInt) { // Given a struct with all field universal, what is the layout? MetadataType tGen = testModule.GetType("GenericTypes", "GenStruct`3"); @@ -327,6 +327,7 @@ public void TestIndeterminateNestedStructField() InstantiatedType genOfIntNestedInt; InstantiatedType genOfLongNestedInt; +#pragma warning disable IDE0059 // Unnecessary assignment of a value TestIndeterminatedNestedStructFieldPerContext(_contextX64, _testModuleX64, out genOfIntNestedInt, out genOfLongNestedInt); Assert.Equal(new LayoutInt(8), genOfLongNestedInt.InstanceByteAlignment); Assert.Equal(new LayoutInt(8), genOfLongNestedInt.InstanceByteAlignment); @@ -334,11 +335,12 @@ public void TestIndeterminateNestedStructField() Assert.Equal(new LayoutInt(4), genOfLongNestedInt.InstanceByteAlignment); Assert.Equal(new LayoutInt(4), genOfLongNestedInt.InstanceByteAlignment); TestIndeterminatedNestedStructFieldPerContext(_contextARM, _testModuleARM, out genOfIntNestedInt, out genOfLongNestedInt); +#pragma warning restore IDE0059 // Unnecessary assignment of a value Assert.Equal(LayoutInt.Indeterminate, genOfLongNestedInt.InstanceByteAlignment); Assert.Equal(LayoutInt.Indeterminate, genOfLongNestedInt.InstanceByteAlignment); } - private void AssertClassIndeterminateSize(TypeSystemContext context, MetadataType type, LayoutInt expectedIndeterminateByteAlignment) + private static void AssertClassIndeterminateSize(TypeSystemContext context, MetadataType type, LayoutInt expectedIndeterminateByteAlignment) { Assert.Equal(context.Target.LayoutPointerSize, type.InstanceFieldAlignment); Assert.Equal(context.Target.LayoutPointerSize, type.InstanceFieldSize); @@ -347,7 +349,7 @@ private void AssertClassIndeterminateSize(TypeSystemContext context, MetadataTyp Assert.Equal(LayoutInt.Indeterminate, type.InstanceByteCountUnaligned); } - private void CommonClassLayoutTestBits(ModuleDesc testModule, + private static void CommonClassLayoutTestBits(ModuleDesc testModule, TypeSystemContext context, LayoutInt expectedIndeterminateByteAlignment, out InstantiatedType genOfIU, diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ValueTypeShapeCharacteristicsTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ValueTypeShapeCharacteristicsTests.cs index 2971fd468ead31..b0f60dca9acd02 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ValueTypeShapeCharacteristicsTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/ValueTypeShapeCharacteristicsTests.cs @@ -9,11 +9,10 @@ namespace TypeSystemTests { public class ValueTypeShapeCharacteristicsTests { - const ValueTypeShapeCharacteristics Float32Aggregate = ValueTypeShapeCharacteristics.Float32Aggregate; - const ValueTypeShapeCharacteristics Float64Aggregate = ValueTypeShapeCharacteristics.Float64Aggregate; - - TestTypeSystemContext _context; - ModuleDesc _testModule; + private const ValueTypeShapeCharacteristics Float32Aggregate = ValueTypeShapeCharacteristics.Float32Aggregate; + private const ValueTypeShapeCharacteristics Float64Aggregate = ValueTypeShapeCharacteristics.Float64Aggregate; + private TestTypeSystemContext _context; + private ModuleDesc _testModule; public ValueTypeShapeCharacteristicsTests() { @@ -32,7 +31,7 @@ public void TestHfaPrimitives() Assert.True(singleType.IsHomogeneousAggregate); Assert.Equal(Float32Aggregate, singleType.ValueTypeShapeCharacteristics); - + Assert.True(doubleType.IsHomogeneousAggregate); Assert.Equal(Float64Aggregate, doubleType.ValueTypeShapeCharacteristics); } diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/VirtualFunctionOverrideTests.cs b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/VirtualFunctionOverrideTests.cs index 938377d8cd3c9c..e228993296ff59 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/VirtualFunctionOverrideTests.cs +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem.Tests/VirtualFunctionOverrideTests.cs @@ -12,10 +12,10 @@ namespace TypeSystemTests { public class VirtualFunctionOverrideTests { - TestTypeSystemContext _context; - ModuleDesc _testModule; - DefType _stringType; - DefType _voidType; + private TestTypeSystemContext _context; + private ModuleDesc _testModule; + private DefType _stringType; + private DefType _voidType; public VirtualFunctionOverrideTests() { @@ -77,7 +77,7 @@ public void TestVirtualDispatchOnGenericType() MethodDesc targetOnInstance = testInstance.GetMethod("ToString", toStringSig); MethodDesc targetMethod = testInstance.FindVirtualFunctionTargetMethodOnObjectType(objectToString); - Assert.Equal(targetOnInstance, targetMethod); + Assert.Equal(targetOnInstance, targetMethod); } [Fact] @@ -103,7 +103,7 @@ public void TestFinalizeOverrideChecking() { MetadataType classWithFinalizer = _testModule.GetType("VirtualFunctionOverride", "ClassWithFinalizer"); DefType objectType = _testModule.Context.GetWellKnownType(WellKnownType.Object); - MethodDesc finalizeMethod = objectType.GetMethod("Finalize", new MethodSignature(MethodSignatureFlags.None, 0, _voidType, new TypeDesc[] { })); + MethodDesc finalizeMethod = objectType.GetMethod("Finalize", new MethodSignature(MethodSignatureFlags.None, 0, _voidType, Array.Empty())); MethodDesc actualFinalizer = classWithFinalizer.FindVirtualFunctionTargetMethodOnObjectType(finalizeMethod); Assert.NotNull(actualFinalizer); @@ -192,7 +192,6 @@ public void TestGenericsClassOverrideOfMethodWhereMethodHasBeenMovedFromTheTypeW var bang0Type = _context.GetSignatureVariable(0, false); var bang1Type = _context.GetSignatureVariable(1, false); var bang2Type = _context.GetSignatureVariable(2, false); - var bang3Type = _context.GetSignatureVariable(3, false); MethodSignature sigBang0Bang1 = new MethodSignature(0, 0, stringType, new TypeDesc[] { bang0Type, bang1Type }); MethodDesc baseMethod0_1 = baseType.GetMethod("Method", sigBang0Bang1); @@ -200,7 +199,6 @@ public void TestGenericsClassOverrideOfMethodWhereMethodHasBeenMovedFromTheTypeW MethodDesc virtualMethodBang0Bang1 = algo.FindVirtualFunctionTargetMethodOnObjectType(baseMethod0_1, myDerivedType); Assert.Equal(virtualMethodBang0Bang1.OwningType, baseType); - MethodSignature sigBang2Bang3 = new MethodSignature(0, 0, stringType, new TypeDesc[] { bang2Type, bang3Type }); MethodDesc baseMethod2_3 = null; // BaseMethod(!2,!3) has custom modifiers in its signature, and thus the sig is difficult to write up by hand. Just search for // it in an ad hoc manner diff --git a/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj b/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj index 4108ff822ed7f2..5fa3238e45d0a8 100644 --- a/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj +++ b/src/coreclr/tools/aot/ILCompiler.TypeSystem/ILCompiler.TypeSystem.csproj @@ -18,6 +18,7 @@ false Debug;Release;Checked true + true diff --git a/src/coreclr/tools/aot/ILCompiler/ConfigurablePInvokePolicy.cs b/src/coreclr/tools/aot/ILCompiler/ConfigurablePInvokePolicy.cs index 93fd389484b607..f5f634c06f12d0 100644 --- a/src/coreclr/tools/aot/ILCompiler/ConfigurablePInvokePolicy.cs +++ b/src/coreclr/tools/aot/ILCompiler/ConfigurablePInvokePolicy.cs @@ -11,7 +11,7 @@ namespace ILCompiler { - class ConfigurablePInvokePolicy : PInvokeILEmitterConfiguration + internal sealed class ConfigurablePInvokePolicy : PInvokeILEmitterConfiguration { private readonly TargetDetails _target; private readonly Dictionary> _directPInvokes; diff --git a/src/coreclr/tools/aot/ILCompiler/ILCompiler.csproj b/src/coreclr/tools/aot/ILCompiler/ILCompiler.csproj index 263d814a99de62..6dfd4edfebb2c2 100644 --- a/src/coreclr/tools/aot/ILCompiler/ILCompiler.csproj +++ b/src/coreclr/tools/aot/ILCompiler/ILCompiler.csproj @@ -1,7 +1,8 @@ - + $(RuntimeBinDir)ilc/ $(OutputRid) + true diff --git a/src/coreclr/tools/aot/ILCompiler/Program.cs b/src/coreclr/tools/aot/ILCompiler/Program.cs index f3c064835d8bff..7adb06231ed9a1 100644 --- a/src/coreclr/tools/aot/ILCompiler/Program.cs +++ b/src/coreclr/tools/aot/ILCompiler/Program.cs @@ -23,7 +23,7 @@ namespace ILCompiler { - internal class Program + internal sealed class Program { private const string DefaultSystemModule = "System.Private.CoreLib"; @@ -116,7 +116,7 @@ private Program() { } - private void Help(string helpText) + private static void Help(string helpText) { Console.WriteLine(); Console.Write(".NET Native IL Compiler"); @@ -276,13 +276,13 @@ private ArgumentSyntax ParseCommandLine(string[] args) string[] ValidArchitectures = new string[] { "arm", "arm64", "x86", "x64" }; string[] ValidOS = new string[] { "windows", "linux", "osx" }; - Program.ComputeDefaultOptions(out TargetOS defaultOs, out TargetArchitecture defaultArch); + ComputeDefaultOptions(out TargetOS defaultOs, out TargetArchitecture defaultArch); - extraHelp.Add(String.Format("Valid switches for {0} are: '{1}'. The default value is '{2}'", "--targetos", String.Join("', '", ValidOS), defaultOs.ToString().ToLowerInvariant())); + extraHelp.Add(string.Format("Valid switches for {0} are: '{1}'. The default value is '{2}'", "--targetos", string.Join("', '", ValidOS), defaultOs.ToString().ToLowerInvariant())); extraHelp.Add(""); - extraHelp.Add(String.Format("Valid switches for {0} are: '{1}'. The default value is '{2}'", "--targetarch", String.Join("', '", ValidArchitectures), defaultArch.ToString().ToLowerInvariant())); + extraHelp.Add(string.Format("Valid switches for {0} are: '{1}'. The default value is '{2}'", "--targetarch", string.Join("', '", ValidArchitectures), defaultArch.ToString().ToLowerInvariant())); extraHelp.Add(""); @@ -296,7 +296,7 @@ private ArgumentSyntax ParseCommandLine(string[] args) archString.Append(arch); archString.Append(": "); - TargetArchitecture targetArch = Program.GetTargetArchitectureFromArg(arch); + TargetArchitecture targetArch = GetTargetArchitectureFromArg(arch); bool first = true; foreach (var instructionSet in Internal.JitInterface.InstructionSetFlags.ArchitectureToValidInstructionSets(targetArch)) { @@ -476,7 +476,7 @@ private int Run(string[] args) { string instructionSet = instructionSetParamsInput[i]; - if (String.IsNullOrEmpty(instructionSet)) + if (string.IsNullOrEmpty(instructionSet)) throw new CommandLineException("Instruction set must not be empty"); char firstChar = instructionSet[0]; @@ -508,7 +508,7 @@ private int Run(string[] args) instructionSetSupportBuilder.ComputeInstructionSetFlags(out var supportedInstructionSet, out var unsupportedInstructionSet, (string specifiedInstructionSet, string impliedInstructionSet) => - throw new CommandLineException(String.Format("Unsupported combination of instruction sets: {0}/{1}", specifiedInstructionSet, impliedInstructionSet))); + throw new CommandLineException(string.Format("Unsupported combination of instruction sets: {0}/{1}", specifiedInstructionSet, impliedInstructionSet))); InstructionSetSupportBuilder optimisticInstructionSetSupportBuilder = new InstructionSetSupportBuilder(_targetArchitecture); @@ -615,7 +615,7 @@ private int Run(string[] args) securityMitigationOptions = SecurityMitigationOptions.ControlFlowGuardAnnotations; } - else if (!String.IsNullOrEmpty(_guard)) + else if (!string.IsNullOrEmpty(_guard)) { throw new CommandLineException($"Unrecognized mitigation option '{_guard}'"); } @@ -714,8 +714,8 @@ private int Run(string[] args) } } - _conditionallyRootedAssemblies = new List(_conditionallyRootedAssemblies.Select(a => ILLinkify(a))); - _trimmedAssemblies = new List(_trimmedAssemblies.Select(a => ILLinkify(a))); + _conditionallyRootedAssemblies = new List(_conditionallyRootedAssemblies.Select(ILLinkify)); + _trimmedAssemblies = new List(_trimmedAssemblies.Select(ILLinkify)); static string ILLinkify(string rootedAssembly) { @@ -751,12 +751,12 @@ static string ILLinkify(string rootedAssembly) CompilationBuilder builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup); - string compilationUnitPrefix = _multiFile ? System.IO.Path.GetFileNameWithoutExtension(_outputFilePath) : ""; + string compilationUnitPrefix = _multiFile ? Path.GetFileNameWithoutExtension(_outputFilePath) : ""; builder.UseCompilationUnitPrefix(compilationUnitPrefix); if (_mibcFilePaths.Count > 0) ((RyuJitCompilationBuilder)builder).UseProfileData(_mibcFilePaths); - if (!String.IsNullOrEmpty(_jitPath)) + if (!string.IsNullOrEmpty(_jitPath)) ((RyuJitCompilationBuilder)builder).UseJitPath(_jitPath); PInvokeILEmitterConfiguration pinvokePolicy = new ConfigurablePInvokePolicy(typeSystemContext.Target, _directPInvokes, _directPInvokeLists); @@ -1030,7 +1030,7 @@ static bool IsRelatedToInvalidInput(MethodDesc method) return 0; } - private void DiffCompilationResults(ref bool result, IEnumerable set1, IEnumerable set2, string prefix, + private static void DiffCompilationResults(ref bool result, IEnumerable set1, IEnumerable set2, string prefix, string set1name, string set2name, Predicate filter) { HashSet diff = new HashSet(set1); @@ -1053,7 +1053,7 @@ private void DiffCompilationResults(ref bool result, IEnumerable set1, IEn } } - private TypeDesc FindType(CompilerTypeSystemContext context, string typeName) + private static TypeDesc FindType(CompilerTypeSystemContext context, string typeName) { ModuleDesc systemModule = context.SystemModule; @@ -1125,7 +1125,7 @@ private static IEnumerable ProcessWarningCodes(IEnumerable warningC string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in values) { - if (!id.StartsWith("IL", StringComparison.Ordinal) || !ushort.TryParse(id.Substring(2), out ushort code)) + if (!id.StartsWith("IL", StringComparison.Ordinal) || !ushort.TryParse(id.AsSpan(2), out ushort code)) continue; yield return code; diff --git a/src/coreclr/tools/aot/ILCompiler/RdXmlRootProvider.cs b/src/coreclr/tools/aot/ILCompiler/RdXmlRootProvider.cs index e1d976eb3118e9..2c6b01849db031 100644 --- a/src/coreclr/tools/aot/ILCompiler/RdXmlRootProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler/RdXmlRootProvider.cs @@ -18,7 +18,7 @@ namespace ILCompiler /// Only supports a subset of the Runtime Directives configuration file format. /// /// https://msdn.microsoft.com/en-us/library/dn600639(v=vs.110).aspx - internal class RdXmlRootProvider : ICompilationRootProvider + internal sealed class RdXmlRootProvider : ICompilationRootProvider { private XElement _documentRoot; private TypeSystemContext _context; @@ -88,7 +88,7 @@ private void ProcessAssemblyDirective(IRootingServiceProvider rootProvider, XEle } } - private void ProcessTypeDirective(IRootingServiceProvider rootProvider, ModuleDesc containingModule, XElement typeElement) + private static void ProcessTypeDirective(IRootingServiceProvider rootProvider, ModuleDesc containingModule, XElement typeElement) { var typeNameAttribute = typeElement.Attribute("Name"); if (typeNameAttribute == null) @@ -137,7 +137,7 @@ private void ProcessTypeDirective(IRootingServiceProvider rootProvider, ModuleDe } } - private void ProcessMethodDirective(IRootingServiceProvider rootProvider, ModuleDesc containingModule, TypeDesc containingType, XElement methodElement) + private static void ProcessMethodDirective(IRootingServiceProvider rootProvider, ModuleDesc containingModule, TypeDesc containingType, XElement methodElement) { var methodNameAttribute = methodElement.Attribute("Name"); if (methodNameAttribute == null) diff --git a/src/coreclr/tools/aot/ILLink.Shared/Annotations.cs b/src/coreclr/tools/aot/ILLink.Shared/Annotations.cs index ca09218c0cc9c6..302dfeae6addf7 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/Annotations.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/Annotations.cs @@ -79,9 +79,9 @@ public static string GetMemberTypesString (DynamicallyAccessedMemberTypes member })); } - static readonly DynamicallyAccessedMemberTypes[] AllDynamicallyAccessedMemberTypes = GetAllDynamicallyAccessedMemberTypes (); + private static readonly DynamicallyAccessedMemberTypes[] AllDynamicallyAccessedMemberTypes = GetAllDynamicallyAccessedMemberTypes (); - static DynamicallyAccessedMemberTypes[] GetAllDynamicallyAccessedMemberTypes () + private static DynamicallyAccessedMemberTypes[] GetAllDynamicallyAccessedMemberTypes () { var values = new HashSet ( Enum.GetValues (typeof (DynamicallyAccessedMemberTypes)) diff --git a/src/coreclr/tools/aot/ILLink.Shared/ClosedAttribute.cs b/src/coreclr/tools/aot/ILLink.Shared/ClosedAttribute.cs index 5c0260fc1fb26a..feea932ed6fc9a 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/ClosedAttribute.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/ClosedAttribute.cs @@ -12,4 +12,4 @@ internal sealed class ClosedAttribute : Attribute { public ClosedAttribute () { } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/ILLink.Shared/DataFlow/DefaultValueDictionary.cs b/src/coreclr/tools/aot/ILLink.Shared/DataFlow/DefaultValueDictionary.cs index 1d8221463ace3b..599e7d3b9871c5 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/DataFlow/DefaultValueDictionary.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/DataFlow/DefaultValueDictionary.cs @@ -21,9 +21,8 @@ public struct DefaultValueDictionary : IEquatable where TValue : IEquatable { - Dictionary? Dictionary; - - readonly TValue DefaultValue; + private Dictionary? Dictionary; + private readonly TValue DefaultValue; public DefaultValueDictionary (TValue defaultValue) => (Dictionary, DefaultValue) = (null, defaultValue); @@ -81,13 +80,13 @@ public IEnumerator> GetEnumerator () public override string ToString () { StringBuilder sb = new (); - sb.Append ("{"); + sb.Append ('{'); if (Dictionary != null) { foreach (var kvp in Dictionary) sb.Append (Environment.NewLine).Append ('\t').Append (kvp.Key.ToString ()).Append (" -> ").Append (kvp.Value.ToString ()); } sb.Append (Environment.NewLine).Append ("\t_ -> ").Append (DefaultValue.ToString ()); - sb.Append (Environment.NewLine).Append ("}"); + sb.Append (Environment.NewLine).Append ('}'); return sb.ToString (); } diff --git a/src/coreclr/tools/aot/ILLink.Shared/DataFlow/ForwardDataFlowAnalysis.cs b/src/coreclr/tools/aot/ILLink.Shared/DataFlow/ForwardDataFlowAnalysis.cs index 345fbe8680a545..cd65c55f404b44 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/DataFlow/ForwardDataFlowAnalysis.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/DataFlow/ForwardDataFlowAnalysis.cs @@ -25,10 +25,10 @@ public abstract class ForwardDataFlowAnalysis blockOutput; + private readonly Dictionary blockOutput; // The control flow graph doesn't contain edges for exceptional control flow: // - From any point in a try region to the start of any catch or finally @@ -38,7 +38,7 @@ struct ControlFlowGraphState // when visiting operations inside of a try or catch region. // Dataflow states for exceptions propagating out of try or catch regions - readonly Dictionary> exceptionState; + private readonly Dictionary> exceptionState; // Control may flow through a finally region when an exception is thrown from anywhere in the corresponding // try or catch regions, or as part of non-exceptional control flow out of a try or catch. @@ -46,15 +46,14 @@ struct ControlFlowGraphState // propagated out of the finally. // Dataflow states for finally blocks when exception propagate through the finally region - readonly Dictionary exceptionFinallyState; + private readonly Dictionary exceptionFinallyState; // Finally regions may be reached (along non-exceptional paths) // from multiple branches. This gets updated to track the normal finally input // states from all of these branches (which aren't represented explicitly in the CFG). - readonly Dictionary finallyInputState; - - readonly TControlFlowGraph cfg; - readonly TLattice lattice; + private readonly Dictionary finallyInputState; + private readonly TControlFlowGraph cfg; + private readonly TLattice lattice; public ControlFlowGraphState (TControlFlowGraph cfg, TLattice lattice) { diff --git a/src/coreclr/tools/aot/ILLink.Shared/DataFlow/MaybeLattice.cs b/src/coreclr/tools/aot/ILLink.Shared/DataFlow/MaybeLattice.cs index f2b43d9deaebd9..4e77f96347ef0a 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/DataFlow/MaybeLattice.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/DataFlow/MaybeLattice.cs @@ -48,4 +48,4 @@ public Maybe Meet (Maybe left, Maybe right) return new Maybe (ValueLattice.Meet (leftValue, rightValue)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/ILLink.Shared/DataFlow/ValueSet.cs b/src/coreclr/tools/aot/ILLink.Shared/DataFlow/ValueSet.cs index 120e9116eaf376..c47397d5af258a 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/DataFlow/ValueSet.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/DataFlow/ValueSet.cs @@ -17,7 +17,7 @@ namespace ILLink.Shared.DataFlow { // Since we're going to do lot of type checks for this class a lot, it is much more efficient // if the class is sealed (as then the runtime can do a simple method table pointer comparison) - sealed class EnumerableValues : HashSet + private sealed class EnumerableValues : HashSet { public EnumerableValues (IEnumerable values) : base (values) { } @@ -32,9 +32,9 @@ public override int GetHashCode () public struct Enumerator : IEnumerator, IDisposable, IEnumerator { - readonly object? _value; - int _state; // 0 before begining, 1 at item, 2 after end - readonly IEnumerator? _enumerator; + private readonly object? _value; + private int _state; // 0 before begining, 1 at item, 2 after end + private readonly IEnumerator? _enumerator; internal Enumerator (object? values) { @@ -87,13 +87,13 @@ public void Reset () // null - no values (empty set) // TValue - single value itself // EnumerableValues typed object - multiple values, stored in the hashset - readonly object? _values; + private readonly object? _values; public ValueSet (TValue value) => _values = value; public ValueSet (IEnumerable values) => _values = new EnumerableValues (values); - ValueSet (EnumerableValues values) => _values = values; + private ValueSet (EnumerableValues values) => _values = values; public static implicit operator ValueSet (TValue value) => new (value); @@ -166,9 +166,9 @@ internal static ValueSet Meet (ValueSet left, ValueSet r public override string ToString () { StringBuilder sb = new (); - sb.Append ("{"); + sb.Append ('{'); sb.Append (string.Join (",", this.Select (v => v.ToString ()))); - sb.Append ("}"); + sb.Append ('}'); return sb.ToString (); } diff --git a/src/coreclr/tools/aot/ILLink.Shared/DiagnosticString.cs b/src/coreclr/tools/aot/ILLink.Shared/DiagnosticString.cs index 0102ae90c22c20..ce505e1c7727b1 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/DiagnosticString.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/DiagnosticString.cs @@ -10,8 +10,8 @@ namespace ILLink.Shared { public readonly struct DiagnosticString { - readonly string _titleFormat; - readonly string _messageFormat; + private readonly string _titleFormat; + private readonly string _messageFormat; public DiagnosticString (DiagnosticId diagnosticId) { diff --git a/src/coreclr/tools/aot/ILLink.Shared/HashUtils.cs b/src/coreclr/tools/aot/ILLink.Shared/HashUtils.cs index cc9b259bedb9c9..9a265ed2f648c8 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/HashUtils.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/HashUtils.cs @@ -10,7 +10,7 @@ namespace ILLink.Shared { - static class HashUtils + internal static class HashUtils { #if NETSTANDARD2_0 // This constant is taken from code that Roslyn generates for GetHashCode of records. diff --git a/src/coreclr/tools/aot/ILLink.Shared/IsExternalInit.cs b/src/coreclr/tools/aot/ILLink.Shared/IsExternalInit.cs index f2b081a032f43a..c95d5f7b153ba8 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/IsExternalInit.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/IsExternalInit.cs @@ -12,4 +12,4 @@ public sealed class IsExternalInit { } } -#endif \ No newline at end of file +#endif diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ArrayValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ArrayValue.cs index d8c399878374d1..342e3a5c51a630 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ArrayValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ArrayValue.cs @@ -9,9 +9,9 @@ namespace ILLink.Shared.TrimAnalysis { - sealed partial record ArrayValue : SingleValue + internal sealed partial record ArrayValue : SingleValue { - static ValueSetLattice MultiValueLattice => default; + private static ValueSetLattice MultiValueLattice => default; public readonly SingleValue Size; diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ConstIntValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ConstIntValue.cs index e83a7cd5d37838..b8816567f2a408 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ConstIntValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ConstIntValue.cs @@ -11,7 +11,7 @@ namespace ILLink.Shared.TrimAnalysis /// /// Represents a ldc on an int32. /// - sealed record ConstIntValue : SingleValue + internal sealed record ConstIntValue : SingleValue { public ConstIntValue (int value) => Value = value; diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/DiagnosticContext.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/DiagnosticContext.cs index 95c984d7fda51c..adece4a854a35f 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/DiagnosticContext.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/DiagnosticContext.cs @@ -6,7 +6,7 @@ namespace ILLink.Shared.TrimAnalysis { - readonly partial struct DiagnosticContext + public readonly partial struct DiagnosticContext { /// /// The diagnostic context may be entirely disabled or some kinds of warnings may be suppressed. diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/FieldValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/FieldValue.cs index 0041e436313f36..2c2354723f0d36 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/FieldValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/FieldValue.cs @@ -6,5 +6,5 @@ namespace ILLink.Shared.TrimAnalysis { - sealed partial record FieldValue : ValueWithDynamicallyAccessedMembers; + internal sealed partial record FieldValue : ValueWithDynamicallyAccessedMembers; } diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/FlowAnnotations.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/FlowAnnotations.cs index 7d3912e971e294..0a27918ceb44b4 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/FlowAnnotations.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/FlowAnnotations.cs @@ -10,7 +10,7 @@ namespace ILLink.Shared.TrimAnalysis { // Shared helpers to go from MethodProxy to dataflow values. - partial class FlowAnnotations + public partial class FlowAnnotations { internal partial bool MethodRequiresDataFlowAnalysis (MethodProxy method); @@ -28,4 +28,4 @@ partial class FlowAnnotations internal partial MethodParameterValue GetMethodParameterValue (MethodProxy method, int parameterIndex); } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/GenericParameterValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/GenericParameterValue.cs index 18bfa5fbbdef73..155ab10dc57e46 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/GenericParameterValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/GenericParameterValue.cs @@ -12,7 +12,7 @@ namespace ILLink.Shared.TrimAnalysis /// This is a System.Type value which represents generic parameter (basically result of typeof(T)) /// Its actual type is unknown, but it can have annotations. /// - sealed partial record GenericParameterValue : ValueWithDynamicallyAccessedMembers + internal sealed partial record GenericParameterValue : ValueWithDynamicallyAccessedMembers { public readonly GenericParameterProxy GenericParameter; } diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/HandleCallAction.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/HandleCallAction.cs index b8f3607827cbbe..51046d7a831ac0 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/HandleCallAction.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/HandleCallAction.cs @@ -19,13 +19,13 @@ namespace ILLink.Shared.TrimAnalysis { [StructLayout (LayoutKind.Auto)] // A good way to avoid CS0282, we don't really care about field order - partial struct HandleCallAction + internal partial struct HandleCallAction { - static ValueSetLattice MultiValueLattice => default; + private static ValueSetLattice MultiValueLattice => default; - readonly DiagnosticContext _diagnosticContext; - readonly FlowAnnotations _annotations; - readonly RequireDynamicallyAccessedMembersAction _requireDynamicallyAccessedMembersAction; + private readonly DiagnosticContext _diagnosticContext; + private readonly FlowAnnotations _annotations; + private readonly RequireDynamicallyAccessedMembersAction _requireDynamicallyAccessedMembersAction; public bool Invoke (MethodProxy calledMethod, MultiValue instanceValue, IReadOnlyList argumentValues, out MultiValue methodReturnValue, out IntrinsicId intrinsicId) { @@ -1198,7 +1198,7 @@ void AddReturnValue (MultiValue value) } } - IEnumerable ProcessGetMethodByName (TypeProxy type, string methodName, BindingFlags? bindingFlags) + private IEnumerable ProcessGetMethodByName (TypeProxy type, string methodName, BindingFlags? bindingFlags) { bool foundAny = false; foreach (var method in GetMethodsOnTypeHierarchy (type, methodName, bindingFlags)) { @@ -1215,7 +1215,7 @@ IEnumerable ProcessGetMethodByName (TypeProxy type, string methodNam yield return NullValue.Instance; } - bool AnalyzeGenericInstantiationTypeArray (in MultiValue arrayParam, in MethodProxy calledMethod, ImmutableArray genericParameters) + private bool AnalyzeGenericInstantiationTypeArray (in MultiValue arrayParam, in MethodProxy calledMethod, ImmutableArray genericParameters) { bool hasRequirements = false; foreach (var genericParameter in genericParameters) { @@ -1278,7 +1278,7 @@ static DynamicallyAccessedMemberTypes GetGenericParameterEffectiveMemberTypes (G } } - void ValidateGenericMethodInstantiation ( + private void ValidateGenericMethodInstantiation ( MethodProxy genericMethod, in MultiValue genericParametersArray, MethodProxy reflectionMethod) @@ -1293,7 +1293,7 @@ void ValidateGenericMethodInstantiation ( } } - ImmutableArray GetGenericParameterValues (ImmutableArray genericParameters) + private ImmutableArray GetGenericParameterValues (ImmutableArray genericParameters) { if (genericParameters.IsEmpty) return ImmutableArray.Empty; @@ -1305,7 +1305,7 @@ ImmutableArray GetGenericParameterValues (ImmutableArray< return builder.ToImmutableArray (); } - void ProcessCreateInstanceByName (MethodProxy calledMethod, IReadOnlyList argumentValues) + private void ProcessCreateInstanceByName (MethodProxy calledMethod, IReadOnlyList argumentValues) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; bool parameterlessConstructor = true; diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/IntrinsicId.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/IntrinsicId.cs index bd9d8df893a2c6..2b2713c65c7301 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/IntrinsicId.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/IntrinsicId.cs @@ -7,7 +7,7 @@ namespace ILLink.Shared.TrimAnalysis { [StaticCs.Closed] - enum IntrinsicId + internal enum IntrinsicId { None = 0, IntrospectionExtensions_GetTypeInfo, diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/Intrinsics.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/Intrinsics.cs index 654e851513cdde..2d772a54c60b20 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/Intrinsics.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/Intrinsics.cs @@ -8,7 +8,7 @@ namespace ILLink.Shared.TrimAnalysis { - static class Intrinsics + internal static class Intrinsics { public static IntrinsicId GetIntrinsicIdForMethod (MethodProxy calledMethod) { diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/KnownStringValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/KnownStringValue.cs index bbdedf5bf02dc6..b1cee312beefd2 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/KnownStringValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/KnownStringValue.cs @@ -11,7 +11,7 @@ namespace ILLink.Shared.TrimAnalysis /// /// A known string - such as the result of a ldstr. /// - sealed partial record KnownStringValue : SingleValue + internal sealed partial record KnownStringValue : SingleValue { public KnownStringValue (string contents) => Contents = contents; diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/MethodParameterValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/MethodParameterValue.cs index 8d2b4a6a64b4fd..29c042db79ad78 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/MethodParameterValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/MethodParameterValue.cs @@ -6,5 +6,5 @@ namespace ILLink.Shared.TrimAnalysis { - sealed partial record MethodParameterValue : ValueWithDynamicallyAccessedMembers; + internal sealed partial record MethodParameterValue : ValueWithDynamicallyAccessedMembers; } diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/MethodReturnValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/MethodReturnValue.cs index 708b5f469c39b7..915234337e873c 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/MethodReturnValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/MethodReturnValue.cs @@ -6,5 +6,5 @@ namespace ILLink.Shared.TrimAnalysis { - sealed partial record class MethodReturnValue : ValueWithDynamicallyAccessedMembers; + internal sealed partial record class MethodReturnValue : ValueWithDynamicallyAccessedMembers; } diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/MethodThisParameterValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/MethodThisParameterValue.cs index baf12d256d8fb2..5339529c80de12 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/MethodThisParameterValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/MethodThisParameterValue.cs @@ -6,5 +6,5 @@ namespace ILLink.Shared.TrimAnalysis { - sealed partial record MethodThisParameterValue : ValueWithDynamicallyAccessedMembers; + internal sealed partial record MethodThisParameterValue : ValueWithDynamicallyAccessedMembers; } diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/NullValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/NullValue.cs index 90afd5a87929f3..0e354bf19be56d 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/NullValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/NullValue.cs @@ -8,7 +8,7 @@ namespace ILLink.Shared.TrimAnalysis { - sealed record NullValue : SingleValue + internal sealed record NullValue : SingleValue { private NullValue () { diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/NullableSystemTypeValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/NullableSystemTypeValue.cs index 1f54cc2779bf16..f08d97bafb65cd 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/NullableSystemTypeValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/NullableSystemTypeValue.cs @@ -14,7 +14,7 @@ namespace ILLink.Shared.TrimAnalysis /// This represents a Nullable where T is a known SystemTypeValue. /// It is necessary to track the underlying type to propagate DynamicallyAccessedMembers annotations to the underlying type when applied to a Nullable. /// - sealed record NullableSystemTypeValue : SingleValue + internal sealed record NullableSystemTypeValue : SingleValue { public NullableSystemTypeValue (in TypeProxy nullableType, in SystemTypeValue underlyingTypeValue) { diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/NullableValueWithDynamicallyAccessedMembers.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/NullableValueWithDynamicallyAccessedMembers.cs index 4c09d6f7f173f2..38983bd9aec79a 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/NullableValueWithDynamicallyAccessedMembers.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/NullableValueWithDynamicallyAccessedMembers.cs @@ -13,10 +13,10 @@ namespace ILLink.Shared.TrimAnalysis { /// - /// This represents a Nullable where T is an unknown value with DynamicallyAccessedMembers annotations. + /// This represents a Nullable where T is an unknown value with DynamicallyAccessedMembers annotations. /// It is necessary to track the underlying type to ensure DynamicallyAccessedMembers annotations on the underlying type match the target parameters where the Nullable is used. /// - sealed record NullableValueWithDynamicallyAccessedMembers : ValueWithDynamicallyAccessedMembers + internal sealed record NullableValueWithDynamicallyAccessedMembers : ValueWithDynamicallyAccessedMembers { public NullableValueWithDynamicallyAccessedMembers (in TypeProxy nullableType, in ValueWithDynamicallyAccessedMembers underlyingTypeValue) { diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ReferenceKind.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ReferenceKind.cs index 1c46b2dbeba0b9..7355ef8f4ec457 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ReferenceKind.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ReferenceKind.cs @@ -11,4 +11,4 @@ public enum ReferenceKind Out, None } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RequireDynamicallyAccessedMembersAction.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RequireDynamicallyAccessedMembersAction.cs index 9eb5db78804f55..b706ca8bc13ffd 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RequireDynamicallyAccessedMembersAction.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RequireDynamicallyAccessedMembersAction.cs @@ -14,9 +14,9 @@ namespace ILLink.Shared.TrimAnalysis { [StructLayout (LayoutKind.Auto)] - partial struct RequireDynamicallyAccessedMembersAction + internal partial struct RequireDynamicallyAccessedMembersAction { - readonly DiagnosticContext _diagnosticContext; + private readonly DiagnosticContext _diagnosticContext; public void Invoke (in MultiValue value, ValueWithDynamicallyAccessedMembers targetValue) { diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeMethodHandleValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeMethodHandleValue.cs index 7ef048f224b5bd..f8e0029e05094d 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeMethodHandleValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeMethodHandleValue.cs @@ -12,7 +12,7 @@ namespace ILLink.Shared.TrimAnalysis /// /// This is the System.RuntimeMethodHandle equivalent to a node. /// - sealed partial record RuntimeMethodHandleValue : SingleValue + internal sealed partial record RuntimeMethodHandleValue : SingleValue { public RuntimeMethodHandleValue (in MethodProxy representedMethod) { diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleForGenericParameterValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleForGenericParameterValue.cs index 1eb108e5faeaee..c6b82ccc808ce2 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleForGenericParameterValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleForGenericParameterValue.cs @@ -12,7 +12,7 @@ namespace ILLink.Shared.TrimAnalysis /// /// This is the System.RuntimeTypeHandle equivalent to a node. /// - sealed record RuntimeTypeHandleForGenericParameterValue : SingleValue + internal sealed record RuntimeTypeHandleForGenericParameterValue : SingleValue { public readonly GenericParameterProxy GenericParameter; diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleForNullableSystemTypeValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleForNullableSystemTypeValue.cs index c92d4274b2d917..f85536aeb4a5e1 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleForNullableSystemTypeValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleForNullableSystemTypeValue.cs @@ -14,7 +14,7 @@ namespace ILLink.Shared.TrimAnalysis /// This represents a type handle Nullable where T is a known SystemTypeValue. /// It is necessary to track the underlying type to propagate DynamicallyAccessedMembers annotations to the underlying type when applied to a Nullable. /// - sealed record RuntimeTypeHandleForNullableSystemTypeValue : SingleValue + internal sealed record RuntimeTypeHandleForNullableSystemTypeValue : SingleValue { public RuntimeTypeHandleForNullableSystemTypeValue (in TypeProxy nullableType, in SystemTypeValue underlyingTypeValue) { diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleForNullableValueWithDynamicallyAccessedMembers.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleForNullableValueWithDynamicallyAccessedMembers.cs index b4b0653931d072..968e55fcd3cf3a 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleForNullableValueWithDynamicallyAccessedMembers.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleForNullableValueWithDynamicallyAccessedMembers.cs @@ -11,10 +11,10 @@ namespace ILLink.Shared.TrimAnalysis { /// - /// This represents a type handle of a Nullable where T is an unknown value with DynamicallyAccessedMembers annotations. + /// This represents a type handle of a Nullable where T is an unknown value with DynamicallyAccessedMembers annotations. /// It is necessary to track the underlying type to ensure DynamicallyAccessedMembers annotations on the underlying type match the target parameters where the Nullable is used. /// - sealed record RuntimeTypeHandleForNullableValueWithDynamicallyAccessedMembers : SingleValue + internal sealed record RuntimeTypeHandleForNullableValueWithDynamicallyAccessedMembers : SingleValue { public RuntimeTypeHandleForNullableValueWithDynamicallyAccessedMembers (in TypeProxy nullableType, in SingleValue underlyingTypeValue) { @@ -26,7 +26,7 @@ public RuntimeTypeHandleForNullableValueWithDynamicallyAccessedMembers (in TypeP public readonly TypeProxy NullableType; public readonly SingleValue UnderlyingTypeValue; - public override SingleValue DeepCopy () => this; // This value is immutable } + public override SingleValue DeepCopy () => this; // This value is immutable public override string ToString () => this.ValueToString (UnderlyingTypeValue, NullableType); } diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleValue.cs index c508c1f784dcab..3e9cbccf7c1ea1 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/RuntimeTypeHandleValue.cs @@ -12,7 +12,7 @@ namespace ILLink.Shared.TrimAnalysis /// /// This is the System.RuntimeTypeHandle equivalent to a node. /// - sealed record RuntimeTypeHandleValue : SingleValue + internal sealed record RuntimeTypeHandleValue : SingleValue { public RuntimeTypeHandleValue (in TypeProxy representedType) { diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/SystemReflectionMethodBaseValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/SystemReflectionMethodBaseValue.cs index 3ef755cb7aae8f..ac3d0ec89fd6c4 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/SystemReflectionMethodBaseValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/SystemReflectionMethodBaseValue.cs @@ -12,7 +12,7 @@ namespace ILLink.Shared.TrimAnalysis /// /// This is a known System.Reflection.MethodBase value. MethodRepresented is the 'value' of the MethodBase. /// - sealed partial record SystemReflectionMethodBaseValue : SingleValue + internal sealed partial record SystemReflectionMethodBaseValue : SingleValue { public SystemReflectionMethodBaseValue (MethodProxy representedMethod) => RepresentedMethod = representedMethod; diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/SystemTypeValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/SystemTypeValue.cs index 71af91c4e56dc6..796c4333caa3e9 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/SystemTypeValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/SystemTypeValue.cs @@ -12,7 +12,7 @@ namespace ILLink.Shared.TrimAnalysis /// /// This is a known System.Type value. TypeRepresented is the 'value' of the System.Type. /// - sealed record SystemTypeValue : SingleValue + internal sealed record SystemTypeValue : SingleValue { public SystemTypeValue (in TypeProxy representedType) { diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/UnknownValue.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/UnknownValue.cs index 7dc49dc6662767..863d757d4ccd4e 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/UnknownValue.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/UnknownValue.cs @@ -8,7 +8,7 @@ namespace ILLink.Shared.TrimAnalysis { - sealed record UnknownValue : SingleValue + internal sealed record UnknownValue : SingleValue { private UnknownValue () { diff --git a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ValueExtensions.cs b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ValueExtensions.cs index d9358f2910f1b1..0e7643a8d5d439 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ValueExtensions.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TrimAnalysis/ValueExtensions.cs @@ -11,7 +11,7 @@ namespace ILLink.Shared.TrimAnalysis { - static partial class ValueExtensions + internal static partial class ValueExtensions { internal static string ValueToString (this SingleValue value, params object[] args) { @@ -20,15 +20,15 @@ internal static string ValueToString (this SingleValue value, params object[] ar StringBuilder sb = new (); sb.Append (value.GetType ().Name); - sb.Append ("("); + sb.Append ('('); if (args != null) { for (int i = 0; i < args.Length; i++) { if (i > 0) - sb.Append (","); + sb.Append (','); sb.Append (args[i] == null ? "" : args[i].ToString ()); } } - sb.Append (")"); + sb.Append (')'); return sb.ToString (); } diff --git a/src/coreclr/tools/aot/ILLink.Shared/TypeSystemProxy/IMemberProxy.cs b/src/coreclr/tools/aot/ILLink.Shared/TypeSystemProxy/IMemberProxy.cs index 3e358b9a5b85ee..7f4882ee037620 100644 --- a/src/coreclr/tools/aot/ILLink.Shared/TypeSystemProxy/IMemberProxy.cs +++ b/src/coreclr/tools/aot/ILLink.Shared/TypeSystemProxy/IMemberProxy.cs @@ -6,7 +6,7 @@ namespace ILLink.Shared.TypeSystemProxy { - interface IMemberProxy + internal interface IMemberProxy { public string Name { get; } diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/BaseExpectedLinkedBehaviorAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/BaseExpectedLinkedBehaviorAttribute.cs index 9a963f61055715..c5fb5096a681d9 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/BaseExpectedLinkedBehaviorAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/BaseExpectedLinkedBehaviorAttribute.cs @@ -13,4 +13,4 @@ namespace Mono.Linker.Tests.Cases.Expectations.Assertions public abstract class BaseExpectedLinkedBehaviorAttribute : Attribute { } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/BaseMemberAssertionAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/BaseMemberAssertionAttribute.cs index 5afd16cfd6d9e1..61838421cfe484 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/BaseMemberAssertionAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/BaseMemberAssertionAttribute.cs @@ -12,4 +12,4 @@ namespace Mono.Linker.Tests.Cases.Expectations.Assertions public abstract class BaseMemberAssertionAttribute : Attribute { } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/CreatedMemberAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/CreatedMemberAttribute.cs index 9fdbb1938776e5..f9e95dbfa1aea7 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/CreatedMemberAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/CreatedMemberAttribute.cs @@ -15,4 +15,4 @@ public CreatedMemberAttribute (string name) throw new ArgumentException ("Value cannot be null or empty.", nameof (name)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/EnableLoggerAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/EnableLoggerAttribute.cs index 436281610fbebd..45d4b88fb21cba 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/EnableLoggerAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/EnableLoggerAttribute.cs @@ -6,4 +6,4 @@ namespace Mono.Linker.Tests.Cases.Expectations.Assertions public abstract class EnableLoggerAttribute : BaseExpectedLinkedBehaviorAttribute { } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectBodyModifiedAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectBodyModifiedAttribute.cs index dbe07219cf015c..f4f45f99cbc4d1 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectBodyModifiedAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectBodyModifiedAttribute.cs @@ -9,4 +9,4 @@ namespace Mono.Linker.Tests.Cases.Expectations.Assertions public class ExpectBodyModifiedAttribute : BaseInAssemblyAttribute { } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectExactlyResolvedDocumentationSignatureAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectExactlyResolvedDocumentationSignatureAttribute.cs index b618ed7a354867..e17d46377f0cc2 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectExactlyResolvedDocumentationSignatureAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectExactlyResolvedDocumentationSignatureAttribute.cs @@ -11,4 +11,4 @@ public ExpectExactlyResolvedDocumentationSignatureAttribute (string input) { } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectExceptionHandlersModifiedAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectExceptionHandlersModifiedAttribute.cs index a76e4b64897779..ef7f7f0216552e 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectExceptionHandlersModifiedAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectExceptionHandlersModifiedAttribute.cs @@ -9,4 +9,4 @@ namespace Mono.Linker.Tests.Cases.Expectations.Assertions public class ExpectExceptionHandlersModifiedAttribute : BaseInAssemblyAttribute { } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectGeneratedDocumentationSignatureAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectGeneratedDocumentationSignatureAttribute.cs index c25b2ff3d02624..0065c86d1ac294 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectGeneratedDocumentationSignatureAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectGeneratedDocumentationSignatureAttribute.cs @@ -11,4 +11,4 @@ public ExpectGeneratedDocumentationSignatureAttribute (string expected) { } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectLocalsModifiedAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectLocalsModifiedAttribute.cs index 56a30bd52d20cf..c6ef05f63cb070 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectLocalsModifiedAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectLocalsModifiedAttribute.cs @@ -9,4 +9,4 @@ namespace Mono.Linker.Tests.Cases.Expectations.Assertions public class ExpectLocalsModifiedAttribute : BaseInAssemblyAttribute { } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectResolvedDocumentationSignatureAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectResolvedDocumentationSignatureAttribute.cs index 5a3c16fe9bcc2d..39e2c6d5065b9f 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectResolvedDocumentationSignatureAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectResolvedDocumentationSignatureAttribute.cs @@ -11,4 +11,4 @@ public ExpectResolvedDocumentationSignatureAttribute (string input) { } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectUnresolvedDocumentationSignatureAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectUnresolvedDocumentationSignatureAttribute.cs index aea9068451bcc1..dd2cd32b0b4458 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectUnresolvedDocumentationSignatureAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectUnresolvedDocumentationSignatureAttribute.cs @@ -11,4 +11,4 @@ public ExpectUnresolvedDocumentationSignatureAttribute (string expected) { } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectedInstructionSequenceAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectedInstructionSequenceAttribute.cs index 35ead6966a4f62..5883066e838dca 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectedInstructionSequenceAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectedInstructionSequenceAttribute.cs @@ -14,4 +14,4 @@ public ExpectedInstructionSequenceAttribute (string[] opCodes) throw new ArgumentNullException (nameof (opCodes)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectedInstructionSequenceOnMemberInAssemblyAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectedInstructionSequenceOnMemberInAssemblyAttribute.cs index 899b979c5211e8..9da84991530811 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectedInstructionSequenceOnMemberInAssemblyAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectedInstructionSequenceOnMemberInAssemblyAttribute.cs @@ -32,4 +32,4 @@ public ExpectedInstructionSequenceOnMemberInAssemblyAttribute (string assemblyFi throw new ArgumentNullException (nameof (opCodes)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectedLocalsSequenceAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectedLocalsSequenceAttribute.cs index fdd3441b71f44f..99a4839fab8ce3 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectedLocalsSequenceAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/ExpectedLocalsSequenceAttribute.cs @@ -20,4 +20,4 @@ public ExpectedLocalsSequenceAttribute (Type[] types) throw new ArgumentNullException (nameof (types)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/IgnoreTestCaseAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/IgnoreTestCaseAttribute.cs index 78fd0e45374232..753e4a6fb11bf6 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/IgnoreTestCaseAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/IgnoreTestCaseAttribute.cs @@ -15,4 +15,4 @@ public IgnoreTestCaseAttribute (string reason) throw new ArgumentNullException (nameof (reason)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAllTypesAndMembersInAssemblyAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAllTypesAndMembersInAssemblyAttribute.cs index ffdb9d07c2e0a5..0c44aadca49554 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAllTypesAndMembersInAssemblyAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAllTypesAndMembersInAssemblyAttribute.cs @@ -14,4 +14,4 @@ public KeptAllTypesAndMembersInAssemblyAttribute (string assemblyFileName) throw new ArgumentException ("Value cannot be null or empty.", nameof (assemblyFileName)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAssemblyAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAssemblyAttribute.cs index 9103fa1c31763e..d75844581fb083 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAssemblyAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAssemblyAttribute.cs @@ -18,4 +18,4 @@ public KeptAssemblyAttribute (string fileName) throw new ArgumentException ("Value cannot be null or empty.", nameof (fileName)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAttribute.cs index 922123f7d11bd0..179ea77e5d7bd9 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAttribute.cs @@ -9,4 +9,4 @@ namespace Mono.Linker.Tests.Cases.Expectations.Assertions public class KeptAttribute : BaseExpectedLinkedBehaviorAttribute { } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAttributeInAssemblyAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAttributeInAssemblyAttribute.cs index 91081f68a1416b..1fe5699ff61bbc 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAttributeInAssemblyAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAttributeInAssemblyAttribute.cs @@ -68,4 +68,4 @@ public KeptAttributeInAssemblyAttribute (string assemblyName, Type attributeType { } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAttributeOnFixedBufferTypeAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAttributeOnFixedBufferTypeAttribute.cs index 0fc56741a8ca42..f8ab0bdb3593f9 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAttributeOnFixedBufferTypeAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptAttributeOnFixedBufferTypeAttribute.cs @@ -20,4 +20,4 @@ public KeptAttributeOnFixedBufferTypeAttribute (Type type) throw new ArgumentNullException (nameof (type)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptBaseOnTypeInAssemblyAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptBaseOnTypeInAssemblyAttribute.cs index acac5d575bbcea..84957dbc36fa2a 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptBaseOnTypeInAssemblyAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptBaseOnTypeInAssemblyAttribute.cs @@ -34,4 +34,4 @@ public KeptBaseOnTypeInAssemblyAttribute (string assemblyFileName, string typeNa throw new ArgumentException ("Value cannot be null or empty.", nameof (baseTypeName)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptBaseTypeAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptBaseTypeAttribute.cs index c4e4a24889542c..673795e134b5a3 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptBaseTypeAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptBaseTypeAttribute.cs @@ -22,4 +22,4 @@ public KeptBaseTypeAttribute (Type baseType, params object[] typeArguments) throw new ArgumentNullException (nameof (typeArguments)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptFixedBufferAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptFixedBufferAttribute.cs index d0067544ad7609..18b1bef2fdd082 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptFixedBufferAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptFixedBufferAttribute.cs @@ -9,4 +9,4 @@ namespace Mono.Linker.Tests.Cases.Expectations.Assertions public class KeptFixedBufferAttribute : KeptAttribute { } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptInitializerData.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptInitializerData.cs index 25b8c8261f16ce..c52323dac4086d 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptInitializerData.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptInitializerData.cs @@ -19,4 +19,4 @@ public KeptInitializerData (int occurrenceIndexInBody) throw new ArgumentOutOfRangeException (nameof (occurrenceIndexInBody)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptInterfaceAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptInterfaceAttribute.cs index 85279abcd83f6d..35403cfd004c76 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptInterfaceAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptInterfaceAttribute.cs @@ -23,4 +23,4 @@ public KeptInterfaceAttribute (Type interfaceType, params object[] typeArguments throw new ArgumentNullException (nameof (typeArguments)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptInterfaceOnTypeInAssemblyAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptInterfaceOnTypeInAssemblyAttribute.cs index 2741439facc88d..bf5065968570fd 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptInterfaceOnTypeInAssemblyAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptInterfaceOnTypeInAssemblyAttribute.cs @@ -34,4 +34,4 @@ public KeptInterfaceOnTypeInAssemblyAttribute (string assemblyFileName, string t throw new ArgumentException ("Value cannot be null or empty.", nameof (interfaceTypeName)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptMemberAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptMemberAttribute.cs index 6f7adcf30bedba..d30d195f804703 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptMemberAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptMemberAttribute.cs @@ -15,4 +15,4 @@ public KeptMemberAttribute (string name) throw new ArgumentException ("Value cannot be null or empty.", nameof (name)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptPrivateImplementationDetails.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptPrivateImplementationDetails.cs index a410eb2f50bbce..ad7576345a34a9 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptPrivateImplementationDetails.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptPrivateImplementationDetails.cs @@ -14,4 +14,4 @@ public KeptPrivateImplementationDetailsAttribute (string methodName) throw new ArgumentException ("Value cannot be null or empty.", nameof (methodName)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptReferenceAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptReferenceAttribute.cs index f4bb464260dba8..554bc8d7ae3f20 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptReferenceAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptReferenceAttribute.cs @@ -17,4 +17,4 @@ public KeptReferenceAttribute (string name) throw new ArgumentException ("Value cannot be null or empty.", nameof (name)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptReferencesInAssemblyAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptReferencesInAssemblyAttribute.cs index 0265b9f3a40d9f..b075864265333e 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptReferencesInAssemblyAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptReferencesInAssemblyAttribute.cs @@ -17,4 +17,4 @@ public KeptReferencesInAssemblyAttribute (string assemblyFileName, string[] expe throw new ArgumentNullException (nameof (expectedReferenceAssemblyNames)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptSymbolsAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptSymbolsAttribute.cs index 3e435017b8b57b..3cfcee17bbcf2f 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptSymbolsAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/KeptSymbolsAttribute.cs @@ -14,4 +14,4 @@ public KeptSymbolsAttribute (string assemblyFileName) throw new ArgumentException ("Value cannot be null or empty.", nameof (assemblyFileName)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedAssemblyAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedAssemblyAttribute.cs index e1dc4c0e1e36a2..9258217230a3cd 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedAssemblyAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedAssemblyAttribute.cs @@ -18,4 +18,4 @@ public RemovedAssemblyAttribute (string fileName) throw new ArgumentException ("Value cannot be null or empty.", nameof (fileName)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedAttributeInAssembly.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedAttributeInAssembly.cs index 591aa81b40f0ea..4e05c1e7ae95d3 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedAttributeInAssembly.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedAttributeInAssembly.cs @@ -68,4 +68,4 @@ public RemovedAttributeInAssembly (string assemblyName, Type attributeType, Type { } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedInterfaceOnTypeInAssemblyAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedInterfaceOnTypeInAssemblyAttribute.cs index 70465fc3d6035f..a0bd1c5fc62dd5 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedInterfaceOnTypeInAssemblyAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedInterfaceOnTypeInAssemblyAttribute.cs @@ -34,4 +34,4 @@ public RemovedInterfaceOnTypeInAssemblyAttribute (string assemblyFileName, strin throw new ArgumentException ("Value cannot be null or empty.", nameof (interfaceTypeName)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedPseudoAttributeAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedPseudoAttributeAttribute.cs index 00b4eb588eaf70..fd2198aac8b71d 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedPseudoAttributeAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedPseudoAttributeAttribute.cs @@ -12,4 +12,4 @@ public RemovedPseudoAttributeAttribute (uint value) { } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedSymbolsAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedSymbolsAttribute.cs index 1549b8a03c9f17..1557a837586ad8 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedSymbolsAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Assertions/RemovedSymbolsAttribute.cs @@ -14,4 +14,4 @@ public RemovedSymbolsAttribute (string assemblyFileName) throw new ArgumentException ("Value cannot be null or empty.", nameof (assemblyFileName)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Helpers/PlatformAssemblies.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Helpers/PlatformAssemblies.cs index c2e77e98f8d445..03643715f05359 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Helpers/PlatformAssemblies.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Helpers/PlatformAssemblies.cs @@ -11,4 +11,4 @@ public static class PlatformAssemblies public const string CoreLib = "mscorlib.dll"; #endif } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/NotATestCaseAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/NotATestCaseAttribute.cs index a099ee6301a4b5..67881a49a88a8b 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/NotATestCaseAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/NotATestCaseAttribute.cs @@ -9,4 +9,4 @@ namespace Mono.Linker.Tests.Cases.Expectations.Metadata public class NotATestCaseAttribute : BaseMetadataAttribute { } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/ReferenceDependencyAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/ReferenceDependencyAttribute.cs index c038fe43f75048..9f810958164f0f 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/ReferenceDependencyAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/ReferenceDependencyAttribute.cs @@ -14,4 +14,4 @@ public ReferenceDependencyAttribute (string value) throw new ArgumentException ("Value cannot be null or empty.", nameof (value)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SandboxDependencyAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SandboxDependencyAttribute.cs index dce29bd3170bbc..93b906161f0874 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SandboxDependencyAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SandboxDependencyAttribute.cs @@ -21,4 +21,4 @@ public SandboxDependencyAttribute (Type typeOfSourceFileToInclude, string destin throw new ArgumentException ("Value cannot be null or empty.", nameof (typeOfSourceFileToInclude)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupCompileAsLibraryAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupCompileAsLibraryAttribute.cs index e78aaa089bcc3c..0d44529ff2c7a6 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupCompileAsLibraryAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupCompileAsLibraryAttribute.cs @@ -9,4 +9,4 @@ namespace Mono.Linker.Tests.Cases.Expectations.Metadata public class SetupCompileAsLibraryAttribute : BaseMetadataAttribute { } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupCompileAssemblyNameAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupCompileAssemblyNameAttribute.cs index 7fad90431149d6..5bd0d8613ad791 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupCompileAssemblyNameAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupCompileAssemblyNameAttribute.cs @@ -14,4 +14,4 @@ public SetupCompileAssemblyNameAttribute (string outputName) throw new ArgumentNullException (nameof (outputName)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerArgumentAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerArgumentAttribute.cs index 6f2e55f24bba27..0f81a06fe7949a 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerArgumentAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerArgumentAttribute.cs @@ -8,7 +8,7 @@ namespace Mono.Linker.Tests.Cases.Expectations.Metadata /// /// Used to define arguments to pass to the linker. - /// + /// /// Don't use this attribute to setup single character flags. These flags do a poor job of communicating their purpose /// and although we need to continue to support the usages that exist today, that doesn't mean we need to make our tests harder to read /// diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerDefaultActionAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerDefaultActionAttribute.cs index ee9794d495f98c..422a0cb469afe3 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerDefaultActionAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerDefaultActionAttribute.cs @@ -14,4 +14,4 @@ public SetupLinkerDefaultActionAttribute (string action) throw new ArgumentNullException (nameof (action)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerKeepDebugMembersAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerKeepDebugMembersAttribute.cs index 2213b9cc551c79..94d036e4347187 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerKeepDebugMembersAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerKeepDebugMembersAttribute.cs @@ -14,4 +14,4 @@ public SetupLinkerKeepDebugMembersAttribute (string value) throw new ArgumentException ("Value cannot be null or empty.", nameof (value)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerLinkPublicAndFamilyAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerLinkPublicAndFamilyAttribute.cs index c4250b82e231da..70d407928a4a35 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerLinkPublicAndFamilyAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerLinkPublicAndFamilyAttribute.cs @@ -9,4 +9,4 @@ namespace Mono.Linker.Tests.Cases.Expectations.Metadata public class SetupLinkerLinkPublicAndFamilyAttribute : BaseMetadataAttribute { } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerResponseFileAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerResponseFileAttribute.cs index 28c30f868bcda3..1226e91894e862 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerResponseFileAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerResponseFileAttribute.cs @@ -14,4 +14,4 @@ public SetupLinkerResponseFileAttribute (string relativePathToFile, string desti throw new ArgumentException ("Value cannot be null or empty.", nameof (relativePathToFile)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerSubstitutionFileAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerSubstitutionFileAttribute.cs index 6a102a830fa163..e27f6e8182a602 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerSubstitutionFileAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Metadata/SetupLinkerSubstitutionFileAttribute.cs @@ -14,4 +14,4 @@ public SetupLinkerSubstitutionFileAttribute (string relativePathToFile, string d throw new ArgumentException ("Value cannot be null or empty.", nameof (relativePathToFile)); } } -} \ No newline at end of file +} diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Mono.Linker.Tests.Cases.Expectations.csproj b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Mono.Linker.Tests.Cases.Expectations.csproj index 14a94ab30bf27c..104c5d7562d534 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Mono.Linker.Tests.Cases.Expectations.csproj +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Mono.Linker.Tests.Cases.Expectations.csproj @@ -5,6 +5,7 @@ disable x64;x86 AnyCPU + true diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Support/RemoveAttributeInstancesAttribute.cs b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Support/RemoveAttributeInstancesAttribute.cs index e2eb936d545f85..c1ff585a6f5de6 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Support/RemoveAttributeInstancesAttribute.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases.Expectations/Support/RemoveAttributeInstancesAttribute.cs @@ -6,7 +6,7 @@ namespace Mono.Linker { /// - /// This attribute name will be the name hardcoded in linker which will remove all + /// This attribute name will be the name hardcoded in linker which will remove all /// attribute usages but not the attribute definition /// [AttributeUsage ( diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases/Mono.Linker.Tests.Cases.csproj b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases/Mono.Linker.Tests.Cases.csproj index ec237817f2901f..1e6202665c685f 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests.Cases/Mono.Linker.Tests.Cases.csproj +++ b/src/coreclr/tools/aot/Mono.Linker.Tests.Cases/Mono.Linker.Tests.Cases.csproj @@ -8,6 +8,7 @@ $(DefineConstants);INCLUDE_EXPECTATIONS 0 0 + true diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/Extensions/CecilExtensions.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/Extensions/CecilExtensions.cs index f88c4d8cf177fd..763cec9c4c776d 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/Extensions/CecilExtensions.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/Extensions/CecilExtensions.cs @@ -118,7 +118,9 @@ public static bool DerivesFrom (this TypeDefinition type, string baseTypeName) public static PropertyDefinition GetPropertyDefinition (this MethodDefinition method) { if (!method.IsSetter && !method.IsGetter) +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentException (); +#pragma warning restore CA2208 // Instantiate argument exceptions correctly var propertyName = method.Name.Substring (4); return method.DeclaringType.Properties.First (p => p.Name == propertyName); @@ -132,7 +134,7 @@ public static string GetSignature (this MethodDefinition method) builder.Append ($"<#{method.GenericParameters.Count}>"); } - builder.Append ("("); + builder.Append ('('); if (method.HasParameters) { for (int i = 0; i < method.Parameters.Count - 1; i++) { @@ -144,7 +146,7 @@ public static string GetSignature (this MethodDefinition method) builder.Append (method.Parameters[method.Parameters.Count - 1].ParameterType); } - builder.Append (")"); + builder.Append (')'); return builder.ToString (); } @@ -200,7 +202,7 @@ public static string GetDisplayName (this MethodReference method) } // Append parameters - sb.Append ("("); + sb.Append ('('); if (method.HasParameters) { for (int i = 0; i < method.Parameters.Count - 1; i++) sb.Append (method.Parameters[i].ParameterType.GetDisplayNameWithoutNamespace ()).Append (", "); @@ -208,7 +210,7 @@ public static string GetDisplayName (this MethodReference method) sb.Append (method.Parameters[method.Parameters.Count - 1].ParameterType.GetDisplayNameWithoutNamespace ()); } - sb.Append (")"); + sb.Append (')'); // Insert generic parameters if (method.HasGenericParameters) { @@ -250,7 +252,7 @@ public static string GetDisplayName (this FieldReference field) var builder = new StringBuilder (); if (field.DeclaringType != null) { builder.Append (field.DeclaringType.GetDisplayName ()); - builder.Append ("."); + builder.Append ('.'); } builder.Append (field.Name); @@ -328,7 +330,7 @@ public static void PrependGenericParameters (IList genericPara sb.Insert (0, '<'); } - static void PrependGenericArguments (Stack genericArguments, int argumentsToTake, StringBuilder sb) + private static void PrependGenericArguments (Stack genericArguments, int argumentsToTake, StringBuilder sb) { sb.Insert (0, '>').Insert (0, genericArguments.Pop ().GetDisplayNameWithoutNamespace ().ToString ()); while (--argumentsToTake > 0) @@ -337,7 +339,7 @@ static void PrependGenericArguments (Stack genericArguments, int sb.Insert (0, '<'); } - static void AppendArrayType (ArrayType arrayType, StringBuilder sb) + private static void AppendArrayType (ArrayType arrayType, StringBuilder sb) { void parseArrayDimensions (ArrayType at) { diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/Extensions/NiceIO.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/Extensions/NiceIO.cs index 9272ffc026c03e..cb2f8e78c15e8e 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/Extensions/NiceIO.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/Extensions/NiceIO.cs @@ -48,13 +48,15 @@ public class NPath : IEquatable, IComparable public NPath (string path) { if (path == null) +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException (); +#pragma warning restore CA2208 // Instantiate argument exceptions correctly path = ParseDriveLetter (path, out _driveLetter); if (path == "/") { _isRelative = false; - _elements = new string[] { }; + _elements = Array.Empty (); } else { var split = path.Split ('/', '\\'); @@ -97,7 +99,7 @@ private static bool HasNonDotDotLastElement (List stack) return stack.Count > 0 && stack[stack.Count - 1] != ".."; } - private string ParseDriveLetter (string path, out string? driveLetter) + private static string ParseDriveLetter (string path, out string? driveLetter) { if (path.Length >= 2 && path[1] == ':') { driveLetter = path[0].ToString (); @@ -242,7 +244,7 @@ public string ExtensionWithDot { var last = _elements.Last (); var index = last.LastIndexOf ("."); - if (index < 0) return String.Empty; + if (index < 0) return string.Empty; return last.Substring (index); } } @@ -274,7 +276,7 @@ public string ToString (SlashMode slashMode) var sb = new StringBuilder (); if (_driveLetter != null) { sb.Append (_driveLetter); - sb.Append (":"); + sb.Append (':'); } if (!_isRelative) sb.Append (Slash (slashMode)); @@ -294,7 +296,7 @@ public static implicit operator string (NPath path) return path.ToString (); } - static char Slash (SlashMode slashMode) + private static char Slash (SlashMode slashMode) { return slashMode switch { SlashMode.Backward => '\\', @@ -303,7 +305,7 @@ static char Slash (SlashMode slashMode) }; } - public override bool Equals (Object? obj) + public override bool Equals (object? obj) { if (obj == null) return false; @@ -379,8 +381,8 @@ public int CompareTo (object? obj) public bool HasExtension (params string[] extensions) { - var extensionWithDotLower = ExtensionWithDot.ToLower (); - return extensions.Any (e => WithDot (e).ToLower () == extensionWithDotLower); + var extensionWithDotLower = ExtensionWithDot.ToLowerInvariant (); + return extensions.Any (e => WithDot (e).ToLowerInvariant () == extensionWithDotLower); } private static string WithDot (string extension) @@ -439,7 +441,7 @@ public NPath CreateFile () ThrowIfRelative (); ThrowIfRoot (); EnsureParentDirectoryExists (); - File.WriteAllBytes (ToString (), new byte[0]); + File.WriteAllBytes (ToString (), Array.Empty ()); return this; } @@ -511,10 +513,10 @@ public NPath MakeAbsolute () if (!IsRelative) return this; - return NPath.CurrentDirectory.Combine (this); + return CurrentDirectory.Combine (this); } - NPath? CopyWithDeterminedDestination (NPath absoluteDestination, Func fileFilter) + private NPath? CopyWithDeterminedDestination (NPath absoluteDestination, Func fileFilter) { if (absoluteDestination.IsRelative) throw new ArgumentException ("absoluteDestination must be absolute"); @@ -792,7 +794,7 @@ public IEnumerable MoveFiles (NPath destination, bool recurse, Func file.Move (destination.Combine (file.RelativeTo (this)))).ToArray (); } - static bool AlwaysTrue (NPath p) + private static bool AlwaysTrue (NPath p) { return true; } diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/Mono.Linker.Tests.csproj b/src/coreclr/tools/aot/Mono.Linker.Tests/Mono.Linker.Tests.csproj index 479c971ed03fd7..e82fddf45fb444 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/Mono.Linker.Tests.csproj +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/Mono.Linker.Tests.csproj @@ -11,6 +11,7 @@ linux-x64;win-x64;osx-x64 Debug;Release;Checked + true diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCases/TestDatabase.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCases/TestDatabase.cs index 71c527c459d772..dc580c55f081c9 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCases/TestDatabase.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCases/TestDatabase.cs @@ -41,10 +41,9 @@ public static NPath TestCasesRootDirectory { } } - static IEnumerable AllCases () + private static IEnumerable AllCases () { - if (_cachedAllCases == null) - _cachedAllCases = CreateCollector () + _cachedAllCases ??= CreateCollector () .Collect () .Where (c => c != null) .OrderBy (c => c.DisplayName) @@ -58,7 +57,7 @@ static IEnumerable AllCases () return AllCases ().FirstOrDefault (c => c.Name == name); } - static IEnumerable TestNamesBySuiteName (string suiteName) + private static IEnumerable TestNamesBySuiteName (string suiteName) { return AllCases () .Where (c => c.TestSuiteDirectory.FileName == suiteName) @@ -67,7 +66,7 @@ static IEnumerable TestNamesBySuiteName (string suiteName) .Select (c => new object[] { c }); } - static void GetDirectoryPaths (out string rootSourceDirectory, out string testCaseAssemblyPath) + private static void GetDirectoryPaths (out string rootSourceDirectory, out string testCaseAssemblyPath) { rootSourceDirectory = Path.GetFullPath (Path.Combine (PathUtilities.GetTestsSourceRootDirectory (), "Mono.Linker.Tests.Cases")); testCaseAssemblyPath = PathUtilities.GetTestAssemblyPath ("Mono.Linker.Tests.Cases"); diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/AssemblyChecker.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/AssemblyChecker.cs index f84265206067a9..1e2836d080e286 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/AssemblyChecker.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/AssemblyChecker.cs @@ -16,13 +16,12 @@ namespace Mono.Linker.Tests.TestCasesRunner { public class AssemblyChecker { - readonly AssemblyDefinition originalAssembly, linkedAssembly; - - HashSet linkedMembers; - readonly HashSet verifiedGeneratedFields = new HashSet (); - readonly HashSet verifiedEventMethods = new HashSet (); - readonly HashSet verifiedGeneratedTypes = new HashSet (); - bool checkNames; + private readonly AssemblyDefinition originalAssembly, linkedAssembly; + private HashSet linkedMembers; + private readonly HashSet verifiedGeneratedFields = new HashSet (); + private readonly HashSet verifiedEventMethods = new HashSet (); + private readonly HashSet verifiedGeneratedTypes = new HashSet (); + private bool checkNames; public AssemblyChecker (AssemblyDefinition original, AssemblyDefinition linked) { @@ -188,7 +187,7 @@ protected virtual void VerifyTypeDefinitionKept (TypeDefinition original, TypeDe } } - void VerifyBaseType (TypeDefinition src, TypeDefinition linked) + private void VerifyBaseType (TypeDefinition src, TypeDefinition linked) { string expectedBaseName; var expectedBaseGenericAttr = src.CustomAttributes.FirstOrDefault (w => w.AttributeType.Name == nameof (KeptBaseTypeAttribute) && w.ConstructorArguments.Count > 1); @@ -204,7 +203,7 @@ void VerifyBaseType (TypeDefinition src, TypeDefinition linked) } } - void VerifyInterfaces (TypeDefinition src, TypeDefinition linked) + private void VerifyInterfaces (TypeDefinition src, TypeDefinition linked) { var expectedInterfaces = new HashSet (src.CustomAttributes .Where (w => w.AttributeType.Name == nameof (KeptInterfaceAttribute)) @@ -223,18 +222,18 @@ void VerifyInterfaces (TypeDefinition src, TypeDefinition linked) } } - static string FormatBaseOrInterfaceAttributeValue (CustomAttribute attr) + private static string FormatBaseOrInterfaceAttributeValue (CustomAttribute attr) { if (attr.ConstructorArguments.Count == 1) return attr.ConstructorArguments[0].Value.ToString ()!; StringBuilder builder = new StringBuilder (); builder.Append (attr.ConstructorArguments[0].Value); - builder.Append ("<"); + builder.Append ('<'); bool separator = false; foreach (var caa in (CustomAttributeArgument[]) attr.ConstructorArguments[1].Value) { if (separator) - builder.Append (","); + builder.Append (','); else separator = true; @@ -242,11 +241,11 @@ static string FormatBaseOrInterfaceAttributeValue (CustomAttribute attr) builder.Append (arg.Value); } - builder.Append (">"); + builder.Append ('>'); return builder.ToString (); } - void VerifyField (FieldDefinition src, FieldDefinition? linked) + private void VerifyField (FieldDefinition src, FieldDefinition? linked) { bool expectedKept = ShouldBeKept (src); @@ -260,14 +259,14 @@ void VerifyField (FieldDefinition src, FieldDefinition? linked) VerifyFieldKept (src, linked); } - void VerifyFieldKept (FieldDefinition src, FieldDefinition? linked) + private void VerifyFieldKept (FieldDefinition src, FieldDefinition? linked) { if (linked == null) { Assert.True (false, $"Field `{src}' should have been kept"); return; } - if (!object.Equals (src.Constant, linked.Constant)) { + if (!Equals (src.Constant, linked.Constant)) { Assert.True (false, $"Field '{src}' value doesn's match. Expected {src.Constant}, actual {linked.Constant}"); } @@ -275,7 +274,7 @@ void VerifyFieldKept (FieldDefinition src, FieldDefinition? linked) VerifyCustomAttributes (src, linked); } - void VerifyProperty (PropertyDefinition src, PropertyDefinition? linked, TypeDefinition linkedType) + private void VerifyProperty (PropertyDefinition src, PropertyDefinition? linked, TypeDefinition linkedType) { VerifyMemberBackingField (src, linkedType); @@ -301,7 +300,7 @@ void VerifyProperty (PropertyDefinition src, PropertyDefinition? linked, TypeDef VerifyCustomAttributes (src, linked); } - void VerifyEvent (EventDefinition src, EventDefinition? linked, TypeDefinition linkedType) + private void VerifyEvent (EventDefinition src, EventDefinition? linked, TypeDefinition linkedType) { VerifyMemberBackingField (src, linkedType); @@ -335,14 +334,13 @@ void VerifyEvent (EventDefinition src, EventDefinition? linked, TypeDefinition l VerifyCustomAttributes (src, linked); } - void VerifyMethod (MethodDefinition src, MethodDefinition? linked) + private void VerifyMethod (MethodDefinition src, MethodDefinition? linked) { bool expectedKept = ShouldMethodBeKept (src); VerifyMethodInternal (src, linked, expectedKept); } - - void VerifyMethodInternal (MethodDefinition src, MethodDefinition? linked, bool expectedKept) + private void VerifyMethodInternal (MethodDefinition src, MethodDefinition? linked, bool expectedKept) { if (!expectedKept) { if (linked != null) @@ -354,7 +352,7 @@ void VerifyMethodInternal (MethodDefinition src, MethodDefinition? linked, bool VerifyMethodKept (src, linked); } - void VerifyMemberBackingField (IMemberDefinition src, TypeDefinition linkedType) + private void VerifyMemberBackingField (IMemberDefinition src, TypeDefinition linkedType) { var keptBackingFieldAttribute = src.CustomAttributes.FirstOrDefault (attr => attr.AttributeType.Name == nameof (KeptBackingFieldAttribute)); if (keptBackingFieldAttribute == null) @@ -460,13 +458,13 @@ void Append (string text) => result.Add ((null, text)); } - static string FormatInstruction (Instruction instr) + private static string FormatInstruction (Instruction instr) { switch (instr.OpCode.FlowControl) { case FlowControl.Branch: case FlowControl.Cond_Branch: if (instr.Operand is Instruction target) - return $"{instr.OpCode.ToString ()} il_{target.Offset.ToString ("x")}"; + return $"{instr.OpCode} il_{target.Offset:x}"; break; } @@ -474,35 +472,35 @@ static string FormatInstruction (Instruction instr) switch (instr.OpCode.Code) { case Code.Ldc_I4: if (instr.Operand is int ivalue) - return $"{instr.OpCode.ToString ()} 0x{ivalue.ToString ("x")}"; + return $"{instr.OpCode} 0x{ivalue:x}"; throw new NotImplementedException (instr.Operand.GetType ().ToString ()); case Code.Ldc_I4_S: if (instr.Operand is sbyte bvalue) - return $"{instr.OpCode.ToString ()} 0x{bvalue.ToString ("x")}"; + return $"{instr.OpCode} 0x{bvalue:x}"; throw new NotImplementedException (instr.Operand.GetType ().ToString ()); case Code.Ldc_I8: if (instr.Operand is long lvalue) - return $"{instr.OpCode.ToString ()} 0x{lvalue.ToString ("x")}"; + return $"{instr.OpCode} 0x{lvalue:x}"; throw new NotImplementedException (instr.Operand.GetType ().ToString ()); case Code.Ldc_R4: if (instr.Operand is float fvalue) - return $"{instr.OpCode.ToString ()} {fvalue.ToString ()}"; + return $"{instr.OpCode} {fvalue}"; throw new NotImplementedException (instr.Operand.GetType ().ToString ()); case Code.Ldc_R8: if (instr.Operand is double dvalue) - return $"{instr.OpCode.ToString ()} {dvalue.ToString ()}"; + return $"{instr.OpCode} {dvalue}"; throw new NotImplementedException (instr.Operand.GetType ().ToString ()); case Code.Ldstr: if (instr.Operand is string svalue) - return $"{instr.OpCode.ToString ()} '{svalue}'"; + return $"{instr.OpCode} '{svalue}'"; throw new NotImplementedException (instr.Operand.GetType ().ToString ()); @@ -523,13 +521,14 @@ static string FormatInstruction (Instruction instr) } if (operandString != null) - return $"{instr.OpCode.ToString ()} {operandString}"; + return $"{instr.OpCode} {operandString}"; else return instr.OpCode.ToString (); } } } - static void VerifyLocals (MethodDefinition src, MethodDefinition linked) + + private static void VerifyLocals (MethodDefinition src, MethodDefinition linked) { VerifyBodyProperties ( src, @@ -560,7 +559,7 @@ public static void VerifyBodyProperties (MethodDefinition src, MethodDefinition } } - void VerifyReferences (AssemblyDefinition original, AssemblyDefinition linked) + private void VerifyReferences (AssemblyDefinition original, AssemblyDefinition linked) { var expected = original.MainModule.AllDefinedTypes () .SelectMany (t => GetCustomAttributeCtorValues (t, nameof (KeptReferenceAttribute))) @@ -586,7 +585,7 @@ void VerifyReferences (AssemblyDefinition original, AssemblyDefinition linked) actual.Should ().BeEquivalentTo (expected); } - string? ReduceAssemblyFileNameOrNameToNameOnly (string? fileNameOrAssemblyName) + private string? ReduceAssemblyFileNameOrNameToNameOnly (string? fileNameOrAssemblyName) { if (fileNameOrAssemblyName == null) return null; @@ -598,7 +597,7 @@ void VerifyReferences (AssemblyDefinition original, AssemblyDefinition linked) return fileNameOrAssemblyName; } - void VerifyResources (AssemblyDefinition original, AssemblyDefinition linked) + private void VerifyResources (AssemblyDefinition original, AssemblyDefinition linked) { var expectedResourceNames = original.MainModule.AllDefinedTypes () .SelectMany (t => GetCustomAttributeCtorValues (t, nameof (KeptResourceAttribute))) @@ -620,7 +619,7 @@ void VerifyResources (AssemblyDefinition original, AssemblyDefinition linked) } } - void VerifyExportedTypes (AssemblyDefinition original, AssemblyDefinition linked) + private void VerifyExportedTypes (AssemblyDefinition original, AssemblyDefinition linked) { var expectedTypes = original.MainModule.AllDefinedTypes () .SelectMany (t => GetCustomAttributeCtorValues (t, nameof (KeptExportedTypeAttribute)).Select (l => l?.FullName ?? "")).ToArray (); @@ -731,7 +730,7 @@ protected virtual void VerifyArrayInitializers (MethodDefinition src, MethodDefi } } - void VerifyInitializerField (FieldDefinition src, FieldDefinition? linked) + private void VerifyInitializerField (FieldDefinition src, FieldDefinition? linked) { VerifyFieldKept (src, linked); verifiedGeneratedFields.Add (linked!.FullName); @@ -742,7 +741,7 @@ void VerifyInitializerField (FieldDefinition src, FieldDefinition? linked) verifiedGeneratedTypes.Add (linked.DeclaringType.FullName); } - static bool IsLdtokenOnPrivateImplementationDetails (TypeDefinition privateImplementationDetails, Instruction instruction) + private static bool IsLdtokenOnPrivateImplementationDetails (TypeDefinition privateImplementationDetails, Instruction instruction) { if (instruction.OpCode.Code == Code.Ldtoken && instruction.Operand is FieldReference field) { return field.DeclaringType.Resolve () == privateImplementationDetails; @@ -809,7 +808,7 @@ protected virtual IEnumerable FilterLinkedSecurityAttributes (ISecurityD .Select (attr => attr.AttributeType.ToString ()); } - void VerifyFixedBufferFields (TypeDefinition src, TypeDefinition linked) + private void VerifyFixedBufferFields (TypeDefinition src, TypeDefinition linked) { var fields = src.Fields.Where (f => f.CustomAttributes.Any (attr => attr.AttributeType.Name == nameof (KeptFixedBufferAttribute))); @@ -846,7 +845,7 @@ void VerifyFixedBufferFields (TypeDefinition src, TypeDefinition linked) } } - void VerifyDelegateBackingFields (TypeDefinition src, TypeDefinition linked) + private void VerifyDelegateBackingFields (TypeDefinition src, TypeDefinition linked) { var expectedFieldNames = GetCustomAttributeCtorValues (src, nameof (KeptDelegateCacheFieldAttribute)) .Select (unique => $"<>f__mg$cache{unique}") @@ -866,7 +865,7 @@ void VerifyDelegateBackingFields (TypeDefinition src, TypeDefinition linked) } } - void VerifyGenericParameters (IGenericParameterProvider src, IGenericParameterProvider linked) + private void VerifyGenericParameters (IGenericParameterProvider src, IGenericParameterProvider linked) { Assert.Equal (src.HasGenericParameters, linked.HasGenericParameters); if (src.HasGenericParameters) { @@ -888,7 +887,7 @@ void VerifyGenericParameters (IGenericParameterProvider src, IGenericParameterPr } } - void VerifyParameters (IMethodSignature src, IMethodSignature linked) + private void VerifyParameters (IMethodSignature src, IMethodSignature linked) { Assert.Equal (src.HasParameters, linked.HasParameters); if (src.HasParameters) { diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/BaseMetadataProvider.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/BaseMetadataProvider.cs index b136da80846b44..2be52e19df6f03 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/BaseMetadataProvider.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/BaseMetadataProvider.cs @@ -85,7 +85,7 @@ protected virtual NPath SourceFileForAttributeArgumentValue (object value) return MakeSourceTreeFilePathAbsolute (value.ToString ()!); } - static TypeReference ParentMostType (TypeReference type) + private static TypeReference ParentMostType (TypeReference type) { if (!type.IsNested) return type; diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILCompilerDriver.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILCompilerDriver.cs index 5c8c44267edb61..94389b716e22f5 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILCompilerDriver.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILCompilerDriver.cs @@ -85,7 +85,7 @@ public void Trim (ILCompilerOptions options, ILogWriter logWriter) .UseParallelism (System.Diagnostics.Debugger.IsAttached ? 1 : -1) .ToILScanner (); - ILScanResults results = scanner.Scan (); + _ = scanner.Scan (); } public static void ComputeDefaultOptions (out TargetOS os, out TargetArchitecture arch) @@ -119,7 +119,7 @@ public static void ComputeDefaultOptions (out TargetOS os, out TargetArchitectur } } - private IReadOnlyCollection CreateInitializerList (CompilerTypeSystemContext context, ILCompilerOptions options) + private static IReadOnlyCollection CreateInitializerList (CompilerTypeSystemContext context, ILCompilerOptions options) { List assembliesWithInitalizers = new List (); diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILCompilerOptionsBuilder.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILCompilerOptionsBuilder.cs index 98f0ee4351ef12..a370eff817d26a 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILCompilerOptionsBuilder.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILCompilerOptionsBuilder.cs @@ -221,7 +221,7 @@ public virtual void ProcessOptions (TestCaseLinkerOptions options) AddAdditionalArgument (additionalArgument.Key, additionalArgument.Value); } - static void AppendExpandedPaths (Dictionary dictionary, string pattern) + private static void AppendExpandedPaths (Dictionary dictionary, string pattern) { bool empty = true; diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILCompilerTestCaseResult.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILCompilerTestCaseResult.cs index 8fe4bfe8b8e71f..20039ead239a31 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILCompilerTestCaseResult.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILCompilerTestCaseResult.cs @@ -1,7 +1,6 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using Mono.Linker.Tests.TestCasesRunner; using Mono.Linker.Tests.Extensions; using Mono.Linker.Tests.TestCases; diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILInputCompiler.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILInputCompiler.cs index 32973f050fa6ea..bffa9822c358f5 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILInputCompiler.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ILInputCompiler.cs @@ -42,7 +42,7 @@ protected virtual void SetupProcess (Process process, CompilerOptions options) process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; } - private string BuildArguments (CompilerOptions options) + private static string BuildArguments (CompilerOptions options) { var args = new StringBuilder (); #if NETCOREAPP diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/IgnoreTestException.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/IgnoreTestException.cs index 767bc07454fcb9..838edb1cdd4ba1 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/IgnoreTestException.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/IgnoreTestException.cs @@ -5,7 +5,7 @@ namespace Mono.Linker.Tests.TestCasesRunner { - internal class IgnoreTestException : Exception + internal sealed class IgnoreTestException : Exception { public IgnoreTestException (string message) : base (message) { } } diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ResultChecker.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ResultChecker.cs index a6adaf187d4c55..e09966f22d45c1 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ResultChecker.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/ResultChecker.cs @@ -6,32 +6,25 @@ using System.Diagnostics; using System.IO; using System.Linq; -using System.Reflection.Metadata.Ecma335; -using System.Reflection.PortableExecutable; -using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; using FluentAssertions; using ILCompiler; -using ILCompiler.Dataflow; using ILCompiler.Logging; -using Mono.Linker.Tests.TestCasesRunner; using Internal.TypeSystem; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Linker.Tests.Cases.Expectations.Assertions; -using Mono.Linker.Tests.Cases.Expectations.Metadata; using Mono.Linker.Tests.Extensions; using Xunit; -using Mono.Linker.Tests.Cases.RequiresCapability; namespace Mono.Linker.Tests.TestCasesRunner { public class ResultChecker { - readonly BaseAssemblyResolver _originalsResolver; - readonly ReaderParameters _originalReaderParameters; - readonly ReaderParameters _linkedReaderParameters; + private readonly BaseAssemblyResolver _originalsResolver; + private readonly ReaderParameters _originalReaderParameters; + private readonly ReaderParameters _linkedReaderParameters; public ResultChecker () : this (new TestCaseAssemblyResolver (), @@ -64,7 +57,7 @@ public virtual void Check (ILCompilerTestCaseResult trimmedResult) } } - void InitializeResolvers (ILCompilerTestCaseResult linkedResult) + private void InitializeResolvers (ILCompilerTestCaseResult linkedResult) { _originalsResolver.AddSearchDirectory (linkedResult.ExpectationsAssemblyPath.Parent.ToString ()); } @@ -83,13 +76,13 @@ protected virtual void AdditionalChecking (ILCompilerTestCaseResult linkResult, VerifyLoggedMessages (original, linkResult.LogWriter, checkRemainingErrors); } - static bool IsProducedByNativeAOT (CustomAttribute attr) + private static bool IsProducedByNativeAOT (CustomAttribute attr) { var producedBy = attr.GetPropertyValue ("ProducedBy"); return producedBy is null ? true : ((ProducedBy) producedBy).HasFlag (ProducedBy.NativeAot); } - static IEnumerable GetAttributeProviders (AssemblyDefinition assembly) + private static IEnumerable GetAttributeProviders (AssemblyDefinition assembly) { foreach (var testType in assembly.AllDefinedTypes ()) { foreach (var provider in testType.AllMembers ()) @@ -104,12 +97,12 @@ static IEnumerable GetAttributeProviders (AssemblyDefi yield return assembly; } - void VerifyLoggedMessages (AssemblyDefinition original, TestLogWriter logger, bool checkRemainingErrors) + private void VerifyLoggedMessages (AssemblyDefinition original, TestLogWriter logger, bool checkRemainingErrors) { List loggedMessages = logger.GetLoggedMessages (); List<(IMemberDefinition, CustomAttribute)> expectedNoWarningsAttributes = new List<(IMemberDefinition, CustomAttribute)> (); foreach (var attrProvider in GetAttributeProviders (original)) { - if (attrProvider.ToString () is String mystring && mystring.Contains ("RequiresInCompilerGeneratedCode/SuppressInLambda")) + if (attrProvider.ToString () is string mystring && mystring.Contains ("RequiresInCompilerGeneratedCode/SuppressInLambda")) Debug.WriteLine ("Print"); foreach (var attr in attrProvider.CustomAttributes) { if (!IsProducedByNativeAOT (attr)) @@ -145,7 +138,7 @@ void VerifyLoggedMessages (AssemblyDefinition original, TestLogWriter logger, bo Assert.True ( isLogged (), - $"Expected to not find logged message matching `{unexpectedMessage}`, but found:{Environment.NewLine}{loggedMessage.ToString ()}{Environment.NewLine}Logged messages:{Environment.NewLine}{string.Join (Environment.NewLine, loggedMessages)}"); + $"Expected to not find logged message matching `{unexpectedMessage}`, but found:{Environment.NewLine}{loggedMessage}{Environment.NewLine}Logged messages:{Environment.NewLine}{string.Join (Environment.NewLine, loggedMessages)}"); } } break; @@ -311,7 +304,7 @@ void VerifyLoggedMessages (AssemblyDefinition original, TestLogWriter logger, bo Assert.False (remainingErrors.Any (), $"Found unexpected errors:{Environment.NewLine}{string.Join (Environment.NewLine, remainingErrors)}"); } - bool LogMessageHasSameOriginMember (MessageContainer mc, ICustomAttributeProvider expectedOriginProvider) + static bool LogMessageHasSameOriginMember (MessageContainer mc, ICustomAttributeProvider expectedOriginProvider) { var origin = mc.Origin; Debug.Assert (origin != null); @@ -393,13 +386,13 @@ static string ConvertSignatureToIlcFormat (string value) StringBuilder sb = new StringBuilder (); foreach (var part in parts) { if (sb.Length > 0) - sb.Append ("."); + sb.Append ('.'); if (part.EndsWith ('>')) { int i = part.LastIndexOf ('<'); if (i >= 0) { - sb.Append (part.Substring (0, i)); - sb.Append ("`"); + sb.Append (part.AsSpan (0, i)); + sb.Append ('`'); sb.Append (part.Substring (i + 1).Where (c => c == ',').Count () + 1); continue; } @@ -412,7 +405,7 @@ static string ConvertSignatureToIlcFormat (string value) } } - static bool HasAttribute (ICustomAttributeProvider caProvider, string attributeName) + private static bool HasAttribute (ICustomAttributeProvider caProvider, string attributeName) { if (caProvider is AssemblyDefinition assembly && assembly.EntryPoint != null) return assembly.EntryPoint.DeclaringType.CustomAttributes diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseAssemblyResolver.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseAssemblyResolver.cs index dec3270905e447..d3d4601c584fd3 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseAssemblyResolver.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseAssemblyResolver.cs @@ -9,7 +9,7 @@ namespace Mono.Linker.Tests.TestCasesRunner { public class TestCaseAssemblyResolver : DefaultAssemblyResolver { - readonly HashSet itemsToDispose; + private readonly HashSet itemsToDispose; public TestCaseAssemblyResolver () { diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseCompilationMetadataProvider.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseCompilationMetadataProvider.cs index 1aa354f58176b3..633e191f247c01 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseCompilationMetadataProvider.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseCompilationMetadataProvider.cs @@ -58,7 +58,7 @@ public virtual bool IsIgnored ([NotNullWhen(true)] out string? reason) return false; } - bool IsRequirementMissing (TestRunCharacteristics requirement, TestRunCharacteristics testCaseRequirements) + private bool IsRequirementMissing (TestRunCharacteristics requirement, TestRunCharacteristics testCaseRequirements) { return testCaseRequirements.HasFlag (requirement) && !Characteristics.HasFlag (requirement); } @@ -90,7 +90,7 @@ public virtual string GetAssemblyName () public virtual string GetCSharpCompilerToUse () { - return GetOptionAttributeValue (nameof (SetupCSharpCompilerToUseAttribute), string.Empty)!.ToLower (); + return GetOptionAttributeValue (nameof (SetupCSharpCompilerToUseAttribute), string.Empty)!.ToLowerInvariant (); } public virtual IEnumerable GetSetupCompilerArguments () @@ -107,7 +107,7 @@ public virtual IEnumerable AdditionalFilesToSandbox () .Select (GetSourceAndRelativeDestinationValue); } - static string GetReferenceDir () + private static string GetReferenceDir () { string runtimeDir = Path.GetDirectoryName (typeof (object).Assembly.Location)!; string ncaVersion = Path.GetFileName (runtimeDir); diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseCompiler.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseCompiler.cs index 442b176c38fc6e..8067d2969a4d23 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseCompiler.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseCompiler.cs @@ -39,7 +39,7 @@ public TestCaseCompiler (TestCaseSandbox sandbox, TestCaseCompilationMetadataPro public NPath CompileTestIn (NPath outputDirectory, string outputName, IEnumerable sourceFiles, string[] commonReferences, string[] mainAssemblyReferences, IEnumerable? defines, NPath[] resources, string[] additionalArguments) { var originalCommonReferences = commonReferences.Select (r => r.ToNPath ()).ToArray (); - var originalDefines = defines?.ToArray () ?? new string[0]; + var originalDefines = defines?.ToArray () ?? Array.Empty (); Prepare (outputDirectory); @@ -92,8 +92,8 @@ protected virtual CompilerOptions CreateOptionsForTestCase (NPath outputPath, NP protected virtual CompilerOptions CreateOptionsForSupportingAssembly (SetupCompileInfo setupCompileInfo, NPath outputDirectory, NPath[] sourceFiles, NPath[] references, string[] defines, NPath[] resources) { - var allDefines = defines.Concat (setupCompileInfo.Defines ?? new string[0]).ToArray (); - var allReferences = references.Concat (setupCompileInfo.References?.Select (p => MakeSupportingAssemblyReferencePathAbsolute (outputDirectory, p)) ?? new NPath[0]).ToArray (); + var allDefines = defines.Concat (setupCompileInfo.Defines ?? Array.Empty ()).ToArray (); + var allReferences = references.Concat (setupCompileInfo.References?.Select (p => MakeSupportingAssemblyReferencePathAbsolute (outputDirectory, p)) ?? Array.Empty ()).ToArray (); string[]? additionalArguments = string.IsNullOrEmpty (setupCompileInfo.AdditionalArguments) ? null : new[] { setupCompileInfo.AdditionalArguments }; return new CompilerOptions { OutputPath = outputDirectory.Combine (setupCompileInfo.OutputName), @@ -102,7 +102,7 @@ protected virtual CompilerOptions CreateOptionsForSupportingAssembly (SetupCompi Defines = allDefines, Resources = resources, AdditionalArguments = additionalArguments, - CompilerToUse = setupCompileInfo.CompilerToUse?.ToLower () + CompilerToUse = setupCompileInfo.CompilerToUse?.ToLowerInvariant () }; } @@ -367,7 +367,7 @@ protected NPath CompileCSharpAssemblyWithExternalCompiler (string executable, Co return options.OutputPath; } - static string LocateMcsExecutable () + private static string LocateMcsExecutable () { if (Environment.OSVersion.Platform == PlatformID.Win32NT) throw new IgnoreTestException ("We don't have a universal way of locating mcs on Windows"); diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseMetadataProvider.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseMetadataProvider.cs index cf3a7623963790..d24956508ddf8a 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseMetadataProvider.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseMetadataProvider.cs @@ -1,15 +1,14 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using System; using System.Collections.Generic; using System.IO; using System.Linq; using Mono.Cecil; -using Mono.Linker.Tests.Cases.Expectations.Assertions; using Mono.Linker.Tests.Cases.Expectations.Metadata; using Mono.Linker.Tests.Extensions; using Mono.Linker.Tests.TestCases; +using System; namespace Mono.Linker.Tests.TestCasesRunner { @@ -72,7 +71,7 @@ public virtual TestCaseLinkerOptions GetLinkerOptions (NPath inputPath) if (pos != -1) { string custom_assembly_path = values[0].Substring (pos + 1); if (!Path.IsPathRooted (custom_assembly_path)) - values[0] = values[0].Substring (0, pos + 1) + Path.Combine (inputPath, custom_assembly_path); + values[0] = string.Concat (values[0].AsSpan (0, pos + 1), Path.Combine (inputPath, custom_assembly_path)); } break; case "-a": diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseSandbox.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseSandbox.cs index c7041020c44810..5a6bd2a2d873c7 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseSandbox.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestCaseSandbox.cs @@ -14,10 +14,9 @@ public class TestCaseSandbox { protected readonly TestCase _testCase; protected readonly NPath _directory; + private const string _linkerAssemblyPath = "";//typeof (Trimmer).Assembly.Location; - static readonly string _linkerAssemblyPath = "";//typeof (Trimmer).Assembly.Location; - - static NPath GetArtifactsTestPath () + private static NPath GetArtifactsTestPath () { // Converts paths like /root-folder/runtime/artifacts/bin/Mono.Linker.Tests/x64/Debug/Mono.Linker.Tests.dll // to /root-folder/runtime/artifacts/bin/ILLink.testcases/ diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestInfraMultiFileCompilationModuleGroup.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestInfraMultiFileCompilationModuleGroup.cs index 0ce32dfb4f33a4..e774cf7c50beba 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestInfraMultiFileCompilationModuleGroup.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestInfraMultiFileCompilationModuleGroup.cs @@ -1,52 +1,49 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Collections.Generic; using System.Diagnostics; using ILCompiler; -using ILCompiler.DependencyAnalysis; using Internal.TypeSystem; -using Internal.TypeSystem.Ecma; namespace Mono.Linker.Tests.TestCasesRunner { - /// - /// Represents a non-leaf multifile compilation group where types contained in the group are always fully expanded. - /// - public class TestInfraMultiFileSharedCompilationModuleGroup : MultiFileCompilationModuleGroup - { - public TestInfraMultiFileSharedCompilationModuleGroup(CompilerTypeSystemContext context, IEnumerable compilationModuleSet) - : base(context, compilationModuleSet) - { - } - - public override bool ShouldProduceFullVTable(TypeDesc type) - { - return false; - } - - public override bool ShouldPromoteToFullType(TypeDesc type) - { - return ShouldProduceFullVTable(type); - } - - public override bool PresenceOfEETypeImpliesAllMethodsOnType(TypeDesc type) - { - return (type.HasInstantiation || type.IsArray) && ShouldProduceFullVTable(type) && - type.ConvertToCanonForm(CanonicalFormKind.Specific).IsCanonicalSubtype(CanonicalFormKind.Any); - } - - public override bool AllowInstanceMethodOptimization(MethodDesc method) - { - // Both the instance methods and the owning type are homed in a single compilation group - // so if we're able to generate the body, we would also generate the owning type here - // and nowhere else. - Debug.Assert(ContainsMethodBody(method, unboxingStub: false)); - TypeDesc owningType = method.OwningType; - return owningType.IsDefType && !owningType.HasInstantiation && !method.HasInstantiation; - } - } + /// + /// Represents a non-leaf multifile compilation group where types contained in the group are always fully expanded. + /// + public class TestInfraMultiFileSharedCompilationModuleGroup : MultiFileCompilationModuleGroup + { + public TestInfraMultiFileSharedCompilationModuleGroup (CompilerTypeSystemContext context, IEnumerable compilationModuleSet) + : base (context, compilationModuleSet) + { + } + + public override bool ShouldProduceFullVTable (TypeDesc type) + { + return false; + } + + public override bool ShouldPromoteToFullType (TypeDesc type) + { + return ShouldProduceFullVTable (type); + } + + public override bool PresenceOfEETypeImpliesAllMethodsOnType (TypeDesc type) + { + return (type.HasInstantiation || type.IsArray) && ShouldProduceFullVTable (type) && + type.ConvertToCanonForm (CanonicalFormKind.Specific).IsCanonicalSubtype (CanonicalFormKind.Any); + } + + public override bool AllowInstanceMethodOptimization (MethodDesc method) + { + // Both the instance methods and the owning type are homed in a single compilation group + // so if we're able to generate the body, we would also generate the owning type here + // and nowhere else. + Debug.Assert (ContainsMethodBody (method, unboxingStub: false)); + TypeDesc owningType = method.OwningType; + return owningType.IsDefType && !owningType.HasInstantiation && !method.HasInstantiation; + } + } } diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestLogWriter.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestLogWriter.cs index c8d4a40a7eabd8..0ef6c8fb995a7f 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestLogWriter.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestLogWriter.cs @@ -1,12 +1,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; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using ILCompiler; using ILCompiler.Logging; diff --git a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestRunner.cs b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestRunner.cs index 3540250b709f31..b358a33c12b866 100644 --- a/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestRunner.cs +++ b/src/coreclr/tools/aot/Mono.Linker.Tests/TestCasesRunner/TestRunner.cs @@ -4,7 +4,6 @@ using System; using System.Linq; using System.Threading.Tasks; -using Mono.Linker.Tests.TestCasesRunner; using Mono.Cecil; using Mono.Linker.Tests.Extensions; using Mono.Linker.Tests.TestCases; @@ -148,7 +147,7 @@ protected virtual void AddLinkOptions (TestCaseSandbox sandbox, ManagedCompilati builder.ProcessTestInputAssembly (compilationResult.InputAssemblyPath); } - private T GetResultOfTaskThatMakesXUnitAssertions (Task task) + private static T GetResultOfTaskThatMakesXUnitAssertions (Task task) { try { return task.Result; From 5e7cfbf086a03d2613e2e390805470063836262b Mon Sep 17 00:00:00 2001 From: Vladimir Sadov Date: Thu, 1 Sep 2022 13:04:48 -0700 Subject: [PATCH 073/107] [NativeAOT] Save full ARM64 SIMD arg registers in UniversalTransition (#74888) * Save full ARM64 SIMD arg registers in UniversalTransition * remove unused SAVE/RESTORE argument macros --- .../nativeaot/Runtime/StackFrameIterator.cpp | 14 +++--- .../Runtime/UniversalTransitionHelpers.cpp | 2 +- .../Runtime/arm64/UniversalTransition.S | 42 +++++++++--------- .../Runtime/arm64/UniversalTransition.asm | 34 +++++++-------- .../Runtime/unix/unixasmmacrosarm64.inc | 43 ------------------- 5 files changed, 46 insertions(+), 89 deletions(-) diff --git a/src/coreclr/nativeaot/Runtime/StackFrameIterator.cpp b/src/coreclr/nativeaot/Runtime/StackFrameIterator.cpp index 2fcceff6d0dd85..3da12598ba196f 100644 --- a/src/coreclr/nativeaot/Runtime/StackFrameIterator.cpp +++ b/src/coreclr/nativeaot/Runtime/StackFrameIterator.cpp @@ -1105,13 +1105,13 @@ struct UniversalTransitionStackFrame // Conservative GC reporting must be applied to everything between the base of the // ReturnBlock and the top of the StackPassedArgs. private: - uintptr_t m_pushedFP; // ChildSP+000 CallerSP-0C0 (0x08 bytes) (fp) - uintptr_t m_pushedLR; // ChildSP+008 CallerSP-0B8 (0x08 bytes) (lr) - uint64_t m_fpArgRegs[8]; // ChildSP+010 CallerSP-0B0 (0x40 bytes) (d0-d7) - uintptr_t m_returnBlock[4]; // ChildSP+050 CallerSP-070 (0x40 bytes) - uintptr_t m_intArgRegs[9]; // ChildSP+070 CallerSP-050 (0x48 bytes) (x0-x8) - uintptr_t m_alignmentPad; // ChildSP+0B8 CallerSP-008 (0x08 bytes) - uintptr_t m_stackPassedArgs[1]; // ChildSP+0C0 CallerSP+000 (unknown size) + uintptr_t m_pushedFP; // ChildSP+000 CallerSP-100 (0x08 bytes) (fp) + uintptr_t m_pushedLR; // ChildSP+008 CallerSP-0F8 (0x08 bytes) (lr) + Fp128 m_fpArgRegs[8]; // ChildSP+010 CallerSP-0F0 (0x80 bytes) (q0-q7) + uintptr_t m_returnBlock[4]; // ChildSP+090 CallerSP-070 (0x40 bytes) + uintptr_t m_intArgRegs[9]; // ChildSP+0B0 CallerSP-050 (0x48 bytes) (x0-x8) + uintptr_t m_alignmentPad; // ChildSP+0F8 CallerSP-008 (0x08 bytes) + uintptr_t m_stackPassedArgs[1]; // ChildSP+100 CallerSP+000 (unknown size) public: PTR_UIntNative get_CallerSP() { return GET_POINTER_TO_FIELD(m_stackPassedArgs[0]); } diff --git a/src/coreclr/nativeaot/Runtime/UniversalTransitionHelpers.cpp b/src/coreclr/nativeaot/Runtime/UniversalTransitionHelpers.cpp index 30a1ff269290ab..649aac21ac8d18 100644 --- a/src/coreclr/nativeaot/Runtime/UniversalTransitionHelpers.cpp +++ b/src/coreclr/nativeaot/Runtime/UniversalTransitionHelpers.cpp @@ -21,7 +21,7 @@ // // In the absence of trashing, such bugs can become undetectable if the code that // dispatches the call happens to never touch the impacted argument register (e.g., xmm3 on -// amd64 or d5 on arm32). In such a case, the original enregistered argument will flow +// amd64 or q5 on arm64). In such a case, the original enregistered argument will flow // unmodified into the eventual callee, obscuring the fact that the dispatcher failed to // propagate the transition frame copy of this register. // diff --git a/src/coreclr/nativeaot/Runtime/arm64/UniversalTransition.S b/src/coreclr/nativeaot/Runtime/arm64/UniversalTransition.S index 12fa42365f4c2e..8274b6b1110a6a 100644 --- a/src/coreclr/nativeaot/Runtime/arm64/UniversalTransition.S +++ b/src/coreclr/nativeaot/Runtime/arm64/UniversalTransition.S @@ -23,7 +23,7 @@ #define RETURN_BLOCK_SIZE (32) #define COUNT_FLOAT_ARG_REGISTERS (8) -#define FLOAT_REGISTER_SIZE (8) +#define FLOAT_REGISTER_SIZE (16) #define FLOAT_ARG_REGISTERS_SIZE (COUNT_FLOAT_ARG_REGISTERS * FLOAT_REGISTER_SIZE) #define PUSHED_LR_SIZE (8) @@ -50,7 +50,7 @@ // // RhpUniversalTransition // -// At input to this function, x0-8, d0-7 and the stack may contain any number of arguments. +// At input to this function, x0-8, q0-7 and the stack may contain any number of arguments. // // In addition, there are 2 extra arguments passed in the intra-procedure-call scratch register: // xip0 will contain the managed function that is to be called by this transition function @@ -63,16 +63,16 @@ // // Frame layout is: // -// {StackPassedArgs} ChildSP+0C0 CallerSP+000 -// {AlignmentPad (0x8 bytes)} ChildSP+0B8 CallerSP-008 -// {IntArgRegs (x0-x8) (0x48 bytes)} ChildSP+070 CallerSP-050 -// {ReturnBlock (0x20 bytes)} ChildSP+050 CallerSP-070 +// {StackPassedArgs} ChildSP+100 CallerSP+000 +// {AlignmentPad (0x8 bytes)} ChildSP+0F8 CallerSP-008 +// {IntArgRegs (x0-x8) (0x48 bytes)} ChildSP+0B0 CallerSP-050 +// {ReturnBlock (0x20 bytes)} ChildSP+090 CallerSP-070 // -- The base address of the Return block is the TransitionBlock pointer, the floating point args are // in the neg space of the TransitionBlock pointer. Note that the callee has knowledge of the exact // layout of all pieces of the frame that lie at or above the pushed floating point registers. -// {FpArgRegs (d0-d7) (0x40 bytes)} ChildSP+010 CallerSP-0B0 -// {PushedLR} ChildSP+008 CallerSP-0B8 -// {PushedFP} ChildSP+000 CallerSP-0C0 +// {FpArgRegs (q0-q7) (0x80 bytes)} ChildSP+010 CallerSP-0F0 +// {PushedLR} ChildSP+008 CallerSP-0F8 +// {PushedFP} ChildSP+000 CallerSP-100 // // NOTE: If the frame layout ever changes, the C++ UniversalTransitionStackFrame structure // must be updated as well. @@ -95,10 +95,10 @@ PROLOG_SAVE_REG_PAIR_INDEXED fp, lr, -STACK_SIZE // ;; Push down stack pointer and store FP and LR // Floating point registers - stp d0, d1, [sp, #(FLOAT_ARG_OFFSET )] - stp d2, d3, [sp, #(FLOAT_ARG_OFFSET + 0x10)] - stp d4, d5, [sp, #(FLOAT_ARG_OFFSET + 0x20)] - stp d6, d7, [sp, #(FLOAT_ARG_OFFSET + 0x30)] + stp q0, q1, [sp, #(FLOAT_ARG_OFFSET )] + stp q2, q3, [sp, #(FLOAT_ARG_OFFSET + 0x20)] + stp q4, q5, [sp, #(FLOAT_ARG_OFFSET + 0x40)] + stp q6, q7, [sp, #(FLOAT_ARG_OFFSET + 0x60)] // Space for return buffer data (0x40 bytes) @@ -112,10 +112,10 @@ #ifdef TRASH_SAVED_ARGUMENT_REGISTERS PREPARE_EXTERNAL_VAR RhpFpTrashValues, x1 - ldp d0,d1, [x1, 0x0] - ldp d2,d3, [x1, 0x10] - ldp d4,d5, [x1, 0x20] - ldp d6,d7, [x1, 0x30] + ldp q0,q1, [x1, 0x0] + ldp q2,q3, [x1, 0x20] + ldp q4,q5, [x1, 0x40] + ldp q6,q7, [x1, 0x60] PREPARE_EXTERNAL_VAR RhpIntegerTrashValues, x1 @@ -139,10 +139,10 @@ mov x12, x0 // Restore floating point registers - ldp d0, d1, [sp, #(FLOAT_ARG_OFFSET )] - ldp d2, d3, [sp, #(FLOAT_ARG_OFFSET + 0x10)] - ldp d4, d5, [sp, #(FLOAT_ARG_OFFSET + 0x20)] - ldp d6, d7, [sp, #(FLOAT_ARG_OFFSET + 0x30)] + ldp q0, q1, [sp, #(FLOAT_ARG_OFFSET )] + ldp q2, q3, [sp, #(FLOAT_ARG_OFFSET + 0x20)] + ldp q4, q5, [sp, #(FLOAT_ARG_OFFSET + 0x40)] + ldp q6, q7, [sp, #(FLOAT_ARG_OFFSET + 0x60)] // Restore the argument registers ldp x0, x1, [sp, #(ARGUMENT_REGISTERS_OFFSET )] diff --git a/src/coreclr/nativeaot/Runtime/arm64/UniversalTransition.asm b/src/coreclr/nativeaot/Runtime/arm64/UniversalTransition.asm index 6f1fc0953cd985..2e23ea4302a4fc 100644 --- a/src/coreclr/nativeaot/Runtime/arm64/UniversalTransition.asm +++ b/src/coreclr/nativeaot/Runtime/arm64/UniversalTransition.asm @@ -23,7 +23,7 @@ #define RETURN_BLOCK_SIZE (32) #define COUNT_FLOAT_ARG_REGISTERS (8) -#define FLOAT_REGISTER_SIZE (8) +#define FLOAT_REGISTER_SIZE (16) #define FLOAT_ARG_REGISTERS_SIZE (COUNT_FLOAT_ARG_REGISTERS * FLOAT_REGISTER_SIZE) #define PUSHED_LR_SIZE (8) @@ -51,7 +51,7 @@ ;; ;; RhpUniversalTransition ;; -;; At input to this function, x0-8, d0-7 and the stack may contain any number of arguments. +;; At input to this function, x0-8, q0-7 and the stack may contain any number of arguments. ;; ;; In addition, there are 2 extra arguments passed in the intra-procedure-call scratch register: ;; xip0 will contain the managed function that is to be called by this transition function @@ -64,16 +64,16 @@ ;; ;; Frame layout is: ;; -;; {StackPassedArgs} ChildSP+0C0 CallerSP+000 -;; {AlignmentPad (0x8 bytes)} ChildSP+0B8 CallerSP-008 -;; {IntArgRegs (x0-x8) (0x48 bytes)} ChildSP+070 CallerSP-050 -;; {ReturnBlock (0x20 bytes)} ChildSP+050 CallerSP-070 +;; {StackPassedArgs} ChildSP+100 CallerSP+000 +;; {AlignmentPad (0x8 bytes)} ChildSP+0F8 CallerSP-008 +;; {IntArgRegs (x0-x8) (0x48 bytes)} ChildSP+0A0 CallerSP-050 +;; {ReturnBlock (0x20 bytes)} ChildSP+090 CallerSP-070 ;; -- The base address of the Return block is the TransitionBlock pointer, the floating point args are ;; in the neg space of the TransitionBlock pointer. Note that the callee has knowledge of the exact ;; layout of all pieces of the frame that lie at or above the pushed floating point registers. -;; {FpArgRegs (d0-d7) (0x40 bytes)} ChildSP+010 CallerSP-0B0 -;; {PushedLR} ChildSP+008 CallerSP-0B8 -;; {PushedFP} ChildSP+000 CallerSP-0C0 +;; {FpArgRegs (q0-q7) (0x80 bytes)} ChildSP+010 CallerSP-0F0 +;; {PushedLR} ChildSP+008 CallerSP-0F8 +;; {PushedFP} ChildSP+000 CallerSP-100 ;; ;; NOTE: If the frame layout ever changes, the C++ UniversalTransitionStackFrame structure ;; must be updated as well. @@ -97,10 +97,10 @@ PROLOG_SAVE_REG_PAIR fp, lr, #-STACK_SIZE! ;; Push down stack pointer and store FP and LR ;; Floating point registers - stp d0, d1, [sp, #(FLOAT_ARG_OFFSET )] - stp d2, d3, [sp, #(FLOAT_ARG_OFFSET + 0x10)] - stp d4, d5, [sp, #(FLOAT_ARG_OFFSET + 0x20)] - stp d6, d7, [sp, #(FLOAT_ARG_OFFSET + 0x30)] + stp q0, q1, [sp, #(FLOAT_ARG_OFFSET )] + stp q2, q3, [sp, #(FLOAT_ARG_OFFSET + 0x20)] + stp q4, q5, [sp, #(FLOAT_ARG_OFFSET + 0x40)] + stp q6, q7, [sp, #(FLOAT_ARG_OFFSET + 0x60)] ;; Space for return buffer data (0x40 bytes) @@ -130,10 +130,10 @@ mov x12, x0 ;; Restore floating point registers - ldp d0, d1, [sp, #(FLOAT_ARG_OFFSET )] - ldp d2, d3, [sp, #(FLOAT_ARG_OFFSET + 0x10)] - ldp d4, d5, [sp, #(FLOAT_ARG_OFFSET + 0x20)] - ldp d6, d7, [sp, #(FLOAT_ARG_OFFSET + 0x30)] + ldp q0, q1, [sp, #(FLOAT_ARG_OFFSET )] + ldp q2, q3, [sp, #(FLOAT_ARG_OFFSET + 0x20)] + ldp q4, q5, [sp, #(FLOAT_ARG_OFFSET + 0x40)] + ldp q6, q7, [sp, #(FLOAT_ARG_OFFSET + 0x60)] ;; Restore the argument registers ldp x0, x1, [sp, #(ARGUMENT_REGISTERS_OFFSET )] diff --git a/src/coreclr/nativeaot/Runtime/unix/unixasmmacrosarm64.inc b/src/coreclr/nativeaot/Runtime/unix/unixasmmacrosarm64.inc index 1bd91a75e2c546..9284c7bbf4d757 100644 --- a/src/coreclr/nativeaot/Runtime/unix/unixasmmacrosarm64.inc +++ b/src/coreclr/nativeaot/Runtime/unix/unixasmmacrosarm64.inc @@ -164,49 +164,6 @@ C_FUNC(\Name): brk #0 .endm -//----------------------------------------------------------------------------- -// The Following sets of SAVE_*_REGISTERS expect the memory to be reserved and -// base address to be passed in $reg -// - -// Reserve 64 bytes of memory before calling SAVE_ARGUMENT_REGISTERS -.macro SAVE_ARGUMENT_REGISTERS reg, ofs - - stp x0, x1, [\reg, #(\ofs)] - stp x2, x3, [\reg, #(\ofs + 16)] - stp x4, x5, [\reg, #(\ofs + 32)] - stp x6, x7, [\reg, #(\ofs + 48)] - -.endm - -// Reserve 64 bytes of memory before calling SAVE_FLOAT_ARGUMENT_REGISTERS -.macro SAVE_FLOAT_ARGUMENT_REGISTERS reg, ofs - - stp d0, d1, [\reg, #(\ofs)] - stp d2, d3, [\reg, #(\ofs + 16)] - stp d4, d5, [\reg, #(\ofs + 32)] - stp d6, d7, [\reg, #(\ofs + 48)] - -.endm - -.macro RESTORE_ARGUMENT_REGISTERS reg, ofs - - ldp x0, x1, [\reg, #(\ofs)] - ldp x2, x3, [\reg, #(\ofs + 16)] - ldp x4, x5, [\reg, #(\ofs + 32)] - ldp x6, x7, [\reg, #(\ofs + 48)] - -.endm - -.macro RESTORE_FLOAT_ARGUMENT_REGISTERS reg, ofs - - ldp d0, d1, [\reg, #(\ofs)] - ldp d2, d3, [\reg, #(\ofs + 16)] - ldp d4, d5, [\reg, #(\ofs + 32)] - ldp d6, d7, [\reg, #(\ofs + 48)] - -.endm - .macro EPILOG_BRANCH_REG reg br \reg From 81f8e64ae310da4ab85bb6850fd0b1d9b2cf2f83 Mon Sep 17 00:00:00 2001 From: Mitchell Hwang <16830051+mdh1418@users.noreply.github.com> Date: Thu, 1 Sep 2022 16:47:57 -0400 Subject: [PATCH 074/107] [Android][libs] Introduce GetLocalUtcOffset temporary fast result (#74459) * Avoid ICU loading via StringComparison.Ordinal * Pass OffsetDateTime and monotonic clock through monovm * WIP Leverage monovm_initialize_preparsed * Initial perf improvement implementation * Cleanup GetLocalUtcOffset * Remove Kernel Monotonic Time app context key * Cleanup GetLocalUtcOffset * Sleep background thread first, then start loading AndroidTZData * Conform Runtime Config Property name * Revert "WIP Leverage monovm_initialize_preparsed" This reverts commit 1edaeeee37066ad392ab19100248994ee53b0797. * Address feedback * Fix thread clearing * Move implementation to DateTimeOffset.Now * Address feedback * Consolidate into DateTimeOffset.Now and avoid calling DateTime.UtcNow multiple times * Introduce small performance gains Leverage a boolean flag instead of && Start the background thread to avoid deadlocking * Bump boolean flag outside of background thread body --- .../System.Private.CoreLib.Shared.projitems | 2 + .../src/System/DateTimeOffset.Android.cs | 89 +++++++++++++++++++ .../src/System/DateTimeOffset.NonAndroid.cs | 12 +++ .../src/System/DateTimeOffset.cs | 6 +- .../src/System/TimeZoneInfo.Unix.Android.cs | 2 +- .../Templates/MonoRunner.java | 7 +- .../AndroidAppBuilder/Templates/monodroid.c | 16 ++-- 7 files changed, 120 insertions(+), 14 deletions(-) create mode 100644 src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.Android.cs create mode 100644 src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.NonAndroid.cs diff --git a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems index 86bde088f4ad7b..c334d0a1dbd908 100644 --- a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems +++ b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems @@ -254,6 +254,8 @@ + + diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.Android.cs b/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.Android.cs new file mode 100644 index 00000000000000..c78dadcdfc3bd6 --- /dev/null +++ b/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.Android.cs @@ -0,0 +1,89 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Threading; + +namespace System +{ + public readonly partial struct DateTimeOffset + { + private static bool s_androidTZDataLoaded; + private static readonly object s_localUtcOffsetLock = new(); + private static Thread? s_loadAndroidTZData; + private static bool s_startNewBackgroundThread = true; + + // Now on Android does the following + // 1) quickly returning a fast path result when first called if the right AppContext data element is set + // 2) starting a background thread to load TimeZoneInfo local cache + // + // On Android, loading AndroidTZData is expensive for startup performance. + // The fast result relies on `System.TimeZoneInfo.LocalDateTimeOffset` being set + // in the App Context's properties as the appropriate local date time offset from UTC. + // monovm_initialize(_preparsed) can be leveraged to do so. + // However, to handle timezone changes during the app lifetime, AndroidTZData needs to be loaded. + // So, on first call, we return the fast path and start a background thread to load + // the TimeZoneInfo Local cache implementation which loads AndroidTZData. + public static DateTimeOffset Now + { + get + { + DateTime utcDateTime = DateTime.UtcNow; + + if (s_androidTZDataLoaded) // The background thread finished, the cache is loaded. + return ToLocalTime(utcDateTime, true); + + if (s_startNewBackgroundThread) // The cache isn't loaded and no background thread has been created + { + lock (s_localUtcOffsetLock) + { + // Now may be called multiple times before a cache is loaded and a background thread is running, + // once the lock is available, check for a cache and background thread. + if (s_androidTZDataLoaded) + return ToLocalTime(utcDateTime, true); + + if (s_loadAndroidTZData == null) + { + s_loadAndroidTZData = new Thread(() => { + // Delay the background thread to avoid impacting startup, if it still coincides after 1s, startup is already perceived as slow + Thread.Sleep(1000); + + _ = TimeZoneInfo.Local; // Load AndroidTZData + s_androidTZDataLoaded = true; + + lock (s_localUtcOffsetLock) + { + s_loadAndroidTZData = null; // Ensure thread is cleared when cache is loaded + } + }); + s_loadAndroidTZData.IsBackground = true; + } + } + + if (s_startNewBackgroundThread) + { + // Because Start does not block the calling thread, + // setting the boolean flag to false immediately after should + // prevent two calls to DateTimeOffset.Now in quick succession + // from both reaching here. + s_loadAndroidTZData.Start(); + s_startNewBackgroundThread = false; + } + } + + + object? localDateTimeOffset = AppContext.GetData("System.TimeZoneInfo.LocalDateTimeOffset"); + if (localDateTimeOffset == null) // If no offset property provided through monovm app context, default + return ToLocalTime(utcDateTime, true); + + // Fast path obtained offset incorporated into ToLocalTime(DateTime.UtcNow, true) logic + int localDateTimeOffsetSeconds = Convert.ToInt32(localDateTimeOffset); + TimeSpan offset = TimeSpan.FromSeconds(localDateTimeOffsetSeconds); + long localTicks = utcDateTime.Ticks + offset.Ticks; + if (localTicks < DateTime.MinTicks || localTicks > DateTime.MaxTicks) + throw new ArgumentException(SR.Arg_ArgumentOutOfRangeException); + + return new DateTimeOffset(localTicks, offset); + } + } + } +} diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.NonAndroid.cs b/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.NonAndroid.cs new file mode 100644 index 00000000000000..511e40ef6c8d12 --- /dev/null +++ b/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.NonAndroid.cs @@ -0,0 +1,12 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace System +{ + public readonly partial struct DateTimeOffset + { + // Returns a DateTimeOffset representing the current date and time. The + // resolution of the returned value depends on the system timer. + public static DateTimeOffset Now => ToLocalTime(DateTime.UtcNow, true); + } +} diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs b/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs index 3f8feead885a77..b2289d1377aceb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateTimeOffset.cs @@ -34,7 +34,7 @@ namespace System [StructLayout(LayoutKind.Auto)] [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public readonly struct DateTimeOffset + public readonly partial struct DateTimeOffset : IComparable, ISpanFormattable, IComparable, @@ -321,10 +321,6 @@ public DateTimeOffset(int year, int month, int day, int hour, int minute, int se _dateTime = _dateTime.AddMicroseconds(microsecond); } - // Returns a DateTimeOffset representing the current date and time. The - // resolution of the returned value depends on the system timer. - public static DateTimeOffset Now => ToLocalTime(DateTime.UtcNow, true); - public static DateTimeOffset UtcNow { get diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.Android.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.Android.cs index e03c67beaa58da..d9b46074b8e351 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.Android.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.Android.cs @@ -107,7 +107,7 @@ private static int ParseGMTNumericZone(string name) { return new TimeZoneInfo(id, TimeSpan.FromSeconds(0), id, name, name, null, disableDaylightSavingTime:true); } - if (name.StartsWith("GMT", StringComparison.Ordinal)) + if (name.Length >= 3 && name[0] == 'G' && name[1] == 'M' && name[2] == 'T') { return new TimeZoneInfo(id, TimeSpan.FromSeconds(ParseGMTNumericZone(name)), id, name, name, null, disableDaylightSavingTime:true); } diff --git a/src/tasks/AndroidAppBuilder/Templates/MonoRunner.java b/src/tasks/AndroidAppBuilder/Templates/MonoRunner.java index 700d95e123f07a..4bd5a68d41623b 100644 --- a/src/tasks/AndroidAppBuilder/Templates/MonoRunner.java +++ b/src/tasks/AndroidAppBuilder/Templates/MonoRunner.java @@ -26,6 +26,8 @@ import java.util.ArrayList; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; public class MonoRunner extends Instrumentation { @@ -88,7 +90,8 @@ public static int initialize(String entryPointLibName, String[] args, Context co unzipAssets(context, filesDir, "assets.zip"); Log.i("DOTNET", "MonoRunner initialize,, entryPointLibName=" + entryPointLibName); - return initRuntime(filesDir, cacheDir, testResultsDir, entryPointLibName, args); + int localDateTimeOffset = OffsetDateTime.now().getOffset().getTotalSeconds(); + return initRuntime(filesDir, cacheDir, testResultsDir, entryPointLibName, args, localDateTimeOffset); } @Override @@ -149,7 +152,7 @@ static void unzipAssets(Context context, String toPath, String zipName) { } } - static native int initRuntime(String libsDir, String cacheDir, String testResultsDir, String entryPointLibName, String[] args); + static native int initRuntime(String libsDir, String cacheDir, String testResultsDir, String entryPointLibName, String[] args, int local_date_time_offset); static native int setEnv(String key, String value); } diff --git a/src/tasks/AndroidAppBuilder/Templates/monodroid.c b/src/tasks/AndroidAppBuilder/Templates/monodroid.c index 1d8d3f1bd529cf..a016353a0b4f39 100644 --- a/src/tasks/AndroidAppBuilder/Templates/monodroid.c +++ b/src/tasks/AndroidAppBuilder/Templates/monodroid.c @@ -203,7 +203,7 @@ cleanup_runtime_config (MonovmRuntimeConfigArguments *args, void *user_data) } int -mono_droid_runtime_init (const char* executable, int managed_argc, char* managed_argv[]) +mono_droid_runtime_init (const char* executable, int managed_argc, char* managed_argv[], int local_date_time_offset) { // NOTE: these options can be set via command line args for adb or xharness, see AndroidSampleApp.csproj @@ -225,13 +225,17 @@ mono_droid_runtime_init (const char* executable, int managed_argc, char* managed // TODO: set TRUSTED_PLATFORM_ASSEMBLIES, APP_PATHS and NATIVE_DLL_SEARCH_DIRECTORIES - const char* appctx_keys[2]; + const char* appctx_keys[3]; appctx_keys[0] = "RUNTIME_IDENTIFIER"; appctx_keys[1] = "APP_CONTEXT_BASE_DIRECTORY"; + appctx_keys[2] = "System.TimeZoneInfo.LocalDateTimeOffset"; - const char* appctx_values[2]; + const char* appctx_values[3]; appctx_values[0] = ANDROID_RUNTIME_IDENTIFIER; appctx_values[1] = bundle_path; + char local_date_time_offset_buffer[32]; + snprintf (local_date_time_offset_buffer, sizeof(local_date_time_offset_buffer), "%d", local_date_time_offset); + appctx_values[2] = strdup (local_date_time_offset_buffer); char *file_name = RUNTIMECONFIG_BIN_FILE; int str_len = strlen (bundle_path) + strlen (file_name) + 1; // +1 is for the "/" @@ -251,7 +255,7 @@ mono_droid_runtime_init (const char* executable, int managed_argc, char* managed free (file_path); } - monovm_initialize(2, appctx_keys, appctx_values); + monovm_initialize(3, appctx_keys, appctx_values); mono_debug_init (MONO_DEBUG_FORMAT_MONO); mono_install_assembly_preload_hook (mono_droid_assembly_preload_hook, NULL); @@ -318,7 +322,7 @@ Java_net_dot_MonoRunner_setEnv (JNIEnv* env, jobject thiz, jstring j_key, jstrin } int -Java_net_dot_MonoRunner_initRuntime (JNIEnv* env, jobject thiz, jstring j_files_dir, jstring j_cache_dir, jstring j_testresults_dir, jstring j_entryPointLibName, jobjectArray j_args) +Java_net_dot_MonoRunner_initRuntime (JNIEnv* env, jobject thiz, jstring j_files_dir, jstring j_cache_dir, jstring j_testresults_dir, jstring j_entryPointLibName, jobjectArray j_args, long current_local_time) { char file_dir[2048]; char cache_dir[2048]; @@ -347,7 +351,7 @@ Java_net_dot_MonoRunner_initRuntime (JNIEnv* env, jobject thiz, jstring j_files_ managed_argv[i + 1] = (*env)->GetStringUTFChars(env, j_arg, NULL); } - int res = mono_droid_runtime_init (executable, managed_argc, managed_argv); + int res = mono_droid_runtime_init (executable, managed_argc, managed_argv, current_local_time); for (int i = 0; i < args_len; ++i) { From ba329311a78ca61161e80bb28920b9d09848737d Mon Sep 17 00:00:00 2001 From: SingleAccretion <62474226+SingleAccretion@users.noreply.github.com> Date: Fri, 2 Sep 2022 00:00:16 +0300 Subject: [PATCH 075/107] Mark certain compiler-created locals as aliased (#74665) * Add a test for the devirt case * Fix the devirt case * Add a test for the ctor case * Fix the ctor case * Add a test for the localloc case This one is actually ok, but only because "gtNewFieldRef" is quirky. * Fix the localloc case * Add an assert to catch future violations * Fix up "arglist" * Add a more elaborate "newobj" test case One might be tempted to say that a "newobj" temp isn't really aliased, since it is atomically assigned by the constructor call. As this new test case shows, such is not the case - the "this" address pointing to the local being constructed can be captured and used to mutate it. --- src/coreclr/jit/importer.cpp | 40 +++- src/coreclr/jit/lclvars.cpp | 1 + .../JitBlue/Runtime_74635/Runtime_74635.il | 210 ++++++++++++++++++ .../Runtime_74635/Runtime_74635.ilproj | 11 + src/tests/issues.targets | 3 + 5 files changed, 255 insertions(+), 10 deletions(-) create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_74635/Runtime_74635.il create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_74635/Runtime_74635.ilproj diff --git a/src/coreclr/jit/importer.cpp b/src/coreclr/jit/importer.cpp index 8afca0e44baee7..5e85743da45b4b 100644 --- a/src/coreclr/jit/importer.cpp +++ b/src/coreclr/jit/importer.cpp @@ -15612,6 +15612,11 @@ void Compiler::impImportBlockCode(BasicBlock* block) compSuppressedZeroInit = true; } + // The constructor may store "this", with subsequent code mutating the underlying local + // through the captured reference. To correctly spill the node we'll push onto the stack + // in such a case, we must mark the temp as potentially aliased. + lclDsc->lvHasLdAddrOp = true; + // Obtain the address of the temp newObjThisPtr = gtNewOperNode(GT_ADDR, TYP_BYREF, gtNewLclvNode(lclNum, lvaTable[lclNum].TypeGet())); @@ -16621,6 +16626,7 @@ void Compiler::impImportBlockCode(BasicBlock* block) stackallocAsLocal); lvaTable[stackallocAsLocal].lvType = TYP_BLK; lvaTable[stackallocAsLocal].lvExactSize = (unsigned)allocSize; + lvaTable[stackallocAsLocal].lvHasLdAddrOp = true; lvaTable[stackallocAsLocal].lvIsUnsafeBuffer = true; op1 = gtNewLclvNode(stackallocAsLocal, TYP_BLK); op1 = gtNewOperNode(GT_ADDR, TYP_I_IMPL, op1); @@ -20203,18 +20209,25 @@ void Compiler::impInlineRecordArgInfo(InlineInfo* pInlineInfo, return; } - GenTree* lclVarTree; - + GenTree* lclVarTree; const bool isAddressInLocal = impIsAddressInLocal(curArgVal, &lclVarTree); - if (isAddressInLocal && varTypeIsStruct(lclVarTree)) + if (isAddressInLocal) { - inlCurArgInfo->argIsByRefToStructLocal = true; -#ifdef FEATURE_SIMD - if (lvaTable[lclVarTree->AsLclVarCommon()->GetLclNum()].lvSIMDType) + LclVarDsc* varDsc = lvaGetDesc(lclVarTree->AsLclVarCommon()); + + if (varTypeIsStruct(lclVarTree)) { - pInlineInfo->hasSIMDTypeArgLocalOrReturn = true; - } + inlCurArgInfo->argIsByRefToStructLocal = true; +#ifdef FEATURE_SIMD + if (varDsc->lvSIMDType) + { + pInlineInfo->hasSIMDTypeArgLocalOrReturn = true; + } #endif // FEATURE_SIMD + } + + // Spilling code relies on correct aliasability annotations. + assert(varDsc->lvHasLdAddrOp || varDsc->IsAddressExposed()); } if (curArgVal->gtFlags & GTF_ALL_EFFECT) @@ -22001,6 +22014,8 @@ void Compiler::impDevirtualizeCall(GenTreeCall* call, // // Ideally, we then inline the boxed method and and if it turns out not to modify // the copy, we can undo the copy too. + GenTree* localCopyThis = nullptr; + if (requiresInstMethodTableArg) { // Perform a trial box removal and ask for the type handle tree that fed the box. @@ -22014,7 +22029,7 @@ void Compiler::impDevirtualizeCall(GenTreeCall* call, // If that worked, turn the box into a copy to a local var // JITDUMP("Found suitable method table arg tree [%06u]\n", dspTreeID(methodTableArg)); - GenTree* localCopyThis = gtTryRemoveBoxUpstreamEffects(thisObj, BR_MAKE_LOCAL_COPY); + localCopyThis = gtTryRemoveBoxUpstreamEffects(thisObj, BR_MAKE_LOCAL_COPY); if (localCopyThis != nullptr) { @@ -22055,7 +22070,7 @@ void Compiler::impDevirtualizeCall(GenTreeCall* call, else { JITDUMP("Found unboxed entry point, trying to simplify box to a local copy\n"); - GenTree* localCopyThis = gtTryRemoveBoxUpstreamEffects(thisObj, BR_MAKE_LOCAL_COPY); + localCopyThis = gtTryRemoveBoxUpstreamEffects(thisObj, BR_MAKE_LOCAL_COPY); if (localCopyThis != nullptr) { @@ -22078,6 +22093,11 @@ void Compiler::impDevirtualizeCall(GenTreeCall* call, if (optimizedTheBox) { + assert(localCopyThis->OperIs(GT_ADDR)); + + // We may end up inlining this call, so the local copy must be marked as "aliased", + // making sure the inlinee importer will know when to spill references to its value. + lvaGetDesc(localCopyThis->AsUnOp()->gtOp1->AsLclVar())->lvHasLdAddrOp = true; #if FEATURE_TAILCALL_OPT if (call->IsImplicitTailCall()) diff --git a/src/coreclr/jit/lclvars.cpp b/src/coreclr/jit/lclvars.cpp index 78bf365413443f..d11743d9902b6c 100644 --- a/src/coreclr/jit/lclvars.cpp +++ b/src/coreclr/jit/lclvars.cpp @@ -1378,6 +1378,7 @@ void Compiler::lvaInitVarArgsHandle(InitVarDscInfo* varDscInfo) // Codegen will need it for x86 scope info. varDsc->lvImplicitlyReferenced = 1; #endif // TARGET_X86 + varDsc->lvHasLdAddrOp = 1; lvaSetVarDoNotEnregister(lvaVarargsHandleArg DEBUGARG(DoNotEnregisterReason::VMNeedsStackAddr)); diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_74635/Runtime_74635.il b/src/tests/JIT/Regression/JitBlue/Runtime_74635/Runtime_74635.il new file mode 100644 index 00000000000000..91dccb5675749f --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_74635/Runtime_74635.il @@ -0,0 +1,210 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +.assembly extern System.Runtime { } +.assembly extern System.Console { } + +.assembly Runtime_74635.dll { } + +#define TRUE "1" +#define FALSE "0" +#define THIS "0" + +#define EXPECTED "0" +#define THRASHED "1" + +.class Runtime_74635 extends [System.Runtime]System.Object +{ + .method public static int32 Main() + { + .entrypoint + + call bool .this::ProblemWithDevirtualization() + brtrue DEVIRT_FAILED + + call bool .this::ProblemWithCtors() + brtrue CTORS_FAILED + + call bool .this::ProblemWithLocAlloc() + brtrue LOCALLOC_FAILED + + call bool .this::ProblemWithCapturingCtors() + brtrue CAPTURING_CTORS_FAILED + + ldc.i4 100 + ret + + DEVIRT_FAILED: + ldc.i4 101 + ret + + CTORS_FAILED: + ldc.i4 102 + ret + + LOCALLOC_FAILED: + ldc.i4 103 + ret + + CAPTURING_CTORS_FAILED: + ldc.i4 104 + ret + } + + .method private static bool ProblemWithDevirtualization() noinlining + { + ldc.i4 EXPECTED + newobj instance void Struct::.ctor(int32) + box valuetype Struct + callvirt instance int32 Interface::ReturnSelf() + ldc.i4 EXPECTED + bne.un FAILED + + ldc.i4 FALSE + ret + + FAILED: + ldc.i4 TRUE + ret + } + + .method private static bool ProblemWithCtors() noinlining + { + ldc.i4 EXPECTED + ldc.i4 THRASHED + newobj instance void Struct::.ctor(int32, int32) + pop + + ldsfld int32 Struct::StaticValue + ldc.i4 EXPECTED + bne.un FAILED + + ldc.i4 FALSE + ret + + FAILED: + ldc.i4 TRUE + ret + } + + .method private static bool ProblemWithLocAlloc() noinlining + { + sizeof valuetype Struct + localloc + call int32 .this::ReturnExpectedWithLocAlloc(void*) + ldc.i4 EXPECTED + bne.un FAILED + + ldc.i4 FALSE + ret + + FAILED: + ldc.i4 TRUE + ret + } + + .method private static int32 ReturnExpectedWithLocAlloc(void* pLocAlloc) + { + ldarg pLocAlloc + ldc.i4 EXPECTED + stind.i4 + + ldarg pLocAlloc + ldfld int32 Struct::Value + ldarg pLocAlloc + ldc.i4 THRASHED + stind.i4 + ret + } + + .method private static bool ProblemWithCapturingCtors() noinlining + { + .locals (valuetype Closure closure) + + ldc.i4 EXPECTED + ldloca closure + newobj instance void Struct::.ctor(int32, valuetype Closure&) + ldloc closure + ldfld valuetype Struct& Closure::StructRef + ldc.i4 THRASHED + stfld int32 Struct::Value + ldfld int32 Struct::Value + ldc.i4 EXPECTED + bne.un FAILED + + ldc.i4 FALSE + ret + + FAILED: + ldc.i4 TRUE + ret + } +} + +.class interface Interface +{ + .method public abstract virtual int32 ReturnSelf() { } +} + +.class sealed sequential Struct extends [System.Runtime]System.ValueType implements Interface +{ + .field public static int32 StaticValue + + .field public int32 Value + + .method public void .ctor(int32 val) + { + ldarg THIS + ldarg val + stfld int32 .this::Value + + ret + } + + .method public void .ctor(int32 expected, int32 thrashed) + { + ldarg THIS + ldarg expected + stfld int32 .this::Value + + ldarg THIS + ldfld int32 .this::Value + ldarg THIS + ldarg thrashed + stind.i4 + stsfld int32 .this::StaticValue + + ret + } + + .method public void .ctor(int32 val, valuetype Closure& closureRef) noinlining + { + ldarg THIS + ldarg val + stfld int32 .this::Value + + ldarg closureRef + ldarg THIS + stfld valuetype Struct& Closure::StructRef + + ret + } + + .method public virtual int32 ReturnSelf() + { + ldarg THIS + ldfld int32 .this::Value + ldarg THIS + ldc.i4 THRASHED + stind.i4 + + ret + } +} + +.class sealed Closure extends [System.Runtime]System.ValueType +{ + .custom instance void [System.Runtime]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = (01 00 00 00) + + .field public valuetype Struct& StructRef +} diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_74635/Runtime_74635.ilproj b/src/tests/JIT/Regression/JitBlue/Runtime_74635/Runtime_74635.ilproj new file mode 100644 index 00000000000000..c61c0c5d312f45 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_74635/Runtime_74635.ilproj @@ -0,0 +1,11 @@ + + + Exe + + + True + + + + + diff --git a/src/tests/issues.targets b/src/tests/issues.targets index 4a97ccfeb9786d..ac3e9975606fd2 100644 --- a/src/tests/issues.targets +++ b/src/tests/issues.targets @@ -2685,6 +2685,9 @@ needs triage + + https://github.com/dotnet/runtime/issues/74687 + From 04ca89d9fb963a2f57582e85bb0c6e626f64c96f Mon Sep 17 00:00:00 2001 From: Akhil Indurti Date: Thu, 1 Sep 2022 15:02:47 -0700 Subject: [PATCH 076/107] Update CompatibilitySuppressions.xml after sorting (#74954) * update suppressions * remove new files * remove new suppressions --- .../src/CompatibilitySuppressions.xml | 72 +-- .../src/CompatibilitySuppressions.xml | 196 +++---- .../src/CompatibilitySuppressions.xml | 8 +- .../src/CompatibilitySuppressions.xml | 502 +++++++++--------- .../src/CompatibilitySuppressions.xml | 20 +- .../src/CompatibilitySuppressions.xml | 32 +- .../src/CompatibilitySuppressions.xml | 74 +-- .../src/CompatibilitySuppressions.xml | 12 +- .../src/CompatibilitySuppressions.xml | 12 +- .../src/CompatibilitySuppressions.xml | 16 +- 10 files changed, 472 insertions(+), 472 deletions(-) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/CompatibilitySuppressions.xml b/src/libraries/System.Configuration.ConfigurationManager/src/CompatibilitySuppressions.xml index 70889d28bf99ad..d3401e27334abf 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/CompatibilitySuppressions.xml +++ b/src/libraries/System.Configuration.ConfigurationManager/src/CompatibilitySuppressions.xml @@ -2,39 +2,15 @@ CP0002 - M:System.Configuration.SettingsAttributeDictionary.#ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext) - lib/netstandard2.0/System.Configuration.ConfigurationManager.dll - lib/net462/System.Configuration.ConfigurationManager.dll - - - CP0002 - M:System.Configuration.SettingsContext.#ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext) - lib/netstandard2.0/System.Configuration.ConfigurationManager.dll - lib/net462/System.Configuration.ConfigurationManager.dll - - - CP0002 - M:System.Configuration.Internal.DelegatingConfigHost.RefreshConfigPaths - lib/netstandard2.0/System.Configuration.ConfigurationManager.dll - lib/net462/System.Configuration.ConfigurationManager.dll - - - CP0002 - M:System.Configuration.Internal.DelegatingConfigHost.get_HasLocalConfig - lib/netstandard2.0/System.Configuration.ConfigurationManager.dll - lib/net462/System.Configuration.ConfigurationManager.dll - - - CP0002 - M:System.Configuration.Internal.DelegatingConfigHost.get_HasRoamingConfig - lib/netstandard2.0/System.Configuration.ConfigurationManager.dll - lib/net462/System.Configuration.ConfigurationManager.dll + M:System.Configuration.Internal.InternalConfigEventHandler.#ctor(System.Object,System.IntPtr) + lib/net6.0/System.Configuration.ConfigurationManager.dll + lib/net7.0/System.Configuration.ConfigurationManager.dll CP0002 - M:System.Configuration.Internal.DelegatingConfigHost.get_IsAppConfigHttp - lib/netstandard2.0/System.Configuration.ConfigurationManager.dll - lib/net462/System.Configuration.ConfigurationManager.dll + M:System.Configuration.Internal.StreamChangeCallback.#ctor(System.Object,System.IntPtr) + lib/net6.0/System.Configuration.ConfigurationManager.dll + lib/net7.0/System.Configuration.ConfigurationManager.dll CP0002 @@ -62,14 +38,38 @@ CP0002 - M:System.Configuration.Internal.InternalConfigEventHandler.#ctor(System.Object,System.IntPtr) - lib/net6.0/System.Configuration.ConfigurationManager.dll - lib/net7.0/System.Configuration.ConfigurationManager.dll + M:System.Configuration.Internal.DelegatingConfigHost.get_HasLocalConfig + lib/netstandard2.0/System.Configuration.ConfigurationManager.dll + lib/net462/System.Configuration.ConfigurationManager.dll CP0002 - M:System.Configuration.Internal.StreamChangeCallback.#ctor(System.Object,System.IntPtr) - lib/net6.0/System.Configuration.ConfigurationManager.dll - lib/net7.0/System.Configuration.ConfigurationManager.dll + M:System.Configuration.Internal.DelegatingConfigHost.get_HasRoamingConfig + lib/netstandard2.0/System.Configuration.ConfigurationManager.dll + lib/net462/System.Configuration.ConfigurationManager.dll + + + CP0002 + M:System.Configuration.Internal.DelegatingConfigHost.get_IsAppConfigHttp + lib/netstandard2.0/System.Configuration.ConfigurationManager.dll + lib/net462/System.Configuration.ConfigurationManager.dll + + + CP0002 + M:System.Configuration.Internal.DelegatingConfigHost.RefreshConfigPaths + lib/netstandard2.0/System.Configuration.ConfigurationManager.dll + lib/net462/System.Configuration.ConfigurationManager.dll + + + CP0002 + M:System.Configuration.SettingsAttributeDictionary.#ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext) + lib/netstandard2.0/System.Configuration.ConfigurationManager.dll + lib/net462/System.Configuration.ConfigurationManager.dll + + + CP0002 + M:System.Configuration.SettingsContext.#ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext) + lib/netstandard2.0/System.Configuration.ConfigurationManager.dll + lib/net462/System.Configuration.ConfigurationManager.dll \ No newline at end of file diff --git a/src/libraries/System.Data.Odbc/src/CompatibilitySuppressions.xml b/src/libraries/System.Data.Odbc/src/CompatibilitySuppressions.xml index 0c15b2d390f7c7..509bb53cd39215 100644 --- a/src/libraries/System.Data.Odbc/src/CompatibilitySuppressions.xml +++ b/src/libraries/System.Data.Odbc/src/CompatibilitySuppressions.xml @@ -1,5 +1,58 @@  + + CP0001 + T:System.Data.Odbc.ODBC32 + lib/netcoreapp3.1/System.Data.Odbc.dll + lib/netstandard2.0/System.Data.Odbc.dll + true + + + CP0001 + T:System.Data.Odbc.ODBC32 + runtimes/freebsd/lib/netcoreapp3.1/System.Data.Odbc.dll + lib/netstandard2.0/System.Data.Odbc.dll + true + + + CP0001 + T:System.Data.Odbc.ODBC32 + runtimes/linux/lib/netcoreapp3.1/System.Data.Odbc.dll + lib/netstandard2.0/System.Data.Odbc.dll + true + + + CP0001 + T:System.Data.Odbc.ODBC32 + runtimes/osx/lib/netcoreapp3.1/System.Data.Odbc.dll + lib/netstandard2.0/System.Data.Odbc.dll + true + + + CP0001 + T:System.Data.Odbc.ODBC32 + runtimes/win/lib/netcoreapp3.1/System.Data.Odbc.dll + lib/netstandard2.0/System.Data.Odbc.dll + true + + + CP0002 + M:System.Data.Odbc.OdbcInfoMessageEventHandler.#ctor(System.Object,System.IntPtr) + lib/net6.0/System.Data.Odbc.dll + lib/net7.0/System.Data.Odbc.dll + + + CP0002 + M:System.Data.Odbc.OdbcRowUpdatedEventHandler.#ctor(System.Object,System.IntPtr) + lib/net6.0/System.Data.Odbc.dll + lib/net7.0/System.Data.Odbc.dll + + + CP0002 + M:System.Data.Odbc.OdbcRowUpdatingEventHandler.#ctor(System.Object,System.IntPtr) + lib/net6.0/System.Data.Odbc.dll + lib/net7.0/System.Data.Odbc.dll + CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset @@ -64,92 +117,85 @@ CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset lib/net7.0/System.Data.Odbc.dll - runtimes/linux/lib/net7.0/System.Data.Odbc.dll + runtimes/illumos/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) lib/net7.0/System.Data.Odbc.dll - runtimes/linux/lib/net7.0/System.Data.Odbc.dll + runtimes/illumos/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset lib/net7.0/System.Data.Odbc.dll - runtimes/osx/lib/net7.0/System.Data.Odbc.dll + runtimes/ios/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) lib/net7.0/System.Data.Odbc.dll - runtimes/osx/lib/net7.0/System.Data.Odbc.dll + runtimes/ios/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset lib/net7.0/System.Data.Odbc.dll - runtimes/win/lib/net7.0/System.Data.Odbc.dll + runtimes/linux/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) lib/net7.0/System.Data.Odbc.dll - runtimes/win/lib/net7.0/System.Data.Odbc.dll + runtimes/linux/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset lib/net7.0/System.Data.Odbc.dll - runtimes/illumos/lib/net7.0/System.Data.Odbc.dll + runtimes/osx/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) lib/net7.0/System.Data.Odbc.dll - runtimes/illumos/lib/net7.0/System.Data.Odbc.dll + runtimes/osx/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset lib/net7.0/System.Data.Odbc.dll - runtimes/ios/lib/net7.0/System.Data.Odbc.dll + runtimes/solaris/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) lib/net7.0/System.Data.Odbc.dll - runtimes/ios/lib/net7.0/System.Data.Odbc.dll + runtimes/solaris/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset lib/net7.0/System.Data.Odbc.dll - runtimes/solaris/lib/net7.0/System.Data.Odbc.dll + runtimes/tvos/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) lib/net7.0/System.Data.Odbc.dll - runtimes/solaris/lib/net7.0/System.Data.Odbc.dll + runtimes/tvos/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset lib/net7.0/System.Data.Odbc.dll - runtimes/tvos/lib/net7.0/System.Data.Odbc.dll + runtimes/win/lib/net7.0/System.Data.Odbc.dll CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) lib/net7.0/System.Data.Odbc.dll - runtimes/tvos/lib/net7.0/System.Data.Odbc.dll - - - CP0001 - T:System.Data.Odbc.ODBC32 - lib/netcoreapp3.1/System.Data.Odbc.dll - lib/netstandard2.0/System.Data.Odbc.dll - true + runtimes/win/lib/net7.0/System.Data.Odbc.dll CP0002 @@ -168,169 +214,141 @@ CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset - runtimes/illumos/lib/net6.0/System.Data.Odbc.dll - lib/net6.0/System.Data.Odbc.dll + runtimes/freebsd/lib/netcoreapp3.1/System.Data.Odbc.dll + lib/netstandard2.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) - runtimes/illumos/lib/net6.0/System.Data.Odbc.dll - lib/net6.0/System.Data.Odbc.dll + runtimes/freebsd/lib/netcoreapp3.1/System.Data.Odbc.dll + lib/netstandard2.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset - runtimes/ios/lib/net6.0/System.Data.Odbc.dll + runtimes/illumos/lib/net6.0/System.Data.Odbc.dll lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) - runtimes/ios/lib/net6.0/System.Data.Odbc.dll + runtimes/illumos/lib/net6.0/System.Data.Odbc.dll lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset - runtimes/linux/lib/net6.0/System.Data.Odbc.dll + runtimes/ios/lib/net6.0/System.Data.Odbc.dll lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) - runtimes/linux/lib/net6.0/System.Data.Odbc.dll + runtimes/ios/lib/net6.0/System.Data.Odbc.dll lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset - runtimes/osx/lib/net6.0/System.Data.Odbc.dll + runtimes/linux/lib/net6.0/System.Data.Odbc.dll lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) - runtimes/osx/lib/net6.0/System.Data.Odbc.dll + runtimes/linux/lib/net6.0/System.Data.Odbc.dll lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset - runtimes/solaris/lib/net6.0/System.Data.Odbc.dll - lib/net6.0/System.Data.Odbc.dll + runtimes/linux/lib/netcoreapp3.1/System.Data.Odbc.dll + lib/netstandard2.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) - runtimes/solaris/lib/net6.0/System.Data.Odbc.dll - lib/net6.0/System.Data.Odbc.dll + runtimes/linux/lib/netcoreapp3.1/System.Data.Odbc.dll + lib/netstandard2.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset - runtimes/tvos/lib/net6.0/System.Data.Odbc.dll + runtimes/osx/lib/net6.0/System.Data.Odbc.dll lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) - runtimes/tvos/lib/net6.0/System.Data.Odbc.dll + runtimes/osx/lib/net6.0/System.Data.Odbc.dll lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset - runtimes/win/lib/net6.0/System.Data.Odbc.dll - lib/net6.0/System.Data.Odbc.dll + runtimes/osx/lib/netcoreapp3.1/System.Data.Odbc.dll + lib/netstandard2.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) - runtimes/win/lib/net6.0/System.Data.Odbc.dll - lib/net6.0/System.Data.Odbc.dll - true - - - CP0001 - T:System.Data.Odbc.ODBC32 - runtimes/freebsd/lib/netcoreapp3.1/System.Data.Odbc.dll + runtimes/osx/lib/netcoreapp3.1/System.Data.Odbc.dll lib/netstandard2.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset - runtimes/freebsd/lib/netcoreapp3.1/System.Data.Odbc.dll - lib/netstandard2.0/System.Data.Odbc.dll + runtimes/solaris/lib/net6.0/System.Data.Odbc.dll + lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) - runtimes/freebsd/lib/netcoreapp3.1/System.Data.Odbc.dll - lib/netstandard2.0/System.Data.Odbc.dll - true - - - CP0001 - T:System.Data.Odbc.ODBC32 - runtimes/linux/lib/netcoreapp3.1/System.Data.Odbc.dll - lib/netstandard2.0/System.Data.Odbc.dll + runtimes/solaris/lib/net6.0/System.Data.Odbc.dll + lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset - runtimes/linux/lib/netcoreapp3.1/System.Data.Odbc.dll - lib/netstandard2.0/System.Data.Odbc.dll + runtimes/tvos/lib/net6.0/System.Data.Odbc.dll + lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) - runtimes/linux/lib/netcoreapp3.1/System.Data.Odbc.dll - lib/netstandard2.0/System.Data.Odbc.dll - true - - - CP0001 - T:System.Data.Odbc.ODBC32 - runtimes/osx/lib/netcoreapp3.1/System.Data.Odbc.dll - lib/netstandard2.0/System.Data.Odbc.dll + runtimes/tvos/lib/net6.0/System.Data.Odbc.dll + lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.get_Offset - runtimes/osx/lib/netcoreapp3.1/System.Data.Odbc.dll - lib/netstandard2.0/System.Data.Odbc.dll + runtimes/win/lib/net6.0/System.Data.Odbc.dll + lib/net6.0/System.Data.Odbc.dll true CP0002 M:System.Data.Odbc.OdbcParameter.set_Offset(System.Int32) - runtimes/osx/lib/netcoreapp3.1/System.Data.Odbc.dll - lib/netstandard2.0/System.Data.Odbc.dll - true - - - CP0001 - T:System.Data.Odbc.ODBC32 - runtimes/win/lib/netcoreapp3.1/System.Data.Odbc.dll - lib/netstandard2.0/System.Data.Odbc.dll + runtimes/win/lib/net6.0/System.Data.Odbc.dll + lib/net6.0/System.Data.Odbc.dll true @@ -347,22 +365,4 @@ lib/netstandard2.0/System.Data.Odbc.dll true - - CP0002 - M:System.Data.Odbc.OdbcInfoMessageEventHandler.#ctor(System.Object,System.IntPtr) - lib/net6.0/System.Data.Odbc.dll - lib/net7.0/System.Data.Odbc.dll - - - CP0002 - M:System.Data.Odbc.OdbcRowUpdatedEventHandler.#ctor(System.Object,System.IntPtr) - lib/net6.0/System.Data.Odbc.dll - lib/net7.0/System.Data.Odbc.dll - - - CP0002 - M:System.Data.Odbc.OdbcRowUpdatingEventHandler.#ctor(System.Object,System.IntPtr) - lib/net6.0/System.Data.Odbc.dll - lib/net7.0/System.Data.Odbc.dll - \ No newline at end of file diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/CompatibilitySuppressions.xml b/src/libraries/System.Diagnostics.DiagnosticSource/src/CompatibilitySuppressions.xml index 994ad65b2944d2..fa1b8e18d4ba2f 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/CompatibilitySuppressions.xml +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/CompatibilitySuppressions.xml @@ -2,25 +2,25 @@ CP0002 - M:System.Diagnostics.SampleActivity`1.#ctor(System.Object,System.IntPtr) + M:System.Diagnostics.DistributedContextPropagator.PropagatorGetterCallback.#ctor(System.Object,System.IntPtr) lib/net6.0/System.Diagnostics.DiagnosticSource.dll lib/net7.0/System.Diagnostics.DiagnosticSource.dll CP0002 - M:System.Diagnostics.DistributedContextPropagator.PropagatorGetterCallback.#ctor(System.Object,System.IntPtr) + M:System.Diagnostics.DistributedContextPropagator.PropagatorSetterCallback.#ctor(System.Object,System.IntPtr) lib/net6.0/System.Diagnostics.DiagnosticSource.dll lib/net7.0/System.Diagnostics.DiagnosticSource.dll CP0002 - M:System.Diagnostics.DistributedContextPropagator.PropagatorSetterCallback.#ctor(System.Object,System.IntPtr) + M:System.Diagnostics.Metrics.MeasurementCallback`1.#ctor(System.Object,System.IntPtr) lib/net6.0/System.Diagnostics.DiagnosticSource.dll lib/net7.0/System.Diagnostics.DiagnosticSource.dll CP0002 - M:System.Diagnostics.Metrics.MeasurementCallback`1.#ctor(System.Object,System.IntPtr) + M:System.Diagnostics.SampleActivity`1.#ctor(System.Object,System.IntPtr) lib/net6.0/System.Diagnostics.DiagnosticSource.dll lib/net7.0/System.Diagnostics.DiagnosticSource.dll diff --git a/src/libraries/System.Drawing.Common/src/CompatibilitySuppressions.xml b/src/libraries/System.Drawing.Common/src/CompatibilitySuppressions.xml index e2ab49e117507d..f2644074c69fce 100644 --- a/src/libraries/System.Drawing.Common/src/CompatibilitySuppressions.xml +++ b/src/libraries/System.Drawing.Common/src/CompatibilitySuppressions.xml @@ -32,256 +32,235 @@ CP0002 - F:System.Drawing.Imaging.Encoder.ColorSpace - lib/netstandard2.0/System.Drawing.Common.dll - lib/net462/System.Drawing.Common.dll + M:System.Drawing.Bitmap.#ctor(System.Int32,System.Int32,System.Int32,System.Drawing.Imaging.PixelFormat,System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - F:System.Drawing.Imaging.Encoder.ImageItems - lib/netstandard2.0/System.Drawing.Common.dll - lib/net462/System.Drawing.Common.dll + M:System.Drawing.Bitmap.FromHicon(System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - F:System.Drawing.Imaging.Encoder.SaveAsCmyk - lib/netstandard2.0/System.Drawing.Common.dll - lib/net462/System.Drawing.Common.dll + M:System.Drawing.Bitmap.FromResource(System.IntPtr,System.String) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - F:System.Drawing.Imaging.EncoderParameterValueType.ValueTypePointer - lib/netstandard2.0/System.Drawing.Common.dll - lib/net462/System.Drawing.Common.dll + M:System.Drawing.Brush.SetNativeBrush(System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.GetContextInfo(System.Drawing.PointF@) - lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.BufferedGraphics.Render(System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.GetContextInfo(System.Drawing.PointF@,System.Drawing.Region@) - lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.BufferedGraphicsContext.Allocate(System.IntPtr,System.Drawing.Rectangle) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.get_TransformElements - lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Font.FromHdc(System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.set_TransformElements(System.Numerics.Matrix3x2) - lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Font.FromHfont(System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Drawing2D.Matrix.#ctor(System.Numerics.Matrix3x2) - lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Font.FromLogFont(System.Object,System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Drawing2D.Matrix.get_MatrixElements - lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.DrawImage(System.Drawing.Image,System.Drawing.Rectangle,System.Int32,System.Int32,System.Int32,System.Int32,System.Drawing.GraphicsUnit,System.Drawing.Imaging.ImageAttributes,System.Drawing.Graphics.DrawImageAbort,System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Drawing2D.Matrix.set_MatrixElements(System.Numerics.Matrix3x2) - lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.DrawImage(System.Drawing.Image,System.Drawing.Rectangle,System.Single,System.Single,System.Single,System.Single,System.Drawing.GraphicsUnit,System.Drawing.Imaging.ImageAttributes,System.Drawing.Graphics.DrawImageAbort,System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.get_TransformElements - runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.DrawImageAbort.#ctor(System.Object,System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.set_TransformElements(System.Numerics.Matrix3x2) - runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.DrawImageAbort.BeginInvoke(System.IntPtr,System.AsyncCallback,System.Object) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.GetContextInfo(System.Drawing.PointF@) - runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.DrawImageAbort.Invoke(System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.GetContextInfo(System.Drawing.PointF@,System.Drawing.Region@) - runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Drawing2D.Matrix.#ctor(System.Numerics.Matrix3x2) - runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Drawing2D.Matrix.get_MatrixElements - runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point,System.Drawing.Rectangle,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Drawing2D.Matrix.set_MatrixElements(System.Numerics.Matrix3x2) - runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point,System.Drawing.Rectangle,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.get_TransformElements - runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point[],System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.set_TransformElements(System.Numerics.Matrix3x2) - runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point[],System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.GetContextInfo(System.Drawing.PointF@) - runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point[],System.Drawing.Rectangle,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.GetContextInfo(System.Drawing.PointF@,System.Drawing.Region@) - runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point[],System.Drawing.Rectangle,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Drawing2D.Matrix.#ctor(System.Numerics.Matrix3x2) - runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Drawing2D.Matrix.get_MatrixElements - runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Drawing2D.Matrix.set_MatrixElements(System.Numerics.Matrix3x2) - runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll - lib/netstandard2.0/System.Drawing.Common.dll - true + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF,System.Drawing.RectangleF,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + lib/net6.0/System.Drawing.Common.dll + lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Bitmap.#ctor(System.Int32,System.Int32,System.Int32,System.Drawing.Imaging.PixelFormat,System.IntPtr) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF,System.Drawing.RectangleF,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Bitmap.FromHicon(System.IntPtr) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF[],System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Bitmap.FromResource(System.IntPtr,System.String) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF[],System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Brush.SetNativeBrush(System.IntPtr) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF[],System.Drawing.RectangleF,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.BufferedGraphics.Render(System.IntPtr) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF[],System.Drawing.RectangleF,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.BufferedGraphicsContext.Allocate(System.IntPtr,System.Drawing.Rectangle) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Rectangle,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Font.FromHdc(System.IntPtr) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Rectangle,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Font.FromHfont(System.IntPtr) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Rectangle,System.Drawing.Rectangle,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Font.FromLogFont(System.Object,System.IntPtr) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Rectangle,System.Drawing.Rectangle,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.DrawImageAbort.#ctor(System.Object,System.IntPtr) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.RectangleF,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.DrawImageAbort.Invoke(System.IntPtr) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.RectangleF,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.DrawImageAbort.BeginInvoke(System.IntPtr,System.AsyncCallback,System.Object) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.RectangleF,System.Drawing.RectangleF,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafileProc.#ctor(System.Object,System.IntPtr) + M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.RectangleF,System.Drawing.RectangleF,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafileProc.Invoke(System.Drawing.Imaging.EmfPlusRecordType,System.Int32,System.Int32,System.IntPtr,System.Drawing.Imaging.PlayRecordCallback) + M:System.Drawing.Graphics.EnumerateMetafileProc.#ctor(System.Object,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll @@ -293,548 +272,569 @@ CP0002 - M:System.Drawing.Graphics.DrawImage(System.Drawing.Image,System.Drawing.Rectangle,System.Int32,System.Int32,System.Int32,System.Int32,System.Drawing.GraphicsUnit,System.Drawing.Imaging.ImageAttributes,System.Drawing.Graphics.DrawImageAbort,System.IntPtr) + M:System.Drawing.Graphics.EnumerateMetafileProc.Invoke(System.Drawing.Imaging.EmfPlusRecordType,System.Int32,System.Int32,System.IntPtr,System.Drawing.Imaging.PlayRecordCallback) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.DrawImage(System.Drawing.Image,System.Drawing.Rectangle,System.Single,System.Single,System.Single,System.Single,System.Drawing.GraphicsUnit,System.Drawing.Imaging.ImageAttributes,System.Drawing.Graphics.DrawImageAbort,System.IntPtr) + M:System.Drawing.Graphics.FromHdc(System.IntPtr,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + M:System.Drawing.Graphics.FromHdc(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + M:System.Drawing.Graphics.FromHdcInternal(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point,System.Drawing.Rectangle,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + M:System.Drawing.Graphics.FromHwnd(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point,System.Drawing.Rectangle,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + M:System.Drawing.Graphics.FromHwndInternal(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + M:System.Drawing.Graphics.ReleaseHdc(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + M:System.Drawing.Graphics.ReleaseHdcInternal(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF,System.Drawing.RectangleF,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + M:System.Drawing.Icon.FromHandle(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF,System.Drawing.RectangleF,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + M:System.Drawing.Image.FromHbitmap(System.IntPtr,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF[],System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + M:System.Drawing.Image.FromHbitmap(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF[],System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + M:System.Drawing.Image.GetThumbnailImage(System.Int32,System.Int32,System.Drawing.Image.GetThumbnailImageAbort,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF[],System.Drawing.RectangleF,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + M:System.Drawing.Image.GetThumbnailImageAbort.#ctor(System.Object,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.PointF[],System.Drawing.RectangleF,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + M:System.Drawing.Imaging.EncoderParameter.#ctor(System.Drawing.Imaging.Encoder,System.Int32,System.Drawing.Imaging.EncoderParameterValueType,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point[],System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Boolean) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point[],System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Imaging.EmfType,System.String) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point[],System.Drawing.Rectangle,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Imaging.EmfType) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Point[],System.Drawing.Rectangle,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Imaging.WmfPlaceableFileHeader,System.Boolean) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Rectangle,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Imaging.WmfPlaceableFileHeader) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Rectangle,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType,System.String) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Rectangle,System.Drawing.Rectangle,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.Rectangle,System.Drawing.Rectangle,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.RectangleF,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Rectangle) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.RectangleF,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType,System.String) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.RectangleF,System.Drawing.RectangleF,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.EnumerateMetafile(System.Drawing.Imaging.Metafile,System.Drawing.RectangleF,System.Drawing.RectangleF,System.Drawing.GraphicsUnit,System.Drawing.Graphics.EnumerateMetafileProc,System.IntPtr,System.Drawing.Imaging.ImageAttributes) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.FromHdc(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.RectangleF) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.FromHdc(System.IntPtr,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.Imaging.EmfType,System.String) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.FromHdcInternal(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.Imaging.EmfType) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.FromHwnd(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType,System.String) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.FromHwndInternal(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.ReleaseHdc(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Graphics.ReleaseHdcInternal(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.Rectangle) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Icon.FromHandle(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType,System.String) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Image.GetThumbnailImageAbort.#ctor(System.Object,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Image.FromHbitmap(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Image.FromHbitmap(System.IntPtr,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.RectangleF) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Image.GetThumbnailImage(System.Int32,System.Int32,System.Drawing.Image.GetThumbnailImageAbort,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Region.FromHrgn(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Imaging.EmfType,System.String) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Region.ReleaseHrgn(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Imaging.EmfType) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Text.PrivateFontCollection.AddMemoryFont(System.IntPtr,System.Int32) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType,System.String) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Printing.PageSettings.CopyToHdevmode(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Printing.PageSettings.SetHdevmode(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.String) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Printing.PrinterSettings.SetHdevmode(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Printing.PrinterSettings.SetHdevnames(System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Rectangle) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Printing.PrintEventHandler.#ctor(System.Object,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType,System.String) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Printing.PrintPageEventHandler.#ctor(System.Object,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Printing.QueryPageSettingsEventHandler.#ctor(System.Object,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.String) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.EncoderParameter.#ctor(System.Drawing.Imaging.Encoder,System.Int32,System.Drawing.Imaging.EncoderParameterValueType,System.IntPtr) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Boolean) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.RectangleF) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Imaging.EmfType) + M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Imaging.EmfType,System.String) + M:System.Drawing.Imaging.Metafile.GetMetafileHeader(System.IntPtr,System.Drawing.Imaging.WmfPlaceableFileHeader) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Imaging.WmfPlaceableFileHeader) + M:System.Drawing.Imaging.Metafile.GetMetafileHeader(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Imaging.WmfPlaceableFileHeader,System.Boolean) + M:System.Drawing.Imaging.PlayRecordCallback.#ctor(System.Object,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Rectangle) + M:System.Drawing.Imaging.PlayRecordCallback.BeginInvoke(System.Drawing.Imaging.EmfPlusRecordType,System.Int32,System.Int32,System.IntPtr,System.AsyncCallback,System.Object) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit) + M:System.Drawing.Imaging.PlayRecordCallback.Invoke(System.Drawing.Imaging.EmfPlusRecordType,System.Int32,System.Int32,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType) + M:System.Drawing.Printing.PageSettings.CopyToHdevmode(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType,System.String) + M:System.Drawing.Printing.PageSettings.SetHdevmode(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.RectangleF) + M:System.Drawing.Printing.PrinterSettings.SetHdevmode(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit) + M:System.Drawing.Printing.PrinterSettings.SetHdevnames(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType) + M:System.Drawing.Printing.PrintEventHandler.#ctor(System.Object,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType,System.String) + M:System.Drawing.Printing.PrintPageEventHandler.#ctor(System.Object,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr) + M:System.Drawing.Printing.QueryPageSettingsEventHandler.#ctor(System.Object,System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.Imaging.EmfType) + M:System.Drawing.Region.FromHrgn(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.Imaging.EmfType,System.String) + M:System.Drawing.Region.ReleaseHrgn(System.IntPtr) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.Rectangle) + M:System.Drawing.Text.PrivateFontCollection.AddMemoryFont(System.IntPtr,System.Int32) lib/net6.0/System.Drawing.Common.dll lib/net7.0/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Drawing2D.Matrix.#ctor(System.Numerics.Matrix3x2) + lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Drawing2D.Matrix.get_MatrixElements + lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType,System.String) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Drawing2D.Matrix.set_MatrixElements(System.Numerics.Matrix3x2) + lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.RectangleF) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Graphics.get_TransformElements + lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Graphics.GetContextInfo(System.Drawing.PointF@,System.Drawing.Region@) + lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Graphics.GetContextInfo(System.Drawing.PointF@) + lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.IO.Stream,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType,System.String) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Graphics.set_TransformElements(System.Numerics.Matrix3x2) + lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + F:System.Drawing.Imaging.Encoder.ColorSpace + lib/netstandard2.0/System.Drawing.Common.dll + lib/net462/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Imaging.EmfType) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + F:System.Drawing.Imaging.Encoder.ImageItems + lib/netstandard2.0/System.Drawing.Common.dll + lib/net462/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Imaging.EmfType,System.String) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + F:System.Drawing.Imaging.Encoder.SaveAsCmyk + lib/netstandard2.0/System.Drawing.Common.dll + lib/net462/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Rectangle) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + F:System.Drawing.Imaging.EncoderParameterValueType.ValueTypePointer + lib/netstandard2.0/System.Drawing.Common.dll + lib/net462/System.Drawing.Common.dll CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Drawing2D.Matrix.#ctor(System.Numerics.Matrix3x2) + runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Drawing2D.Matrix.get_MatrixElements + runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType,System.String) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Drawing2D.Matrix.set_MatrixElements(System.Numerics.Matrix3x2) + runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.Rectangle,System.Drawing.Imaging.MetafileFrameUnit,System.String) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Graphics.get_TransformElements + runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.RectangleF) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Graphics.GetContextInfo(System.Drawing.PointF@,System.Drawing.Region@) + runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Graphics.GetContextInfo(System.Drawing.PointF@) + runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Graphics.set_TransformElements(System.Numerics.Matrix3x2) + runtimes/unix/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.Drawing.Imaging.EmfType,System.String) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Drawing2D.Matrix.#ctor(System.Numerics.Matrix3x2) + runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.#ctor(System.String,System.IntPtr,System.Drawing.RectangleF,System.Drawing.Imaging.MetafileFrameUnit,System.String) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Drawing2D.Matrix.get_MatrixElements + runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.GetMetafileHeader(System.IntPtr) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Drawing2D.Matrix.set_MatrixElements(System.Numerics.Matrix3x2) + runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.Metafile.GetMetafileHeader(System.IntPtr,System.Drawing.Imaging.WmfPlaceableFileHeader) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Graphics.get_TransformElements + runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.PlayRecordCallback.#ctor(System.Object,System.IntPtr) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Graphics.GetContextInfo(System.Drawing.PointF@,System.Drawing.Region@) + runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.PlayRecordCallback.Invoke(System.Drawing.Imaging.EmfPlusRecordType,System.Int32,System.Int32,System.IntPtr) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Graphics.GetContextInfo(System.Drawing.PointF@) + runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true CP0002 - M:System.Drawing.Imaging.PlayRecordCallback.BeginInvoke(System.Drawing.Imaging.EmfPlusRecordType,System.Int32,System.Int32,System.IntPtr,System.AsyncCallback,System.Object) - lib/net6.0/System.Drawing.Common.dll - lib/net7.0/System.Drawing.Common.dll + M:System.Drawing.Graphics.set_TransformElements(System.Numerics.Matrix3x2) + runtimes/win/lib/netcoreapp3.1/System.Drawing.Common.dll + lib/netstandard2.0/System.Drawing.Common.dll + true \ No newline at end of file diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/CompatibilitySuppressions.xml b/src/libraries/System.Security.Cryptography.Pkcs/src/CompatibilitySuppressions.xml index 101c1df6149a27..94799c232756e3 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/CompatibilitySuppressions.xml +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/CompatibilitySuppressions.xml @@ -2,37 +2,37 @@ CP0002 - M:System.Security.Cryptography.Pkcs.CmsSigner.get_PrivateKey + M:System.Security.Cryptography.Pkcs.CmsSigner.#ctor(System.Security.Cryptography.Pkcs.SubjectIdentifierType,System.Security.Cryptography.X509Certificates.X509Certificate2,System.Security.Cryptography.AsymmetricAlgorithm) lib/netstandard2.0/System.Security.Cryptography.Pkcs.dll lib/net462/System.Security.Cryptography.Pkcs.dll CP0002 - M:System.Security.Cryptography.Pkcs.CmsSigner.set_PrivateKey(System.Security.Cryptography.AsymmetricAlgorithm) + M:System.Security.Cryptography.Pkcs.CmsSigner.#ctor(System.Security.Cryptography.Pkcs.SubjectIdentifierType,System.Security.Cryptography.X509Certificates.X509Certificate2,System.Security.Cryptography.RSA,System.Security.Cryptography.RSASignaturePadding) lib/netstandard2.0/System.Security.Cryptography.Pkcs.dll lib/net462/System.Security.Cryptography.Pkcs.dll CP0002 - M:System.Security.Cryptography.Pkcs.CmsSigner.get_SignaturePadding + M:System.Security.Cryptography.Pkcs.CmsSigner.get_PrivateKey lib/netstandard2.0/System.Security.Cryptography.Pkcs.dll lib/net462/System.Security.Cryptography.Pkcs.dll CP0002 - M:System.Security.Cryptography.Pkcs.CmsSigner.set_SignaturePadding(System.Security.Cryptography.RSASignaturePadding) + M:System.Security.Cryptography.Pkcs.CmsSigner.get_SignaturePadding lib/netstandard2.0/System.Security.Cryptography.Pkcs.dll lib/net462/System.Security.Cryptography.Pkcs.dll CP0002 - M:System.Security.Cryptography.Pkcs.CmsSigner.#ctor(System.Security.Cryptography.Pkcs.SubjectIdentifierType,System.Security.Cryptography.X509Certificates.X509Certificate2,System.Security.Cryptography.AsymmetricAlgorithm) + M:System.Security.Cryptography.Pkcs.CmsSigner.set_PrivateKey(System.Security.Cryptography.AsymmetricAlgorithm) lib/netstandard2.0/System.Security.Cryptography.Pkcs.dll lib/net462/System.Security.Cryptography.Pkcs.dll CP0002 - M:System.Security.Cryptography.Pkcs.CmsSigner.#ctor(System.Security.Cryptography.Pkcs.SubjectIdentifierType,System.Security.Cryptography.X509Certificates.X509Certificate2,System.Security.Cryptography.RSA,System.Security.Cryptography.RSASignaturePadding) + M:System.Security.Cryptography.Pkcs.CmsSigner.set_SignaturePadding(System.Security.Cryptography.RSASignaturePadding) lib/netstandard2.0/System.Security.Cryptography.Pkcs.dll lib/net462/System.Security.Cryptography.Pkcs.dll @@ -56,13 +56,13 @@ CP0002 - M:System.Security.Cryptography.Pkcs.SignedCms.Decode(System.ReadOnlySpan{System.Byte}) + M:System.Security.Cryptography.Pkcs.SignedCms.AddCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2) lib/netstandard2.0/System.Security.Cryptography.Pkcs.dll lib/net462/System.Security.Cryptography.Pkcs.dll CP0002 - M:System.Security.Cryptography.Pkcs.SignedCms.AddCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2) + M:System.Security.Cryptography.Pkcs.SignedCms.Decode(System.ReadOnlySpan{System.Byte}) lib/netstandard2.0/System.Security.Cryptography.Pkcs.dll lib/net462/System.Security.Cryptography.Pkcs.dll @@ -74,7 +74,7 @@ CP0002 - M:System.Security.Cryptography.Pkcs.SignerInfo.GetSignature + M:System.Security.Cryptography.Pkcs.SignerInfo.AddUnsignedAttribute(System.Security.Cryptography.AsnEncodedData) lib/netstandard2.0/System.Security.Cryptography.Pkcs.dll lib/net462/System.Security.Cryptography.Pkcs.dll @@ -86,7 +86,7 @@ CP0002 - M:System.Security.Cryptography.Pkcs.SignerInfo.AddUnsignedAttribute(System.Security.Cryptography.AsnEncodedData) + M:System.Security.Cryptography.Pkcs.SignerInfo.GetSignature lib/netstandard2.0/System.Security.Cryptography.Pkcs.dll lib/net462/System.Security.Cryptography.Pkcs.dll diff --git a/src/libraries/System.Security.Permissions/src/CompatibilitySuppressions.xml b/src/libraries/System.Security.Permissions/src/CompatibilitySuppressions.xml index 1f11b7c644c503..0b5944bdde9f57 100644 --- a/src/libraries/System.Security.Permissions/src/CompatibilitySuppressions.xml +++ b/src/libraries/System.Security.Permissions/src/CompatibilitySuppressions.xml @@ -1,14 +1,28 @@  + + CP0001 + T:System.Xaml.Permissions.XamlLoadPermission + lib/net5.0/System.Security.Permissions.dll + lib/netstandard2.0/System.Security.Permissions.dll + true + + + CP0001 + T:System.Xaml.Permissions.XamlLoadPermission + lib/netcoreapp3.1/System.Security.Permissions.dll + lib/netstandard2.0/System.Security.Permissions.dll + true + CP0002 - M:System.Security.Permissions.KeyContainerPermissionAccessEntryCollection.CopyTo(System.Array,System.Int32) + M:System.Security.Permissions.KeyContainerPermissionAccessEntryCollection.#ctor lib/netstandard2.0/System.Security.Permissions.dll lib/net462/System.Security.Permissions.dll CP0002 - M:System.Security.Permissions.KeyContainerPermissionAccessEntryCollection.#ctor + M:System.Security.Permissions.KeyContainerPermissionAccessEntryCollection.CopyTo(System.Array,System.Int32) lib/netstandard2.0/System.Security.Permissions.dll lib/net462/System.Security.Permissions.dll @@ -18,18 +32,4 @@ lib/netstandard2.0/System.Security.Permissions.dll lib/net462/System.Security.Permissions.dll - - CP0001 - T:System.Xaml.Permissions.XamlLoadPermission - lib/net5.0/System.Security.Permissions.dll - lib/netstandard2.0/System.Security.Permissions.dll - true - - - CP0001 - T:System.Xaml.Permissions.XamlLoadPermission - lib/netcoreapp3.1/System.Security.Permissions.dll - lib/netstandard2.0/System.Security.Permissions.dll - true - \ No newline at end of file diff --git a/src/libraries/System.ServiceModel.Syndication/src/CompatibilitySuppressions.xml b/src/libraries/System.ServiceModel.Syndication/src/CompatibilitySuppressions.xml index 9c30d11f2c34ec..9f92dd6ea61fb2 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/CompatibilitySuppressions.xml +++ b/src/libraries/System.ServiceModel.Syndication/src/CompatibilitySuppressions.xml @@ -1,117 +1,117 @@  - CP0002 - M:System.ServiceModel.Syndication.SyndicationFeed.get_Documentation + CP0001 + T:System.ServiceModel.Syndication.SyndicationTextInput lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll - CP0002 - M:System.ServiceModel.Syndication.SyndicationFeed.set_Documentation(System.ServiceModel.Syndication.SyndicationLink) + CP0001 + T:System.ServiceModel.Syndication.TryParseDateTimeCallback lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll - CP0002 - M:System.ServiceModel.Syndication.SyndicationFeed.get_TimeToLive + CP0001 + T:System.ServiceModel.Syndication.TryParseUriCallback lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll - CP0002 - M:System.ServiceModel.Syndication.SyndicationFeed.set_TimeToLive(System.Nullable{System.TimeSpan}) + CP0001 + T:System.ServiceModel.Syndication.XmlDateTimeData lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll - CP0002 - M:System.ServiceModel.Syndication.SyndicationFeed.get_SkipHours + CP0001 + T:System.ServiceModel.Syndication.XmlUriData lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll CP0002 - M:System.ServiceModel.Syndication.SyndicationFeed.get_SkipDays - lib/netstandard2.0/System.ServiceModel.Syndication.dll - lib/net462/System.ServiceModel.Syndication.dll + M:System.ServiceModel.Syndication.TryParseDateTimeCallback.#ctor(System.Object,System.IntPtr) + lib/net6.0/System.ServiceModel.Syndication.dll + lib/net7.0/System.ServiceModel.Syndication.dll CP0002 - M:System.ServiceModel.Syndication.SyndicationFeed.get_TextInput - lib/netstandard2.0/System.ServiceModel.Syndication.dll - lib/net462/System.ServiceModel.Syndication.dll + M:System.ServiceModel.Syndication.TryParseUriCallback.#ctor(System.Object,System.IntPtr) + lib/net6.0/System.ServiceModel.Syndication.dll + lib/net7.0/System.ServiceModel.Syndication.dll CP0002 - M:System.ServiceModel.Syndication.SyndicationFeed.set_TextInput(System.ServiceModel.Syndication.SyndicationTextInput) + M:System.ServiceModel.Syndication.SyndicationFeed.get_Documentation lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll CP0002 - M:System.ServiceModel.Syndication.SyndicationFeedFormatter.get_UriParser + M:System.ServiceModel.Syndication.SyndicationFeed.get_SkipDays lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll CP0002 - M:System.ServiceModel.Syndication.SyndicationFeedFormatter.set_UriParser(System.ServiceModel.Syndication.TryParseUriCallback) + M:System.ServiceModel.Syndication.SyndicationFeed.get_SkipHours lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll CP0002 - M:System.ServiceModel.Syndication.SyndicationFeedFormatter.get_DateTimeParser + M:System.ServiceModel.Syndication.SyndicationFeed.get_TextInput lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll CP0002 - M:System.ServiceModel.Syndication.SyndicationFeedFormatter.set_DateTimeParser(System.ServiceModel.Syndication.TryParseDateTimeCallback) + M:System.ServiceModel.Syndication.SyndicationFeed.get_TimeToLive lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll - CP0001 - T:System.ServiceModel.Syndication.TryParseDateTimeCallback + CP0002 + M:System.ServiceModel.Syndication.SyndicationFeed.set_Documentation(System.ServiceModel.Syndication.SyndicationLink) lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll - CP0001 - T:System.ServiceModel.Syndication.TryParseUriCallback + CP0002 + M:System.ServiceModel.Syndication.SyndicationFeed.set_TextInput(System.ServiceModel.Syndication.SyndicationTextInput) lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll - CP0001 - T:System.ServiceModel.Syndication.SyndicationTextInput + CP0002 + M:System.ServiceModel.Syndication.SyndicationFeed.set_TimeToLive(System.Nullable{System.TimeSpan}) lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll - CP0001 - T:System.ServiceModel.Syndication.XmlDateTimeData + CP0002 + M:System.ServiceModel.Syndication.SyndicationFeedFormatter.get_DateTimeParser lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll - CP0001 - T:System.ServiceModel.Syndication.XmlUriData + CP0002 + M:System.ServiceModel.Syndication.SyndicationFeedFormatter.get_UriParser lib/netstandard2.0/System.ServiceModel.Syndication.dll lib/net462/System.ServiceModel.Syndication.dll CP0002 - M:System.ServiceModel.Syndication.TryParseDateTimeCallback.#ctor(System.Object,System.IntPtr) - lib/net6.0/System.ServiceModel.Syndication.dll - lib/net7.0/System.ServiceModel.Syndication.dll + M:System.ServiceModel.Syndication.SyndicationFeedFormatter.set_DateTimeParser(System.ServiceModel.Syndication.TryParseDateTimeCallback) + lib/netstandard2.0/System.ServiceModel.Syndication.dll + lib/net462/System.ServiceModel.Syndication.dll CP0002 - M:System.ServiceModel.Syndication.TryParseUriCallback.#ctor(System.Object,System.IntPtr) - lib/net6.0/System.ServiceModel.Syndication.dll - lib/net7.0/System.ServiceModel.Syndication.dll + M:System.ServiceModel.Syndication.SyndicationFeedFormatter.set_UriParser(System.ServiceModel.Syndication.TryParseUriCallback) + lib/netstandard2.0/System.ServiceModel.Syndication.dll + lib/net462/System.ServiceModel.Syndication.dll \ No newline at end of file diff --git a/src/libraries/System.ServiceProcess.ServiceController/src/CompatibilitySuppressions.xml b/src/libraries/System.ServiceProcess.ServiceController/src/CompatibilitySuppressions.xml index 638e5bb77ee7b5..2f1011d9f94cfc 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/CompatibilitySuppressions.xml +++ b/src/libraries/System.ServiceProcess.ServiceController/src/CompatibilitySuppressions.xml @@ -1,5 +1,11 @@  + + CP0002 + M:System.ServiceProcess.ServiceBase.ServiceMainCallback(System.Int32,System.IntPtr) + lib/net6.0/System.ServiceProcess.ServiceController.dll + lib/net7.0/System.ServiceProcess.ServiceController.dll + CP0002 M:System.ServiceProcess.ServiceController.Stop(System.Boolean) @@ -21,10 +27,4 @@ runtimes/win/lib/netstandard2.0/System.ServiceProcess.ServiceController.dll true - - CP0002 - M:System.ServiceProcess.ServiceBase.ServiceMainCallback(System.Int32,System.IntPtr) - lib/net6.0/System.ServiceProcess.ServiceController.dll - lib/net7.0/System.ServiceProcess.ServiceController.dll - \ No newline at end of file diff --git a/src/libraries/System.Speech/src/CompatibilitySuppressions.xml b/src/libraries/System.Speech/src/CompatibilitySuppressions.xml index b667bd360eef2f..edd6950f7e5462 100644 --- a/src/libraries/System.Speech/src/CompatibilitySuppressions.xml +++ b/src/libraries/System.Speech/src/CompatibilitySuppressions.xml @@ -6,12 +6,6 @@ lib/net6.0/System.Speech.dll lib/net7.0/System.Speech.dll - - CP0006 - M:System.Speech.Synthesis.TtsEngine.ITtsEngineSite.Write(System.IntPtr,System.Int32) - lib/net6.0/System.Speech.dll - lib/net7.0/System.Speech.dll - CP0002 M:System.Speech.Synthesis.TtsEngine.SpeechEventInfo.#ctor(System.Int16,System.Int16,System.Int32,System.IntPtr) @@ -42,4 +36,10 @@ lib/net6.0/System.Speech.dll lib/net7.0/System.Speech.dll + + CP0006 + M:System.Speech.Synthesis.TtsEngine.ITtsEngineSite.Write(System.IntPtr,System.Int32) + lib/net6.0/System.Speech.dll + lib/net7.0/System.Speech.dll + \ No newline at end of file diff --git a/src/libraries/System.Windows.Extensions/src/CompatibilitySuppressions.xml b/src/libraries/System.Windows.Extensions/src/CompatibilitySuppressions.xml index e619274d554c8c..78e36df68161a0 100644 --- a/src/libraries/System.Windows.Extensions/src/CompatibilitySuppressions.xml +++ b/src/libraries/System.Windows.Extensions/src/CompatibilitySuppressions.xml @@ -1,13 +1,5 @@  - - PKV006 - .NETCoreApp,Version=v3.1 - - - PKV007 - .NETCoreApp,Version=v3.1-win - CP0002 M:System.Security.Cryptography.X509Certificates.X509Certificate2UI.DisplayCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2,System.IntPtr) @@ -20,4 +12,12 @@ lib/net6.0/System.Windows.Extensions.dll lib/net7.0/System.Windows.Extensions.dll + + PKV006 + .NETCoreApp,Version=v3.1 + + + PKV007 + .NETCoreApp,Version=v3.1-win + \ No newline at end of file From 2184b18d2f7414586455d72b108e3a3fa5ed5962 Mon Sep 17 00:00:00 2001 From: Anton Lapounov Date: Thu, 1 Sep 2022 17:00:32 -0700 Subject: [PATCH 077/107] Fix buffer overruns in GC code (#74847) --- src/coreclr/gc/gc.cpp | 21 +++++++++++++-------- src/coreclr/gc/windows/gcenv.windows.cpp | 2 +- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/coreclr/gc/gc.cpp b/src/coreclr/gc/gc.cpp index 207a62355dc738..ddca5bb7e1817d 100644 --- a/src/coreclr/gc/gc.cpp +++ b/src/coreclr/gc/gc.cpp @@ -6089,20 +6089,22 @@ class heap_select uint16_t proc_no[MAX_SUPPORTED_CPUS]; uint16_t node_no[MAX_SUPPORTED_CPUS]; uint16_t max_node_no = 0; - for (uint16_t i = 0; i < n_heaps; i++) + uint16_t heap_num; + for (heap_num = 0; heap_num < n_heaps; heap_num++) { - if (!GCToOSInterface::GetProcessorForHeap (i, &proc_no[i], &node_no[i])) + if (!GCToOSInterface::GetProcessorForHeap (heap_num, &proc_no[heap_num], &node_no[heap_num])) break; - if (!do_numa || node_no[i] == NUMA_NODE_UNDEFINED) - node_no[i] = 0; - max_node_no = max(max_node_no, node_no[i]); + assert(proc_no[heap_num] < MAX_SUPPORTED_CPUS); + if (!do_numa || node_no[heap_num] == NUMA_NODE_UNDEFINED) + node_no[heap_num] = 0; + max_node_no = max(max_node_no, node_no[heap_num]); } // Pass 2: assign heap numbers by numa node int cur_heap_no = 0; for (uint16_t cur_node_no = 0; cur_node_no <= max_node_no; cur_node_no++) { - for (int i = 0; i < n_heaps; i++) + for (int i = 0; i < heap_num; i++) { if (node_no[i] != cur_node_no) continue; @@ -44835,7 +44837,9 @@ HRESULT GCHeap::Initialize() nhp_from_config = static_cast(GCConfig::GetHeapCount()); - g_num_active_processors = GCToEEInterface::GetCurrentProcessCpuCount(); + // The CPU count may be overriden by the user. Ensure that we create no more than g_num_processors + // heaps as that is the number of slots we have allocated for handle tables. + g_num_active_processors = min (GCToEEInterface::GetCurrentProcessCpuCount(), g_num_processors); if (nhp_from_config) { @@ -44944,6 +44948,7 @@ HRESULT GCHeap::Initialize() #endif //USE_REGIONS #ifdef MULTIPLE_HEAPS + assert (nhp <= g_num_processors); gc_heap::n_heaps = nhp; hr = gc_heap::initialize_gc (seg_size, large_seg_size, pin_seg_size, nhp); #else @@ -44978,7 +44983,7 @@ HRESULT GCHeap::Initialize() int available_mem_th = 10; if (gc_heap::total_physical_mem >= ((uint64_t)80 * 1024 * 1024 * 1024)) { - int adjusted_available_mem_th = 3 + (int)((float)47 / (float)(GCToOSInterface::GetTotalProcessorCount())); + int adjusted_available_mem_th = 3 + (int)((float)47 / (float)g_num_processors); available_mem_th = min (available_mem_th, adjusted_available_mem_th); } diff --git a/src/coreclr/gc/windows/gcenv.windows.cpp b/src/coreclr/gc/windows/gcenv.windows.cpp index d8675e5e1060bb..be521a5946ea45 100644 --- a/src/coreclr/gc/windows/gcenv.windows.cpp +++ b/src/coreclr/gc/windows/gcenv.windows.cpp @@ -1190,7 +1190,7 @@ bool GCToOSInterface::GetProcessorForHeap(uint16_t heap_number, uint16_t* proc_n // Locate heap_number-th available processor uint16_t procIndex = 0; size_t cnt = heap_number; - for (uint16_t i = 0; i < GCToOSInterface::GetTotalProcessorCount(); i++) + for (uint16_t i = 0; i < MAX_SUPPORTED_CPUS; i++) { if (g_processAffinitySet.Contains(i)) { From b609e5349c5a5fb4aeee519745491cf60286ef41 Mon Sep 17 00:00:00 2001 From: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> Date: Thu, 1 Sep 2022 17:07:07 -0700 Subject: [PATCH 078/107] Change some exception types thrown in Tar APIs (#74845) * Throw ArgumentException on unsupported tar entry type * Adjust tests * Also change exception type for internal TarEntry conversion constructor called by all other public conversion constructors. Add missing test gap. * LinkName setter null check. * Internal constructors SeekableSubReadStream and SubReadStream unseekable exception should be ArgumentException. * DataStream setter for regular file should throw ArgumentException if passed an unreadable stream. * TarFile CreateFromDirectory unwritable destination change exception to ArgumentException. * Change to ArgumentException when ExtractToDirectory is an unreadable stream. Add missing exception docs. * Add some missing exception docs for TarEntry. * Change TarReader constructor exception if unreadable stream. Close test gap. * Change TarWriter exception for unwritable stream to ArgumentException, adjust docs and tests. * Add missing documentation for exceptions in constructors. * Change wording of conversion constructors comment when passing a Pax GEA entry. * Apply suggestions by Jozkee * Add exception to LinkName if the entry type is hard/symlink and the user tries to set an empty string. Add tests. * Convert all FormatException to InvalidDataException * Address more suggestions Co-authored-by: carlossanlop --- .../src/System/Formats/Tar/GnuTarEntry.cs | 9 +- .../src/System/Formats/Tar/PaxTarEntry.cs | 16 ++- .../Formats/Tar/SeekableSubReadStream.cs | 2 +- .../src/System/Formats/Tar/SubReadStream.cs | 2 +- .../src/System/Formats/Tar/TarEntry.cs | 27 ++--- .../src/System/Formats/Tar/TarFile.cs | 59 ++++++++++- .../src/System/Formats/Tar/TarHeader.Read.cs | 12 +-- .../src/System/Formats/Tar/TarHelpers.cs | 9 +- .../src/System/Formats/Tar/TarReader.cs | 29 +++--- .../src/System/Formats/Tar/TarWriter.Unix.cs | 2 +- .../System/Formats/Tar/TarWriter.Windows.cs | 2 +- .../src/System/Formats/Tar/TarWriter.cs | 16 +-- .../src/System/Formats/Tar/UstarTarEntry.cs | 9 +- .../src/System/Formats/Tar/V7TarEntry.cs | 9 +- .../tests/System.Formats.Tar.Tests.csproj | 1 + .../tests/TarEntry/GnuTarEntry.Tests.cs | 24 ++--- .../TarEntry/PaxTarEntry.Conversion.Tests.cs | 9 ++ .../tests/TarEntry/PaxTarEntry.Tests.cs | 24 ++--- .../TarEntry.Conversion.Tests.Base.cs | 2 +- .../tests/TarEntry/UstarTarEntry.Tests.cs | 24 ++--- .../TarEntry/V7TarEntry.Conversion.Tests.cs | 18 ++-- .../tests/TarEntry/V7TarEntry.Tests.cs | 30 +++--- ...arFile.CreateFromDirectory.Stream.Tests.cs | 2 +- ...e.CreateFromDirectoryAsync.Stream.Tests.cs | 2 +- ...TarFile.ExtractToDirectory.Stream.Tests.cs | 2 +- ...le.ExtractToDirectoryAsync.Stream.Tests.cs | 2 +- .../TarReader/TarReader.File.Async.Tests.cs | 4 +- .../tests/TarReader/TarReader.File.Tests.cs | 4 +- .../TarReader/TarReader.GetNextEntry.Tests.cs | 2 +- .../TarReader.GetNextEntryAsync.Tests.cs | 2 +- .../tests/TarReader/TarReader.Tests.cs | 98 +++++++++++++++++++ .../System.Formats.Tar/tests/TarTestsBase.cs | 15 ++- .../tests/TarWriter/TarWriter.Tests.cs | 4 +- .../TarWriter/TarWriter.WriteEntry.Tests.cs | 2 +- .../TarWriter.WriteEntryAsync.Tests.cs | 2 +- 35 files changed, 338 insertions(+), 138 deletions(-) create mode 100644 src/libraries/System.Formats.Tar/tests/TarReader/TarReader.Tests.cs diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/GnuTarEntry.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/GnuTarEntry.cs index eda97e2b8a26f0..11e3b77c5f8f2d 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/GnuTarEntry.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/GnuTarEntry.cs @@ -20,14 +20,16 @@ internal GnuTarEntry(TarHeader header, TarReader readerOfOrigin) /// /// The type of the entry. /// A string with the path and file name of this entry. - /// is null or empty. - /// The entry type is not supported for creating an entry. /// When creating an instance using the constructor, only the following entry types are supported: /// /// In all platforms: , , , . /// In Unix platforms only: , and . /// /// + /// is . + /// is empty. + /// -or- + /// is not supported in the specified format. public GnuTarEntry(TarEntryType entryType, string entryName) : base(entryType, entryName, TarEntryFormat.Gnu, isGea: false) { @@ -38,6 +40,9 @@ public GnuTarEntry(TarEntryType entryType, string entryName) /// /// Initializes a new instance by converting the specified entry into the GNU format. /// + /// is a and cannot be converted. + /// -or- + /// The entry type of is not supported for conversion to the GNU format. public GnuTarEntry(TarEntry other) : base(other, TarEntryFormat.Gnu) { diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/PaxTarEntry.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/PaxTarEntry.cs index db317f7a884112..555e4feaa27f73 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/PaxTarEntry.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/PaxTarEntry.cs @@ -25,8 +25,6 @@ internal PaxTarEntry(TarHeader header, TarReader readerOfOrigin) /// /// The type of the entry. /// A string with the path and file name of this entry. - /// is null or empty. - /// The entry type is not supported for creating an entry. /// When creating an instance using the constructor, only the following entry types are supported: /// /// In all platforms: , , , . @@ -47,6 +45,10 @@ internal PaxTarEntry(TarHeader header, TarReader readerOfOrigin) /// File length, under the name size, as an , if the string representation of the number is larger than 12 bytes. /// /// + /// is . + /// is empty. + /// -or- + /// is not supported in the specified format. public PaxTarEntry(TarEntryType entryType, string entryName) : base(entryType, entryName, TarEntryFormat.Pax, isGea: false) { @@ -62,9 +64,6 @@ public PaxTarEntry(TarEntryType entryType, string entryName) /// The type of the entry. /// A string with the path and file name of this entry. /// An enumeration of string key-value pairs that represents the metadata to include in the Extended Attributes entry that precedes the current entry. - /// is . - /// is null or empty. - /// The entry type is not supported for creating an entry. /// When creating an instance using the constructor, only the following entry types are supported: /// /// In all platforms: , , , . @@ -85,6 +84,10 @@ public PaxTarEntry(TarEntryType entryType, string entryName) /// File length, under the name size, as an , if the string representation of the number is larger than 12 bytes. /// /// + /// or is . + /// is empty. + /// -or- + /// is not supported in the specified format. public PaxTarEntry(TarEntryType entryType, string entryName, IEnumerable> extendedAttributes) : base(entryType, entryName, TarEntryFormat.Pax, isGea: false) { @@ -100,6 +103,9 @@ public PaxTarEntry(TarEntryType entryType, string entryName, IEnumerable /// Initializes a new instance by converting the specified entry into the PAX format. /// + /// is a and cannot be converted. + /// -or- + /// The entry type of is not supported for conversion to the PAX format. public PaxTarEntry(TarEntry other) : base(other, TarEntryFormat.Pax) { diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/SeekableSubReadStream.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/SeekableSubReadStream.cs index e8fe9b7e01a16f..b35c958b4d53f0 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/SeekableSubReadStream.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/SeekableSubReadStream.cs @@ -18,7 +18,7 @@ public SeekableSubReadStream(Stream superStream, long startPosition, long maxLen { if (!superStream.CanSeek) { - throw new InvalidOperationException(SR.IO_NotSupported_UnseekableStream); + throw new ArgumentException(SR.IO_NotSupported_UnseekableStream, nameof(superStream)); } } diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/SubReadStream.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/SubReadStream.cs index 014165939ac1c7..998e53ea6fc99f 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/SubReadStream.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/SubReadStream.cs @@ -25,7 +25,7 @@ public SubReadStream(Stream superStream, long startPosition, long maxLength) { if (!superStream.CanRead) { - throw new InvalidOperationException(SR.IO_NotSupported_UnreadableStream); + throw new ArgumentException(SR.IO_NotSupported_UnreadableStream, nameof(superStream)); } _startInSuperStream = startPosition; _positionInSuperStream = startPosition; diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs index 9c2f0553eb39bf..a27df41f4c1c6a 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.cs @@ -51,12 +51,12 @@ internal TarEntry(TarEntry other, TarEntryFormat format) { if (other is PaxGlobalExtendedAttributesTarEntry) { - throw new InvalidOperationException(SR.TarCannotConvertPaxGlobalExtendedAttributesEntry); + throw new ArgumentException(SR.TarCannotConvertPaxGlobalExtendedAttributesEntry, nameof(other)); } TarEntryType compatibleEntryType = TarHelpers.GetCorrectTypeFlagForFormat(format, other.EntryType); - TarHelpers.ThrowIfEntryTypeNotSupported(compatibleEntryType, format); + TarHelpers.ThrowIfEntryTypeNotSupported(compatibleEntryType, format, nameof(other)); _readerOfOrigin = other._readerOfOrigin; @@ -92,6 +92,7 @@ public int Gid /// A timestamps that represents the last time the contents of the file represented by this entry were modified. /// /// In Unix platforms, this timestamp is commonly known as mtime. + /// The specified value is larger than . public DateTimeOffset ModificationTime { get => _header._mTime; @@ -114,7 +115,9 @@ public DateTimeOffset ModificationTime /// /// When the indicates a or a , this property returns the link target path of such link. /// - /// Cannot set the link name if the entry type is not or . + /// The entry type is not or . + /// The specified value is . + /// The specified value is empty. public string LinkName { get => _header._linkName ?? string.Empty; @@ -124,6 +127,7 @@ public string LinkName { throw new InvalidOperationException(SR.TarEntryHardLinkOrSymLinkExpected); } + ArgumentException.ThrowIfNullOrEmpty(value); _header._linkName = value; } } @@ -177,7 +181,8 @@ public int Uid /// Elevation is required to extract a or to disk. /// Symbolic links can be recreated using , or . /// Hard links can only be extracted when using or . - /// is or empty. + /// is . + /// is empty. /// The parent directory of does not exist. /// -or- /// is and a file already exists in . @@ -206,7 +211,8 @@ public void ExtractToFile(string destinationFileName, bool overwrite) /// A task that represents the asynchronous extraction operation. /// Files of type , or can only be extracted in Unix platforms. /// Elevation is required to extract a or to disk. - /// is or empty. + /// is . + /// is empty. /// The parent directory of does not exist. /// -or- /// is and a file already exists in . @@ -237,9 +243,8 @@ public Task ExtractToFileAsync(string destinationFileName, bool overwrite, Cance /// Sets a new stream that represents the data section, if it makes sense for the to contain data; if a stream already existed, the old stream gets disposed before substituting it with the new stream. Setting a stream is allowed. /// If you write data to this data stream, make sure to rewind it to the desired start position before writing this entry into an archive using . /// Setting a data section is not supported because the is not (or for an archive of format). - /// Cannot set an unreadable stream. - /// -or- - /// An I/O problem occurred. + /// Cannot set an unreadable stream. + /// An I/O problem occurred. public Stream? DataStream { get => _header._dataStream; @@ -252,7 +257,7 @@ public Stream? DataStream if (value != null && !value.CanRead) { - throw new IOException(SR.IO_NotSupported_UnreadableStream); + throw new ArgumentException(SR.IO_NotSupported_UnreadableStream, nameof(value)); } if (_readerOfOrigin != null) @@ -339,7 +344,7 @@ internal Task ExtractRelativeToDirectoryAsync(string destinationDirectoryPath, b { if (string.IsNullOrEmpty(LinkName)) { - throw new FormatException(SR.TarEntryHardLinkOrSymlinkLinkNameEmpty); + throw new InvalidDataException(SR.TarEntryHardLinkOrSymlinkLinkNameEmpty); } linkTargetPath = GetSanitizedFullPath(destinationDirectoryPath, LinkName); @@ -511,7 +516,7 @@ private void VerifyPathsForEntryType(string filePath, string? linkTargetPath, bo } else { - throw new FormatException(SR.TarEntryHardLinkOrSymlinkLinkNameEmpty); + throw new InvalidDataException(SR.TarEntryHardLinkOrSymlinkLinkNameEmpty); } } } diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarFile.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarFile.cs index 2e490747df80d0..41d95ed7fd9e62 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarFile.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarFile.cs @@ -22,6 +22,12 @@ public static class TarFile /// The path of the directory to archive. /// The destination stream the archive. /// to include the base directory name as the first segment in all the names of the archive entries. to exclude the base directory name from the archive entry names. + /// or is . + /// is empty. + /// -or- + /// does not support writing. + /// The directory path was not found. + /// An I/O exception occurred. public static void CreateFromDirectory(string sourceDirectoryName, Stream destination, bool includeBaseDirectory) { ArgumentException.ThrowIfNullOrEmpty(sourceDirectoryName); @@ -29,7 +35,7 @@ public static void CreateFromDirectory(string sourceDirectoryName, Stream destin if (!destination.CanWrite) { - throw new IOException(SR.IO_NotSupported_UnwritableStream); + throw new ArgumentException(SR.IO_NotSupported_UnwritableStream, nameof(destination)); } if (!Directory.Exists(sourceDirectoryName)) @@ -51,6 +57,12 @@ public static void CreateFromDirectory(string sourceDirectoryName, Stream destin /// to include the base directory name as the first path segment in all the names of the archive entries. to exclude the base directory name from the entry name paths. /// The token to monitor for cancellation requests. The default value is . /// A task that represents the asynchronous creation operation. + /// or is . + /// is empty. + /// -or- + /// does not support writing. + /// The directory path was not found. + /// An I/O exception occurred. public static Task CreateFromDirectoryAsync(string sourceDirectoryName, Stream destination, bool includeBaseDirectory, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) @@ -62,7 +74,7 @@ public static Task CreateFromDirectoryAsync(string sourceDirectoryName, Stream d if (!destination.CanWrite) { - return Task.FromException(new IOException(SR.IO_NotSupported_UnwritableStream)); + return Task.FromException(new ArgumentException(SR.IO_NotSupported_UnwritableStream, nameof(destination))); } if (!Directory.Exists(sourceDirectoryName)) @@ -82,6 +94,10 @@ public static Task CreateFromDirectoryAsync(string sourceDirectoryName, Stream d /// The path of the directory to archive. /// The path of the destination archive file. /// to include the base directory name as the first path segment in all the names of the archive entries. to exclude the base directory name from the entry name paths. + /// or is . + /// or is empty. + /// The directory path was not found. + /// An I/O exception occurred. public static void CreateFromDirectory(string sourceDirectoryName, string destinationFileName, bool includeBaseDirectory) { ArgumentException.ThrowIfNullOrEmpty(sourceDirectoryName); @@ -110,6 +126,10 @@ public static void CreateFromDirectory(string sourceDirectoryName, string destin /// to include the base directory name as the first path segment in all the names of the archive entries. to exclude the base directory name from the entry name paths. /// The token to monitor for cancellation requests. The default value is . /// A task that represents the asynchronous creation operation. + /// or is . + /// or is empty. + /// The directory path was not found. + /// An I/O exception occurred. public static Task CreateFromDirectoryAsync(string sourceDirectoryName, string destinationFileName, bool includeBaseDirectory, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) @@ -139,8 +159,15 @@ public static Task CreateFromDirectoryAsync(string sourceDirectoryName, string d /// to overwrite files and directories in ; to avoid overwriting, and throw if any files or directories are found with existing names. /// Files of type , or can only be extracted in Unix platforms. /// Elevation is required to extract a or to disk. + /// or is . + /// The directory path was not found. /// Operation not permitted due to insufficient permissions. - /// Extracting tar entry would have resulted in a file outside the specified destination directory. + /// Extracting tar entry would have resulted in a file outside the specified destination directory. + /// -or- + /// is empty. + /// -or- + /// does not support reading. + /// An I/O exception occurred. public static void ExtractToDirectory(Stream source, string destinationDirectoryName, bool overwriteFiles) { ArgumentNullException.ThrowIfNull(source); @@ -148,7 +175,7 @@ public static void ExtractToDirectory(Stream source, string destinationDirectory if (!source.CanRead) { - throw new IOException(SR.IO_NotSupported_UnreadableStream); + throw new ArgumentException(SR.IO_NotSupported_UnreadableStream, nameof(source)); } if (!Directory.Exists(destinationDirectoryName)) @@ -172,7 +199,15 @@ public static void ExtractToDirectory(Stream source, string destinationDirectory /// A task that represents the asynchronous extraction operation. /// Files of type , or can only be extracted in Unix platforms. /// Elevation is required to extract a or to disk. + /// or is . + /// The directory path was not found. /// Operation not permitted due to insufficient permissions. + /// Extracting tar entry would have resulted in a file outside the specified destination directory. + /// -or- + /// is empty. + /// -or- + /// does not support reading. + /// An I/O exception occurred. public static Task ExtractToDirectoryAsync(Stream source, string destinationDirectoryName, bool overwriteFiles, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) @@ -184,7 +219,7 @@ public static Task ExtractToDirectoryAsync(Stream source, string destinationDire if (!source.CanRead) { - return Task.FromException(new IOException(SR.IO_NotSupported_UnreadableStream)); + return Task.FromException(new ArgumentException(SR.IO_NotSupported_UnreadableStream, nameof(source))); } if (!Directory.Exists(destinationDirectoryName)) @@ -206,7 +241,14 @@ public static Task ExtractToDirectoryAsync(Stream source, string destinationDire /// to overwrite files and directories in ; to avoid overwriting, and throw if any files or directories are found with existing names. /// Files of type , or can only be extracted in Unix platforms. /// Elevation is required to extract a or to disk. + /// or is . + /// The directory path was not found. + /// The file path was not found. /// Operation not permitted due to insufficient permissions. + /// Extracting tar entry would have resulted in a file outside the specified destination directory. + /// -or- + /// or is empty. + /// An I/O exception occurred. public static void ExtractToDirectory(string sourceFileName, string destinationDirectoryName, bool overwriteFiles) { ArgumentException.ThrowIfNullOrEmpty(sourceFileName); @@ -241,7 +283,14 @@ public static void ExtractToDirectory(string sourceFileName, string destinationD /// A task that represents the asynchronous extraction operation. /// Files of type , or can only be extracted in Unix platforms. /// Elevation is required to extract a or to disk. + /// or is . + /// The directory path was not found. + /// The file path was not found. /// Operation not permitted due to insufficient permissions. + /// Extracting tar entry would have resulted in a file outside the specified destination directory. + /// -or- + /// or is empty. + /// An I/O exception occurred. public static Task ExtractToDirectoryAsync(string sourceFileName, string destinationDirectoryName, bool overwriteFiles, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Read.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Read.cs index 5578707d64eb18..ce37a74c304c80 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Read.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Read.cs @@ -201,7 +201,7 @@ internal void ProcessDataBlock(Stream archiveStream, bool copyData) // No data section if (_size > 0) { - throw new FormatException(string.Format(SR.TarSizeFieldTooLargeForEntryType, _typeFlag)); + throw new InvalidDataException(string.Format(SR.TarSizeFieldTooLargeForEntryType, _typeFlag)); } break; case TarEntryType.RegularFile: @@ -263,7 +263,7 @@ private async Task ProcessDataBlockAsync(Stream archiveStream, bool copyData, Ca // No data section if (_size > 0) { - throw new FormatException(string.Format(SR.TarSizeFieldTooLargeForEntryType, _typeFlag)); + throw new InvalidDataException(string.Format(SR.TarSizeFieldTooLargeForEntryType, _typeFlag)); } break; case TarEntryType.RegularFile: @@ -379,7 +379,7 @@ private async Task ProcessDataBlockAsync(Stream archiveStream, bool copyData, Ca long size = (int)TarHelpers.ParseOctal(buffer.Slice(FieldLocations.Size, FieldLengths.Size)); if (size < 0) { - throw new FormatException(string.Format(SR.TarSizeFieldNegative)); + throw new InvalidDataException(string.Format(SR.TarSizeFieldNegative)); } // Continue with the rest of the fields that require no special checks @@ -477,7 +477,7 @@ private void ReadVersionAttribute(Span buffer) // Check for gnu version header for mixed case if (!version.SequenceEqual(GnuVersionBytes)) { - throw new FormatException(string.Format(SR.TarPosixFormatExpected, _name)); + throw new InvalidDataException(string.Format(SR.TarPosixFormatExpected, _name)); } _version = GnuVersion; @@ -495,7 +495,7 @@ private void ReadVersionAttribute(Span buffer) // Check for ustar or pax version header for mixed case if (!version.SequenceEqual(UstarVersionBytes)) { - throw new FormatException(string.Format(SR.TarGnuFormatExpected, _name)); + throw new InvalidDataException(string.Format(SR.TarGnuFormatExpected, _name)); } _version = UstarVersion; @@ -626,7 +626,7 @@ private void ReadExtendedAttributesFromBuffer(ReadOnlySpan buffer, string { if (!ExtendedAttributes.TryAdd(key, value)) { - throw new FormatException(string.Format(SR.TarDuplicateExtendedAttribute, name)); + throw new InvalidDataException(string.Format(SR.TarDuplicateExtendedAttribute, name)); } } } diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHelpers.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHelpers.cs index c2a1b3b854c14b..fb12a2d3faa74e 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHelpers.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHelpers.cs @@ -7,6 +7,7 @@ using System.Globalization; using System.IO; using System.Numerics; +using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -228,7 +229,7 @@ internal static T ParseOctal(ReadOnlySpan buffer) where T : struct, INu [DoesNotReturn] private static void ThrowInvalidNumber() => - throw new FormatException(SR.Format(SR.TarInvalidNumber)); + throw new InvalidDataException(SR.Format(SR.TarInvalidNumber)); // Returns the string contained in the specified buffer of bytes, // in the specified encoding, removing the trailing null or space chars. @@ -291,7 +292,7 @@ internal static async ValueTask SkipBlockAlignmentPaddingAsync(Stream archi } // Throws if the specified entry type is not supported for the specified format. - internal static void ThrowIfEntryTypeNotSupported(TarEntryType entryType, TarEntryFormat archiveFormat) + internal static void ThrowIfEntryTypeNotSupported(TarEntryType entryType, TarEntryFormat archiveFormat, [CallerArgumentExpression("entryType")] string? paramName = null) { switch (archiveFormat) { @@ -365,10 +366,10 @@ TarEntryType.RegularFile or case TarEntryFormat.Unknown: default: - throw new FormatException(string.Format(SR.TarInvalidFormat, archiveFormat)); + throw new InvalidDataException(string.Format(SR.TarInvalidFormat, archiveFormat)); } - throw new InvalidOperationException(string.Format(SR.TarEntryTypeNotSupportedInFormat, entryType, archiveFormat)); + throw new ArgumentException(string.Format(SR.TarEntryTypeNotSupportedInFormat, entryType, archiveFormat), paramName); } } } diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarReader.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarReader.cs index 5328d61190280b..ae815dc0073b46 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarReader.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarReader.cs @@ -27,15 +27,16 @@ public sealed class TarReader : IDisposable, IAsyncDisposable /// Initializes a instance that can read tar entries from the specified stream, and can optionally leave the stream open upon disposal of this instance. /// /// The stream to read from. - /// to dispose the when this instance is disposed; to leave the stream open. - /// is unreadable. + /// to dispose the when this instance is disposed, as well as all the non-null instances from the entries that were visited by this reader; to leave all the streams open. + /// does not support reading. + /// is . public TarReader(Stream archiveStream, bool leaveOpen = false) { ArgumentNullException.ThrowIfNull(archiveStream); if (!archiveStream.CanRead) { - throw new IOException(SR.IO_NotSupported_UnreadableStream); + throw new ArgumentException(SR.IO_NotSupported_UnreadableStream, nameof(archiveStream)); } _archiveStream = archiveStream; @@ -47,7 +48,7 @@ public TarReader(Stream archiveStream, bool leaveOpen = false) } /// - /// Disposes the current instance, and disposes the streams of all the entries that were read from the archive. + /// Disposes the current instance, and disposes the non-null instances of all the entries that were read from the archive. /// /// The property of any entry can be replaced with a new stream. If the user decides to replace it on a instance that was obtained using a , the underlying stream gets disposed immediately, freeing the of origin from the responsibility of having to dispose it. public void Dispose() @@ -67,7 +68,7 @@ public void Dispose() } /// - /// Asynchronously disposes the current instance, and disposes the streams of all the entries that were read from the archive. + /// Asynchronously disposes the current instance, and disposes the non-null instances of all the entries that were read from the archive. /// /// The property of any entry can be replaced with a new stream. If the user decides to replace it on a instance that was obtained using a , the underlying stream gets disposed immediately, freeing the of origin from the responsibility of having to dispose it. public async ValueTask DisposeAsync() @@ -93,7 +94,7 @@ public async ValueTask DisposeAsync() /// Set it to if the data should not be copied into a new stream. If the underlying stream is unseekable, the user has the responsibility of reading and processing the immediately after calling this method. /// The default value is . /// A instance if a valid entry was found, or if the end of the archive has been reached. - /// The archive is malformed. + /// The entry's data is malformed. /// -or- /// The archive contains entries in different formats. /// -or- @@ -153,7 +154,7 @@ public async ValueTask DisposeAsync() /// The default value is . /// The token to monitor for cancellation requests. The default value is . /// A value task containing a instance if a valid entry was found, or if the end of the archive has been reached. - /// The archive is malformed. + /// The archive is malformed. /// -or- /// The archive contains entries in different formats. /// -or- @@ -400,7 +401,7 @@ TarEntryType.ExtendedAttributes or TarEntryType.LongLink or TarEntryType.LongPath) { - throw new FormatException(string.Format(SR.TarUnexpectedMetadataEntry, actualHeader._typeFlag, TarEntryType.ExtendedAttributes)); + throw new InvalidDataException(string.Format(SR.TarUnexpectedMetadataEntry, actualHeader._typeFlag, TarEntryType.ExtendedAttributes)); } // Replace all the attributes representing standard fields with the extended ones, if any @@ -432,13 +433,13 @@ TarEntryType.ExtendedAttributes or TarEntryType.LongLink or TarEntryType.LongPath) { - throw new FormatException(string.Format(SR.TarUnexpectedMetadataEntry, actualHeader._typeFlag, TarEntryType.ExtendedAttributes)); + throw new InvalidDataException(string.Format(SR.TarUnexpectedMetadataEntry, actualHeader._typeFlag, TarEntryType.ExtendedAttributes)); } // Can't have two extended attribute metadata entries in a row if (actualHeader._typeFlag is TarEntryType.ExtendedAttributes) { - throw new FormatException(string.Format(SR.TarUnexpectedMetadataEntry, TarEntryType.ExtendedAttributes, TarEntryType.ExtendedAttributes)); + throw new InvalidDataException(string.Format(SR.TarUnexpectedMetadataEntry, TarEntryType.ExtendedAttributes, TarEntryType.ExtendedAttributes)); } // Replace all the attributes representing standard fields with the extended ones, if any @@ -467,7 +468,7 @@ private bool TryProcessGnuMetadataHeader(TarHeader header, bool copyData, out Ta // Can't have two identical metadata entries in a row if (secondHeader._typeFlag == header._typeFlag) { - throw new FormatException(string.Format(SR.TarUnexpectedMetadataEntry, secondHeader._typeFlag, header._typeFlag)); + throw new InvalidDataException(string.Format(SR.TarUnexpectedMetadataEntry, secondHeader._typeFlag, header._typeFlag)); } // It's possible to have the two different metadata entries in a row @@ -485,7 +486,7 @@ private bool TryProcessGnuMetadataHeader(TarHeader header, bool copyData, out Ta // Can't have three GNU metadata entries in a row if (thirdHeader._typeFlag is TarEntryType.LongLink or TarEntryType.LongPath) { - throw new FormatException(string.Format(SR.TarUnexpectedMetadataEntry, thirdHeader._typeFlag, secondHeader._typeFlag)); + throw new InvalidDataException(string.Format(SR.TarUnexpectedMetadataEntry, thirdHeader._typeFlag, secondHeader._typeFlag)); } if (header._typeFlag is TarEntryType.LongLink) @@ -542,7 +543,7 @@ private bool TryProcessGnuMetadataHeader(TarHeader header, bool copyData, out Ta // Can't have two identical metadata entries in a row if (secondHeader._typeFlag == header._typeFlag) { - throw new FormatException(string.Format(SR.TarUnexpectedMetadataEntry, secondHeader._typeFlag, header._typeFlag)); + throw new InvalidDataException(string.Format(SR.TarUnexpectedMetadataEntry, secondHeader._typeFlag, header._typeFlag)); } TarHeader finalHeader; @@ -561,7 +562,7 @@ private bool TryProcessGnuMetadataHeader(TarHeader header, bool copyData, out Ta // Can't have three GNU metadata entries in a row if (thirdHeader._typeFlag is TarEntryType.LongLink or TarEntryType.LongPath) { - throw new FormatException(string.Format(SR.TarUnexpectedMetadataEntry, thirdHeader._typeFlag, secondHeader._typeFlag)); + throw new InvalidDataException(string.Format(SR.TarUnexpectedMetadataEntry, thirdHeader._typeFlag, secondHeader._typeFlag)); } if (header._typeFlag is TarEntryType.LongLink) diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.Unix.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.Unix.cs index 28eaf1e3323237..a691582178df6a 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.Unix.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.Unix.cs @@ -46,7 +46,7 @@ private TarEntry ConstructEntryForWriting(string fullPath, string entryName, Fil TarEntryFormat.Ustar => new UstarTarEntry(entryType, entryName), TarEntryFormat.Pax => new PaxTarEntry(entryType, entryName), TarEntryFormat.Gnu => new GnuTarEntry(entryType, entryName), - _ => throw new FormatException(string.Format(SR.TarInvalidFormat, Format)), + _ => throw new InvalidDataException(string.Format(SR.TarInvalidFormat, Format)), }; if (entryType is TarEntryType.BlockDevice or TarEntryType.CharacterDevice) diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.Windows.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.Windows.cs index d3fa19a5b12eac..7452246f742ed6 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.Windows.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.Windows.cs @@ -45,7 +45,7 @@ private TarEntry ConstructEntryForWriting(string fullPath, string entryName, Fil TarEntryFormat.Ustar => new UstarTarEntry(entryType, entryName), TarEntryFormat.Pax => new PaxTarEntry(entryType, entryName), TarEntryFormat.Gnu => new GnuTarEntry(entryType, entryName), - _ => throw new FormatException(string.Format(SR.TarInvalidFormat, Format)), + _ => throw new InvalidDataException(string.Format(SR.TarInvalidFormat, Format)), }; FileSystemInfo info = (attributes & FileAttributes.Directory) != 0 ? new DirectoryInfo(fullPath) : new FileInfo(fullPath); diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.cs index 7d3977eda68df4..b2d144a0bf6a7d 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.cs @@ -25,6 +25,8 @@ public sealed partial class TarWriter : IDisposable, IAsyncDisposable /// /// The stream to write to. /// When using this constructor, is used as the default format of the entries written to the archive using the method. + /// is . + /// does not support writing. public TarWriter(Stream archiveStream) : this(archiveStream, TarEntryFormat.Pax, leaveOpen: false) { @@ -35,6 +37,8 @@ public TarWriter(Stream archiveStream) /// /// The stream to write to. /// to dispose the when this instance is disposed; to leave the stream open. + /// is . + /// is unwritable. public TarWriter(Stream archiveStream, bool leaveOpen = false) : this(archiveStream, TarEntryFormat.Pax, leaveOpen) { @@ -50,7 +54,7 @@ public TarWriter(Stream archiveStream, bool leaveOpen = false) /// to leave the stream open. The default is . /// The recommended format is for its flexibility. /// is . - /// is unwritable. + /// is unwritable. /// is either , or not one of the other enum values. public TarWriter(Stream archiveStream, TarEntryFormat format = TarEntryFormat.Pax, bool leaveOpen = false) { @@ -58,7 +62,7 @@ public TarWriter(Stream archiveStream, TarEntryFormat format = TarEntryFormat.Pa if (!archiveStream.CanWrite) { - throw new IOException(SR.IO_NotSupported_UnwritableStream); + throw new ArgumentException(SR.IO_NotSupported_UnwritableStream); } if (format is not TarEntryFormat.V7 and not TarEntryFormat.Ustar and not TarEntryFormat.Pax and not TarEntryFormat.Gnu) @@ -210,7 +214,7 @@ private async Task ReadFileFromDiskAndWriteToArchiveStreamAsEntryAsync(string fu /// /// /// The archive stream is disposed. - /// The entry type of the is not supported for writing. + /// is . /// An I/O problem occurred. public void WriteEntry(TarEntry entry) { @@ -251,7 +255,7 @@ public void WriteEntry(TarEntry entry) /// /// /// The archive stream is disposed. - /// The entry type of the is not supported for writing. + /// is . /// An I/O problem occurred. public Task WriteEntryAsync(TarEntry entry, CancellationToken cancellationToken = default) { @@ -298,7 +302,7 @@ private void WriteEntryInternal(TarEntry entry) default: Debug.Assert(entry.Format == TarEntryFormat.Unknown, "Missing format handler"); - throw new FormatException(string.Format(SR.TarInvalidFormat, Format)); + throw new InvalidDataException(string.Format(SR.TarInvalidFormat, Format)); } _wroteEntries = true; @@ -320,7 +324,7 @@ private async Task WriteEntryAsyncInternal(TarEntry entry, CancellationToken can TarEntryFormat.Pax when entry._header._typeFlag is TarEntryType.GlobalExtendedAttributes => entry._header.WriteAsPaxGlobalExtendedAttributesAsync(_archiveStream, buffer, _nextGlobalExtendedAttributesEntryNumber++, cancellationToken), TarEntryFormat.Pax => entry._header.WriteAsPaxAsync(_archiveStream, buffer, cancellationToken), TarEntryFormat.Gnu => entry._header.WriteAsGnuAsync(_archiveStream, buffer, cancellationToken), - _ => throw new FormatException(string.Format(SR.TarInvalidFormat, Format)), + _ => throw new InvalidDataException(string.Format(SR.TarInvalidFormat, Format)), }; await task.ConfigureAwait(false); diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/UstarTarEntry.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/UstarTarEntry.cs index 10c5aad7325ade..9969520d96551c 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/UstarTarEntry.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/UstarTarEntry.cs @@ -19,14 +19,16 @@ internal UstarTarEntry(TarHeader header, TarReader readerOfOrigin) /// /// The type of the entry. /// A string with the path and file name of this entry. - /// is null or empty. - /// The entry type is not supported for creating an entry. /// When creating an instance using the constructor, only the following entry types are supported: /// /// In all platforms: , , , . /// In Unix platforms only: , and . /// /// + /// is . + /// is empty. + /// -or- + /// is not supported in the specified format. public UstarTarEntry(TarEntryType entryType, string entryName) : base(entryType, entryName, TarEntryFormat.Ustar, isGea: false) { @@ -36,6 +38,9 @@ public UstarTarEntry(TarEntryType entryType, string entryName) /// /// Initializes a new instance by converting the specified entry into the Ustar format. /// + /// is a and cannot be converted. + /// -or- + /// The entry type of is not supported for conversion to the Ustar format. public UstarTarEntry(TarEntry other) : base(other, TarEntryFormat.Ustar) { diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/V7TarEntry.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/V7TarEntry.cs index fd049c05d90c93..4b20f10faf4beb 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/V7TarEntry.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/V7TarEntry.cs @@ -19,9 +19,11 @@ internal V7TarEntry(TarHeader header, TarReader readerOfOrigin) /// /// The type of the entry. /// A string with the path and file name of this entry. - /// is null or empty. - /// The entry type is not supported for creating an entry. /// When creating an instance using the constructor, only the following entry types are supported: , , and . + /// is . + /// is empty. + /// -or- + /// is not supported for creating an entry. public V7TarEntry(TarEntryType entryType, string entryName) : base(entryType, entryName, TarEntryFormat.V7, isGea: false) { @@ -30,6 +32,9 @@ public V7TarEntry(TarEntryType entryType, string entryName) /// /// Initializes a new instance by converting the specified entry into the V7 format. /// + /// is a and cannot be converted. + /// -or- + /// The entry type of is not supported for conversion to the V7 format. public V7TarEntry(TarEntry other) : base(other, TarEntryFormat.V7) { diff --git a/src/libraries/System.Formats.Tar/tests/System.Formats.Tar.Tests.csproj b/src/libraries/System.Formats.Tar/tests/System.Formats.Tar.Tests.csproj index f06e639b74f564..c43c8dff343f23 100644 --- a/src/libraries/System.Formats.Tar/tests/System.Formats.Tar.Tests.csproj +++ b/src/libraries/System.Formats.Tar/tests/System.Formats.Tar.Tests.csproj @@ -40,6 +40,7 @@ + diff --git a/src/libraries/System.Formats.Tar/tests/TarEntry/GnuTarEntry.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarEntry/GnuTarEntry.Tests.cs index e9bb630dd3f873..4c13273a30ceaf 100644 --- a/src/libraries/System.Formats.Tar/tests/TarEntry/GnuTarEntry.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarEntry/GnuTarEntry.Tests.cs @@ -19,23 +19,23 @@ public void Constructor_InvalidEntryName() [Fact] public void Constructor_UnsupportedEntryTypes() { - Assert.Throws(() => new GnuTarEntry((TarEntryType)byte.MaxValue, InitialEntryName)); + Assert.Throws(() => new GnuTarEntry((TarEntryType)byte.MaxValue, InitialEntryName)); - Assert.Throws(() => new GnuTarEntry(TarEntryType.ExtendedAttributes, InitialEntryName)); - Assert.Throws(() => new GnuTarEntry(TarEntryType.GlobalExtendedAttributes, InitialEntryName)); - Assert.Throws(() => new GnuTarEntry(TarEntryType.V7RegularFile, InitialEntryName)); + Assert.Throws(() => new GnuTarEntry(TarEntryType.ExtendedAttributes, InitialEntryName)); + Assert.Throws(() => new GnuTarEntry(TarEntryType.GlobalExtendedAttributes, InitialEntryName)); + Assert.Throws(() => new GnuTarEntry(TarEntryType.V7RegularFile, InitialEntryName)); // These are specific to GNU, but currently the user cannot create them manually - Assert.Throws(() => new GnuTarEntry(TarEntryType.ContiguousFile, InitialEntryName)); - Assert.Throws(() => new GnuTarEntry(TarEntryType.DirectoryList, InitialEntryName)); - Assert.Throws(() => new GnuTarEntry(TarEntryType.MultiVolume, InitialEntryName)); - Assert.Throws(() => new GnuTarEntry(TarEntryType.RenamedOrSymlinked, InitialEntryName)); - Assert.Throws(() => new GnuTarEntry(TarEntryType.SparseFile, InitialEntryName)); - Assert.Throws(() => new GnuTarEntry(TarEntryType.TapeVolume, InitialEntryName)); + Assert.Throws(() => new GnuTarEntry(TarEntryType.ContiguousFile, InitialEntryName)); + Assert.Throws(() => new GnuTarEntry(TarEntryType.DirectoryList, InitialEntryName)); + Assert.Throws(() => new GnuTarEntry(TarEntryType.MultiVolume, InitialEntryName)); + Assert.Throws(() => new GnuTarEntry(TarEntryType.RenamedOrSymlinked, InitialEntryName)); + Assert.Throws(() => new GnuTarEntry(TarEntryType.SparseFile, InitialEntryName)); + Assert.Throws(() => new GnuTarEntry(TarEntryType.TapeVolume, InitialEntryName)); // The user should not create these entries manually - Assert.Throws(() => new GnuTarEntry(TarEntryType.LongLink, InitialEntryName)); - Assert.Throws(() => new GnuTarEntry(TarEntryType.LongPath, InitialEntryName)); + Assert.Throws(() => new GnuTarEntry(TarEntryType.LongLink, InitialEntryName)); + Assert.Throws(() => new GnuTarEntry(TarEntryType.LongPath, InitialEntryName)); } [Fact] diff --git a/src/libraries/System.Formats.Tar/tests/TarEntry/PaxTarEntry.Conversion.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarEntry/PaxTarEntry.Conversion.Tests.cs index 8125e45708eb30..e42f1df0ea6ea1 100644 --- a/src/libraries/System.Formats.Tar/tests/TarEntry/PaxTarEntry.Conversion.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarEntry/PaxTarEntry.Conversion.Tests.cs @@ -61,6 +61,15 @@ public class PaxTarEntry_Conversion_Tests : TarTestsConversionBase [Fact] public void Constructor_ConversionFromGnu_CharacterDevice() => TestConstructionConversion(TarEntryType.CharacterDevice, TarEntryFormat.Gnu, TarEntryFormat.Pax); + [Fact] + public void Constructor_ConversionFromPaxGEA_ToAny_Throw() + { + Assert.Throws(() => new V7TarEntry(new PaxGlobalExtendedAttributesTarEntry(new Dictionary()))); + Assert.Throws(() => new UstarTarEntry(new PaxGlobalExtendedAttributesTarEntry(new Dictionary()))); + Assert.Throws(() => new PaxTarEntry(new PaxGlobalExtendedAttributesTarEntry(new Dictionary()))); + Assert.Throws(() => new GnuTarEntry(new PaxGlobalExtendedAttributesTarEntry(new Dictionary()))); + } + [Theory] [InlineData(TarEntryFormat.V7)] [InlineData(TarEntryFormat.Ustar)] diff --git a/src/libraries/System.Formats.Tar/tests/TarEntry/PaxTarEntry.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarEntry/PaxTarEntry.Tests.cs index 69e028ae883aa2..0e8bcc952cea5d 100644 --- a/src/libraries/System.Formats.Tar/tests/TarEntry/PaxTarEntry.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarEntry/PaxTarEntry.Tests.cs @@ -19,21 +19,21 @@ public void Constructor_InvalidEntryName() [Fact] public void Constructor_UnsupportedEntryTypes() { - Assert.Throws(() => new PaxTarEntry((TarEntryType)byte.MaxValue, InitialEntryName)); + Assert.Throws(() => new PaxTarEntry((TarEntryType)byte.MaxValue, InitialEntryName)); - Assert.Throws(() => new PaxTarEntry(TarEntryType.ContiguousFile, InitialEntryName)); - Assert.Throws(() => new PaxTarEntry(TarEntryType.DirectoryList, InitialEntryName)); - Assert.Throws(() => new PaxTarEntry(TarEntryType.LongLink, InitialEntryName)); - Assert.Throws(() => new PaxTarEntry(TarEntryType.LongPath, InitialEntryName)); - Assert.Throws(() => new PaxTarEntry(TarEntryType.MultiVolume, InitialEntryName)); - Assert.Throws(() => new PaxTarEntry(TarEntryType.V7RegularFile, InitialEntryName)); - Assert.Throws(() => new PaxTarEntry(TarEntryType.RenamedOrSymlinked, InitialEntryName)); - Assert.Throws(() => new PaxTarEntry(TarEntryType.SparseFile, InitialEntryName)); - Assert.Throws(() => new PaxTarEntry(TarEntryType.TapeVolume, InitialEntryName)); + Assert.Throws(() => new PaxTarEntry(TarEntryType.ContiguousFile, InitialEntryName)); + Assert.Throws(() => new PaxTarEntry(TarEntryType.DirectoryList, InitialEntryName)); + Assert.Throws(() => new PaxTarEntry(TarEntryType.LongLink, InitialEntryName)); + Assert.Throws(() => new PaxTarEntry(TarEntryType.LongPath, InitialEntryName)); + Assert.Throws(() => new PaxTarEntry(TarEntryType.MultiVolume, InitialEntryName)); + Assert.Throws(() => new PaxTarEntry(TarEntryType.V7RegularFile, InitialEntryName)); + Assert.Throws(() => new PaxTarEntry(TarEntryType.RenamedOrSymlinked, InitialEntryName)); + Assert.Throws(() => new PaxTarEntry(TarEntryType.SparseFile, InitialEntryName)); + Assert.Throws(() => new PaxTarEntry(TarEntryType.TapeVolume, InitialEntryName)); // The user should not be creating these entries manually in pax - Assert.Throws(() => new PaxTarEntry(TarEntryType.ExtendedAttributes, InitialEntryName)); - Assert.Throws(() => new PaxTarEntry(TarEntryType.GlobalExtendedAttributes, InitialEntryName)); + Assert.Throws(() => new PaxTarEntry(TarEntryType.ExtendedAttributes, InitialEntryName)); + Assert.Throws(() => new PaxTarEntry(TarEntryType.GlobalExtendedAttributes, InitialEntryName)); } [Fact] diff --git a/src/libraries/System.Formats.Tar/tests/TarEntry/TarEntry.Conversion.Tests.Base.cs b/src/libraries/System.Formats.Tar/tests/TarEntry/TarEntry.Conversion.Tests.Base.cs index 6626ca958f25d4..9fa5e57d460c19 100644 --- a/src/libraries/System.Formats.Tar/tests/TarEntry/TarEntry.Conversion.Tests.Base.cs +++ b/src/libraries/System.Formats.Tar/tests/TarEntry/TarEntry.Conversion.Tests.Base.cs @@ -184,7 +184,7 @@ protected TarEntry InvokeTarEntryConversionConstructor(TarEntryFormat targetForm TarEntryFormat.Ustar => new UstarTarEntry(other), TarEntryFormat.Pax => new PaxTarEntry(other), TarEntryFormat.Gnu => new GnuTarEntry(other), - _ => throw new FormatException($"Unexpected format: {targetFormat}") + _ => throw new InvalidDataException($"Unexpected format: {targetFormat}") }; } } diff --git a/src/libraries/System.Formats.Tar/tests/TarEntry/UstarTarEntry.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarEntry/UstarTarEntry.Tests.cs index 8087621f57ae1d..2fdcb34069e50b 100644 --- a/src/libraries/System.Formats.Tar/tests/TarEntry/UstarTarEntry.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarEntry/UstarTarEntry.Tests.cs @@ -19,19 +19,19 @@ public void Constructor_InvalidEntryName() [Fact] public void Constructor_UnsupportedEntryTypes() { - Assert.Throws(() => new UstarTarEntry((TarEntryType)byte.MaxValue, InitialEntryName)); + Assert.Throws(() => new UstarTarEntry((TarEntryType)byte.MaxValue, InitialEntryName)); - Assert.Throws(() => new UstarTarEntry(TarEntryType.ContiguousFile, InitialEntryName)); - Assert.Throws(() => new UstarTarEntry(TarEntryType.DirectoryList, InitialEntryName)); - Assert.Throws(() => new UstarTarEntry(TarEntryType.ExtendedAttributes, InitialEntryName)); - Assert.Throws(() => new UstarTarEntry(TarEntryType.GlobalExtendedAttributes, InitialEntryName)); - Assert.Throws(() => new UstarTarEntry(TarEntryType.LongLink, InitialEntryName)); - Assert.Throws(() => new UstarTarEntry(TarEntryType.LongPath, InitialEntryName)); - Assert.Throws(() => new UstarTarEntry(TarEntryType.MultiVolume, InitialEntryName)); - Assert.Throws(() => new UstarTarEntry(TarEntryType.V7RegularFile, InitialEntryName)); - Assert.Throws(() => new UstarTarEntry(TarEntryType.RenamedOrSymlinked, InitialEntryName)); - Assert.Throws(() => new UstarTarEntry(TarEntryType.SparseFile, InitialEntryName)); - Assert.Throws(() => new UstarTarEntry(TarEntryType.TapeVolume, InitialEntryName)); + Assert.Throws(() => new UstarTarEntry(TarEntryType.ContiguousFile, InitialEntryName)); + Assert.Throws(() => new UstarTarEntry(TarEntryType.DirectoryList, InitialEntryName)); + Assert.Throws(() => new UstarTarEntry(TarEntryType.ExtendedAttributes, InitialEntryName)); + Assert.Throws(() => new UstarTarEntry(TarEntryType.GlobalExtendedAttributes, InitialEntryName)); + Assert.Throws(() => new UstarTarEntry(TarEntryType.LongLink, InitialEntryName)); + Assert.Throws(() => new UstarTarEntry(TarEntryType.LongPath, InitialEntryName)); + Assert.Throws(() => new UstarTarEntry(TarEntryType.MultiVolume, InitialEntryName)); + Assert.Throws(() => new UstarTarEntry(TarEntryType.V7RegularFile, InitialEntryName)); + Assert.Throws(() => new UstarTarEntry(TarEntryType.RenamedOrSymlinked, InitialEntryName)); + Assert.Throws(() => new UstarTarEntry(TarEntryType.SparseFile, InitialEntryName)); + Assert.Throws(() => new UstarTarEntry(TarEntryType.TapeVolume, InitialEntryName)); } [Fact] diff --git a/src/libraries/System.Formats.Tar/tests/TarEntry/V7TarEntry.Conversion.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarEntry/V7TarEntry.Conversion.Tests.cs index 3f5e41a8f3609f..8856ec4d54809a 100644 --- a/src/libraries/System.Formats.Tar/tests/TarEntry/V7TarEntry.Conversion.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarEntry/V7TarEntry.Conversion.Tests.cs @@ -16,25 +16,25 @@ public class V7TarEntry_Conversion_Tests : TarTestsConversionBase [Fact] public void Constructor_Conversion_UnsupportedEntryTypes_Ustar() { - Assert.Throws(() => new V7TarEntry(new UstarTarEntry(TarEntryType.BlockDevice, InitialEntryName))); - Assert.Throws(() => new V7TarEntry(new UstarTarEntry(TarEntryType.CharacterDevice, InitialEntryName))); - Assert.Throws(() => new V7TarEntry(new UstarTarEntry(TarEntryType.Fifo, InitialEntryName))); + Assert.Throws(() => new V7TarEntry(new UstarTarEntry(TarEntryType.BlockDevice, InitialEntryName))); + Assert.Throws(() => new V7TarEntry(new UstarTarEntry(TarEntryType.CharacterDevice, InitialEntryName))); + Assert.Throws(() => new V7TarEntry(new UstarTarEntry(TarEntryType.Fifo, InitialEntryName))); } [Fact] public void Constructor_Conversion_UnsupportedEntryTypes_Pax() { - Assert.Throws(() => new V7TarEntry(new PaxTarEntry(TarEntryType.BlockDevice, InitialEntryName))); - Assert.Throws(() => new V7TarEntry(new PaxTarEntry(TarEntryType.CharacterDevice, InitialEntryName))); - Assert.Throws(() => new V7TarEntry(new PaxTarEntry(TarEntryType.Fifo, InitialEntryName))); + Assert.Throws(() => new V7TarEntry(new PaxTarEntry(TarEntryType.BlockDevice, InitialEntryName))); + Assert.Throws(() => new V7TarEntry(new PaxTarEntry(TarEntryType.CharacterDevice, InitialEntryName))); + Assert.Throws(() => new V7TarEntry(new PaxTarEntry(TarEntryType.Fifo, InitialEntryName))); } [Fact] public void Constructor_Conversion_UnsupportedEntryTypes_Gnu() { - Assert.Throws(() => new V7TarEntry(new GnuTarEntry(TarEntryType.BlockDevice, InitialEntryName))); - Assert.Throws(() => new V7TarEntry(new GnuTarEntry(TarEntryType.CharacterDevice, InitialEntryName))); - Assert.Throws(() => new V7TarEntry(new GnuTarEntry(TarEntryType.Fifo, InitialEntryName))); + Assert.Throws(() => new V7TarEntry(new GnuTarEntry(TarEntryType.BlockDevice, InitialEntryName))); + Assert.Throws(() => new V7TarEntry(new GnuTarEntry(TarEntryType.CharacterDevice, InitialEntryName))); + Assert.Throws(() => new V7TarEntry(new GnuTarEntry(TarEntryType.Fifo, InitialEntryName))); } [Fact] diff --git a/src/libraries/System.Formats.Tar/tests/TarEntry/V7TarEntry.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarEntry/V7TarEntry.Tests.cs index 36dab66fb24e2f..2bf5471d4fa484 100644 --- a/src/libraries/System.Formats.Tar/tests/TarEntry/V7TarEntry.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarEntry/V7TarEntry.Tests.cs @@ -20,22 +20,22 @@ public void Constructor_InvalidEntryName() [Fact] public void Constructor_UnsupportedEntryTypes() { - Assert.Throws(() => new V7TarEntry((TarEntryType)byte.MaxValue, InitialEntryName)); + Assert.Throws(() => new V7TarEntry((TarEntryType)byte.MaxValue, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.BlockDevice, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.CharacterDevice, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.ContiguousFile, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.DirectoryList, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.ExtendedAttributes, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.Fifo, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.GlobalExtendedAttributes, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.LongLink, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.LongPath, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.MultiVolume, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.RegularFile, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.RenamedOrSymlinked, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.SparseFile, InitialEntryName)); - Assert.Throws(() => new V7TarEntry(TarEntryType.TapeVolume, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.BlockDevice, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.CharacterDevice, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.ContiguousFile, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.DirectoryList, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.ExtendedAttributes, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.Fifo, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.GlobalExtendedAttributes, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.LongLink, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.LongPath, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.MultiVolume, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.RegularFile, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.RenamedOrSymlinked, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.SparseFile, InitialEntryName)); + Assert.Throws(() => new V7TarEntry(TarEntryType.TapeVolume, InitialEntryName)); } [Fact] diff --git a/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.CreateFromDirectory.Stream.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.CreateFromDirectory.Stream.Tests.cs index ca0cb57fab783b..33b550960ef563 100644 --- a/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.CreateFromDirectory.Stream.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.CreateFromDirectory.Stream.Tests.cs @@ -28,7 +28,7 @@ public void UnwritableStream_Throws() { using MemoryStream archive = new MemoryStream(); using WrappedStream unwritable = new WrappedStream(archive, canRead: true, canWrite: false, canSeek: true); - Assert.Throws(() => TarFile.CreateFromDirectory(sourceDirectoryName: "path",destination: unwritable, includeBaseDirectory: false)); + Assert.Throws(() => TarFile.CreateFromDirectory(sourceDirectoryName: "path",destination: unwritable, includeBaseDirectory: false)); } [Fact] diff --git a/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.CreateFromDirectoryAsync.Stream.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.CreateFromDirectoryAsync.Stream.Tests.cs index 7a67aac64508f7..8dbde4461290a6 100644 --- a/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.CreateFromDirectoryAsync.Stream.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.CreateFromDirectoryAsync.Stream.Tests.cs @@ -48,7 +48,7 @@ public async Task UnwritableStream_Throws_Async() { await using (WrappedStream unwritable = new WrappedStream(archiveStream, canRead: true, canWrite: false, canSeek: true)) { - await Assert.ThrowsAsync(() => TarFile.CreateFromDirectoryAsync(sourceDirectoryName: "path", destination: unwritable, includeBaseDirectory: false)); + await Assert.ThrowsAsync(() => TarFile.CreateFromDirectoryAsync(sourceDirectoryName: "path", destination: unwritable, includeBaseDirectory: false)); } } } diff --git a/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.ExtractToDirectory.Stream.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.ExtractToDirectory.Stream.Tests.cs index d53f354ee408d1..b62196bb5c5d6f 100644 --- a/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.ExtractToDirectory.Stream.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.ExtractToDirectory.Stream.Tests.cs @@ -30,7 +30,7 @@ public void UnreadableStream_Throws() { using MemoryStream archive = new MemoryStream(); using WrappedStream unreadable = new WrappedStream(archive, canRead: false, canWrite: true, canSeek: true); - Assert.Throws(() => TarFile.ExtractToDirectory(unreadable, destinationDirectoryName: "path", overwriteFiles: false)); + Assert.Throws(() => TarFile.ExtractToDirectory(unreadable, destinationDirectoryName: "path", overwriteFiles: false)); } [Fact] diff --git a/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.ExtractToDirectoryAsync.Stream.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.ExtractToDirectoryAsync.Stream.Tests.cs index 741ce8e102deb4..70c6fcbf8049d4 100644 --- a/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.ExtractToDirectoryAsync.Stream.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarFile/TarFile.ExtractToDirectoryAsync.Stream.Tests.cs @@ -45,7 +45,7 @@ public async Task UnreadableStream_Throws_Async() { using (WrappedStream unreadable = new WrappedStream(archive, canRead: false, canWrite: true, canSeek: true)) { - await Assert.ThrowsAsync(() => TarFile.ExtractToDirectoryAsync(unreadable, destinationDirectoryName: "path", overwriteFiles: false)); + await Assert.ThrowsAsync(() => TarFile.ExtractToDirectoryAsync(unreadable, destinationDirectoryName: "path", overwriteFiles: false)); } } } diff --git a/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.File.Async.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.File.Async.Tests.cs index 69a543a206d4b9..d86cfa4e34dd47 100644 --- a/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.File.Async.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.File.Async.Tests.cs @@ -230,7 +230,7 @@ public async Task Throw_FifoContainsNonZeroDataSectionAsync() Assert.NotNull(await reader.GetNextEntryAsync()); Assert.NotNull(await reader.GetNextEntryAsync()); Assert.NotNull(await reader.GetNextEntryAsync()); - await Assert.ThrowsAsync(async () => await reader.GetNextEntryAsync()); + await Assert.ThrowsAsync(async () => await reader.GetNextEntryAsync()); } [Fact] @@ -268,7 +268,7 @@ public async Task Throw_ArchivesWithRandomCharsAsync(string testCaseName) { await using MemoryStream archiveStream = GetTarMemoryStream(CompressionMethod.Uncompressed, "golang_tar", testCaseName); await using TarReader reader = new TarReader(archiveStream); - await Assert.ThrowsAsync(async () => await reader.GetNextEntryAsync()); + await Assert.ThrowsAsync(async () => await reader.GetNextEntryAsync()); } [Fact] diff --git a/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.File.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.File.Tests.cs index 298e3e8be47947..17c67423c390b2 100644 --- a/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.File.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.File.Tests.cs @@ -230,7 +230,7 @@ public void Throw_FifoContainsNonZeroDataSection() Assert.NotNull(reader.GetNextEntry()); Assert.NotNull(reader.GetNextEntry()); Assert.NotNull(reader.GetNextEntry()); - Assert.Throws(() => reader.GetNextEntry()); + Assert.Throws(() => reader.GetNextEntry()); } [Fact] @@ -268,7 +268,7 @@ public void Throw_ArchivesWithRandomChars(string testCaseName) { using MemoryStream archiveStream = GetTarMemoryStream(CompressionMethod.Uncompressed, "golang_tar", testCaseName); using TarReader reader = new TarReader(archiveStream); - Assert.Throws(() => reader.GetNextEntry()); + Assert.Throws(() => reader.GetNextEntry()); } [Fact] diff --git a/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.GetNextEntry.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.GetNextEntry.Tests.cs index dda0cae56b69f8..2cede3a350c825 100644 --- a/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.GetNextEntry.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.GetNextEntry.Tests.cs @@ -30,7 +30,7 @@ public void MalformedArchive_HeaderSize() malformed.Seek(0, SeekOrigin.Begin); using TarReader reader = new TarReader(malformed); - Assert.Throws(() => reader.GetNextEntry()); + Assert.Throws(() => reader.GetNextEntry()); } [Fact] diff --git a/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.GetNextEntryAsync.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.GetNextEntryAsync.Tests.cs index 1dcd9326ee81ee..f99e5853ebeaad 100644 --- a/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.GetNextEntryAsync.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.GetNextEntryAsync.Tests.cs @@ -51,7 +51,7 @@ public async Task MalformedArchive_HeaderSize_Async() await using (TarReader reader = new TarReader(malformed)) { - await Assert.ThrowsAsync(async () => await reader.GetNextEntryAsync()); + await Assert.ThrowsAsync(async () => await reader.GetNextEntryAsync()); } } } diff --git a/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.Tests.cs new file mode 100644 index 00000000000000..8b41a5e9bb13bd --- /dev/null +++ b/src/libraries/System.Formats.Tar/tests/TarReader/TarReader.Tests.cs @@ -0,0 +1,98 @@ +// 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.IO; +using System.Linq; +using Xunit; + +namespace System.Formats.Tar.Tests +{ + public class TarReader_Tests : TarTestsBase + { + [Fact] + public void TarReader_NullArchiveStream() => Assert.Throws(() => new TarReader(archiveStream: null)); + + [Fact] + public void TarReader_UnreadableStream() + { + using MemoryStream ms = new MemoryStream(); + using WrappedStream ws = new WrappedStream(ms, canRead: false, canWrite: true, canSeek: true); + Assert.Throws(() => new TarReader(ws)); + } + + [Fact] + public void TarReader_LeaveOpen_False() + { + using MemoryStream ms = GetTarMemoryStream(CompressionMethod.Uncompressed, TestTarFormat.pax, "many_small_files"); + List dataStreams = new List(); + using (TarReader reader = new TarReader(ms, leaveOpen: false)) + { + TarEntry entry; + while ((entry = reader.GetNextEntry()) != null) + { + if (entry.DataStream != null) + { + dataStreams.Add(entry.DataStream); + } + } + } + + Assert.True(dataStreams.Any()); + foreach (Stream ds in dataStreams) + { + Assert.Throws(() => ds.ReadByte()); + } + } + + [Fact] + public void TarReader_LeaveOpen_True() + { + using MemoryStream ms = GetTarMemoryStream(CompressionMethod.Uncompressed, TestTarFormat.pax, "many_small_files"); + List dataStreams = new List(); + using (TarReader reader = new TarReader(ms, leaveOpen: true)) + { + TarEntry entry; + while ((entry = reader.GetNextEntry()) != null) + { + if (entry.DataStream != null) + { + dataStreams.Add(entry.DataStream); + } + } + } + + Assert.True(dataStreams.Any()); + foreach (Stream ds in dataStreams) + { + ds.ReadByte(); // Should not throw + ds.Dispose(); + } + } + + [Fact] + public void TarReader_LeaveOpen_False_CopiedDataNotDisposed() + { + using MemoryStream ms = GetTarMemoryStream(CompressionMethod.Uncompressed, TestTarFormat.pax, "many_small_files"); + List dataStreams = new List(); + using (TarReader reader = new TarReader(ms, leaveOpen: false)) + { + TarEntry entry; + while ((entry = reader.GetNextEntry(copyData: true)) != null) + { + if (entry.DataStream != null) + { + dataStreams.Add(entry.DataStream); + } + } + } + + Assert.True(dataStreams.Any()); + foreach (Stream ds in dataStreams) + { + ds.ReadByte(); // Should not throw, copied streams, user should dispose + ds.Dispose(); + } + } + } +} diff --git a/src/libraries/System.Formats.Tar/tests/TarTestsBase.cs b/src/libraries/System.Formats.Tar/tests/TarTestsBase.cs index 23dc653c83a165..ae01821d62b6d6 100644 --- a/src/libraries/System.Formats.Tar/tests/TarTestsBase.cs +++ b/src/libraries/System.Formats.Tar/tests/TarTestsBase.cs @@ -288,6 +288,8 @@ protected void SetCommonHardLink(TarEntry hardLink) // LinkName Assert.Equal(DefaultLinkName, hardLink.LinkName); + Assert.Throws(() => hardLink.LinkName = null); + Assert.Throws(() => hardLink.LinkName = string.Empty); hardLink.LinkName = TestLinkName; } @@ -299,6 +301,8 @@ protected void SetCommonSymbolicLink(TarEntry symbolicLink) // LinkName Assert.Equal(DefaultLinkName, symbolicLink.LinkName); + Assert.Throws(() => symbolicLink.LinkName = null); + Assert.Throws(() => symbolicLink.LinkName = string.Empty); symbolicLink.LinkName = TestLinkName; } @@ -401,6 +405,13 @@ protected void VerifyDataStream(TarEntry entry, bool isFromWriter) if (isFromWriter) { Assert.Null(entry.DataStream); + + using (MemoryStream ms = new MemoryStream()) + using (WrappedStream ws = new WrappedStream(ms, canRead: false, canWrite: true, canSeek: true)) + { + Assert.Throws(() => entry.DataStream = ws); + } + entry.DataStream = new MemoryStream(); // Verify it is not modified or wrapped in any way Assert.True(entry.DataStream.CanRead); @@ -436,7 +447,7 @@ protected Type GetTypeForFormat(TarEntryFormat expectedFormat) TarEntryFormat.Ustar => typeof(UstarTarEntry), TarEntryFormat.Pax => typeof(PaxTarEntry), TarEntryFormat.Gnu => typeof(GnuTarEntry), - _ => throw new FormatException($"Unrecognized format: {expectedFormat}"), + _ => throw new InvalidDataException($"Unrecognized format: {expectedFormat}"), }; } @@ -472,7 +483,7 @@ protected TarEntry InvokeTarEntryCreationConstructor(TarEntryFormat targetFormat TarEntryFormat.Ustar => new UstarTarEntry(entryType, entryName), TarEntryFormat.Pax => new PaxTarEntry(entryType, entryName), TarEntryFormat.Gnu => new GnuTarEntry(entryType, entryName), - _ => throw new FormatException($"Unexpected format: {targetFormat}") + _ => throw new InvalidDataException($"Unexpected format: {targetFormat}") }; public static IEnumerable GetFormatsAndLinks() diff --git a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.Tests.cs index 894498934f0177..8d482af0b1dff1 100644 --- a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.Tests.cs @@ -63,8 +63,8 @@ public void Constructors_UnwritableStream_Throws() { using MemoryStream archiveStream = new MemoryStream(); using WrappedStream wrappedStream = new WrappedStream(archiveStream, canRead: true, canWrite: false, canSeek: false); - Assert.Throws(() => new TarWriter(wrappedStream)); - Assert.Throws(() => new TarWriter(wrappedStream, TarEntryFormat.V7)); + Assert.Throws(() => new TarWriter(wrappedStream)); + Assert.Throws(() => new TarWriter(wrappedStream, TarEntryFormat.V7)); } [Fact] diff --git a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Tests.cs index 6d19503c4fc25d..b0c78298f2bb01 100644 --- a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Tests.cs @@ -101,7 +101,7 @@ public void Write_RegularFileEntry_In_V7Writer(TarEntryFormat entryFormat) TarEntryFormat.Ustar => new UstarTarEntry(TarEntryType.RegularFile, InitialEntryName), TarEntryFormat.Pax => new PaxTarEntry(TarEntryType.RegularFile, InitialEntryName), TarEntryFormat.Gnu => new GnuTarEntry(TarEntryType.RegularFile, InitialEntryName), - _ => throw new FormatException($"Unexpected format: {entryFormat}") + _ => throw new InvalidDataException($"Unexpected format: {entryFormat}") }; // Should be written in the format of the entry diff --git a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Tests.cs index 8f6637408a8c9b..c2eb58a7f1f24a 100644 --- a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Tests.cs @@ -125,7 +125,7 @@ public async Task Write_RegularFileEntry_In_V7Writer_Async(TarEntryFormat entryF TarEntryFormat.Ustar => new UstarTarEntry(TarEntryType.RegularFile, InitialEntryName), TarEntryFormat.Pax => new PaxTarEntry(TarEntryType.RegularFile, InitialEntryName), TarEntryFormat.Gnu => new GnuTarEntry(TarEntryType.RegularFile, InitialEntryName), - _ => throw new FormatException($"Unexpected format: {entryFormat}") + _ => throw new InvalidDataException($"Unexpected format: {entryFormat}") }; // Should be written in the format of the entry From 4cefab00e60bd4142539351137f00de4dd025fcd Mon Sep 17 00:00:00 2001 From: Carlos Sanchez <1175054+carlossanlop@users.noreply.github.com> Date: Thu, 1 Sep 2022 17:09:32 -0700 Subject: [PATCH 079/107] Disallow TarWriter from writing link entries without LinkName set (#74892) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Disallow TarWriter from writing link entries without LinkName set * Tests * Docs * Apply suggestions from code review Co-authored-by: David Cantú * Apply suggestions from code review Co-authored-by: carlossanlop Co-authored-by: David Cantú --- .../src/System/Formats/Tar/TarHeader.Write.cs | 3 +++ .../src/System/Formats/Tar/TarWriter.cs | 15 +++++++++++++++ .../TarWriter.WriteEntry.Entry.Gnu.Tests.cs | 14 ++++++++++++++ .../TarWriter.WriteEntry.Entry.Pax.Tests.cs | 10 ++++++++++ .../TarWriter.WriteEntry.Entry.Ustar.Tests.cs | 10 ++++++++++ .../TarWriter.WriteEntry.Entry.V7.Tests.cs | 10 ++++++++++ .../TarWriter.WriteEntryAsync.Entry.Gnu.Tests.cs | 14 ++++++++++++++ .../TarWriter.WriteEntryAsync.Entry.Pax.Tests.cs | 10 ++++++++++ ...TarWriter.WriteEntryAsync.Entry.Ustar.Tests.cs | 10 ++++++++++ .../TarWriter.WriteEntryAsync.Entry.V7.Tests.cs | 10 ++++++++++ 10 files changed, 106 insertions(+) diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs index 2afcfb8a9f23df..e1166a066814b3 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHeader.Write.cs @@ -391,6 +391,9 @@ private int WritePosixName(Span buffer) // Writes all the common fields shared by all formats into the specified spans. private int WriteCommonFields(Span buffer, long actualLength, TarEntryType actualEntryType) { + // Don't write an empty LinkName if the entry is a hardlink or symlink + Debug.Assert(!string.IsNullOrEmpty(_linkName) ^ (_typeFlag is not TarEntryType.SymbolicLink and not TarEntryType.HardLink)); + int checksum = 0; if (_mode > 0) diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.cs index b2d144a0bf6a7d..d7b7ceceac3464 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarWriter.cs @@ -213,6 +213,7 @@ private async Task ReadFileFromDiskAndWriteToArchiveStreamAsEntryAsync(string fu /// /// /// + /// The entry type is or and the is or empty. /// The archive stream is disposed. /// is . /// An I/O problem occurred. @@ -220,6 +221,7 @@ public void WriteEntry(TarEntry entry) { ObjectDisposedException.ThrowIf(_isDisposed, this); ArgumentNullException.ThrowIfNull(entry); + ValidateEntryLinkName(entry._header._typeFlag, entry._header._linkName); WriteEntryInternal(entry); } @@ -254,6 +256,7 @@ public void WriteEntry(TarEntry entry) /// /// /// + /// The entry type is or and the is or empty. /// The archive stream is disposed. /// is . /// An I/O problem occurred. @@ -266,6 +269,7 @@ public Task WriteEntryAsync(TarEntry entry, CancellationToken cancellationToken ObjectDisposedException.ThrowIf(_isDisposed, this); ArgumentNullException.ThrowIfNull(entry); + ValidateEntryLinkName(entry._header._typeFlag, entry._header._linkName); return WriteEntryAsyncInternal(entry, cancellationToken); } @@ -369,5 +373,16 @@ private async ValueTask WriteFinalRecordsAsync() return (fullPath, actualEntryName); } + + private static void ValidateEntryLinkName(TarEntryType entryType, string? linkName) + { + if (entryType is TarEntryType.HardLink or TarEntryType.SymbolicLink) + { + if (string.IsNullOrEmpty(linkName)) + { + throw new ArgumentException(SR.TarEntryHardLinkOrSymlinkLinkNameEmpty, "entry"); + } + } + } } } diff --git a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.Gnu.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.Gnu.Tests.cs index d591ba9b6542a6..925daef99d5167 100644 --- a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.Gnu.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.Gnu.Tests.cs @@ -167,6 +167,10 @@ public void Write_Long_Name(TarEntryType entryType) using (TarWriter writer = new TarWriter(archiveStream, TarEntryFormat.Gnu, leaveOpen: true)) { GnuTarEntry entry = new GnuTarEntry(entryType, longName); + if (entryType is TarEntryType.HardLink or TarEntryType.SymbolicLink) + { + entry.LinkName = "linktarget"; + } writer.WriteEntry(entry); } @@ -231,5 +235,15 @@ public void Write_LongName_And_LongLinkName(TarEntryType entryType) Assert.Equal(longLinkName, entry.LinkName); } } + + [Theory] + [InlineData(TarEntryType.HardLink)] + [InlineData(TarEntryType.SymbolicLink)] + public void Write_LinkEntry_EmptyLinkName_Throws(TarEntryType entryType) + { + using MemoryStream archiveStream = new MemoryStream(); + using TarWriter writer = new TarWriter(archiveStream, leaveOpen: false); + Assert.Throws("entry", () => writer.WriteEntry(new GnuTarEntry(entryType, "link"))); + } } } diff --git a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.Pax.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.Pax.Tests.cs index 6c9e79d83a1eff..1e81fb7b1e8a01 100644 --- a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.Pax.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.Pax.Tests.cs @@ -485,5 +485,15 @@ public void WriteTimestampsBeyondOctalLimitInPax() Assert.Equal(overLimitTimestamp, actualCTime); } } + + [Theory] + [InlineData(TarEntryType.HardLink)] + [InlineData(TarEntryType.SymbolicLink)] + public void Write_LinkEntry_EmptyLinkName_Throws(TarEntryType entryType) + { + using MemoryStream archiveStream = new MemoryStream(); + using TarWriter writer = new TarWriter(archiveStream, leaveOpen: false); + Assert.Throws("entry", () => writer.WriteEntry(new PaxTarEntry(entryType, "link"))); + } } } diff --git a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.Ustar.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.Ustar.Tests.cs index da3b69051ab347..c1f2d07562d388 100644 --- a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.Ustar.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.Ustar.Tests.cs @@ -152,5 +152,15 @@ public void WriteFifo() VerifyFifo(fifo); } } + + [Theory] + [InlineData(TarEntryType.HardLink)] + [InlineData(TarEntryType.SymbolicLink)] + public void Write_LinkEntry_EmptyLinkName_Throws(TarEntryType entryType) + { + using MemoryStream archiveStream = new MemoryStream(); + using TarWriter writer = new TarWriter(archiveStream, leaveOpen: false); + Assert.Throws("entry", () => writer.WriteEntry(new UstarTarEntry(entryType, "link"))); + } } } diff --git a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.V7.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.V7.Tests.cs index fb0cbb980ee6e2..51be90c74b07c9 100644 --- a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.V7.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntry.Entry.V7.Tests.cs @@ -92,5 +92,15 @@ public void WriteDirectory() VerifyDirectory(directory); } } + + [Theory] + [InlineData(TarEntryType.HardLink)] + [InlineData(TarEntryType.SymbolicLink)] + public void Write_LinkEntry_EmptyLinkName_Throws(TarEntryType entryType) + { + using MemoryStream archiveStream = new MemoryStream(); + using TarWriter writer = new TarWriter(archiveStream, leaveOpen: false); + Assert.Throws("entry", () => writer.WriteEntry(new V7TarEntry(entryType, "link"))); + } } } diff --git a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.Gnu.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.Gnu.Tests.cs index b33e2bf7add22a..1e77e548d4a6f7 100644 --- a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.Gnu.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.Gnu.Tests.cs @@ -183,6 +183,10 @@ public async Task Write_Long_Name_Async(TarEntryType entryType) await using (TarWriter writer = new TarWriter(archiveStream, TarEntryFormat.Gnu, leaveOpen: true)) { GnuTarEntry entry = new GnuTarEntry(entryType, longName); + if (entryType is TarEntryType.HardLink or TarEntryType.SymbolicLink) + { + entry.LinkName = "linktarget"; + } await writer.WriteEntryAsync(entry); } @@ -252,5 +256,15 @@ public async Task Write_LongName_And_LongLinkName_Async(TarEntryType entryType) } } } + + [Theory] + [InlineData(TarEntryType.HardLink)] + [InlineData(TarEntryType.SymbolicLink)] + public async Task Write_LinkEntry_EmptyLinkName_Throws_Async(TarEntryType entryType) + { + await using MemoryStream archiveStream = new MemoryStream(); + await using TarWriter writer = new TarWriter(archiveStream, leaveOpen: false); + await Assert.ThrowsAsync("entry", () => writer.WriteEntryAsync(new GnuTarEntry(entryType, "link"))); + } } } diff --git a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.Pax.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.Pax.Tests.cs index 688c918baedf15..b0c9d636420b52 100644 --- a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.Pax.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.Pax.Tests.cs @@ -505,5 +505,15 @@ public async Task WriteTimestampsBeyondOctalLimitInPax_Async() Assert.Equal(overLimitTimestamp, actualCTime); } } + + [Theory] + [InlineData(TarEntryType.HardLink)] + [InlineData(TarEntryType.SymbolicLink)] + public async Task Write_LinkEntry_EmptyLinkName_Throws_Async(TarEntryType entryType) + { + await using MemoryStream archiveStream = new MemoryStream(); + await using TarWriter writer = new TarWriter(archiveStream, leaveOpen: false); + await Assert.ThrowsAsync("entry", () => writer.WriteEntryAsync(new PaxTarEntry(entryType, "link"))); + } } } diff --git a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.Ustar.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.Ustar.Tests.cs index 1266e7216a0126..b3e207d434f78e 100644 --- a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.Ustar.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.Ustar.Tests.cs @@ -153,5 +153,15 @@ public async Task WriteFifo_Async() VerifyFifo(fifo); } } + + [Theory] + [InlineData(TarEntryType.HardLink)] + [InlineData(TarEntryType.SymbolicLink)] + public async Task Write_LinkEntry_EmptyLinkName_Throws_Async(TarEntryType entryType) + { + await using MemoryStream archiveStream = new MemoryStream(); + await using TarWriter writer = new TarWriter(archiveStream, leaveOpen: false); + await Assert.ThrowsAsync("entry", () => writer.WriteEntryAsync(new UstarTarEntry(entryType, "link"))); + } } } diff --git a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.V7.Tests.cs b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.V7.Tests.cs index 4408477ee00006..3e41f263ef02e4 100644 --- a/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.V7.Tests.cs +++ b/src/libraries/System.Formats.Tar/tests/TarWriter/TarWriter.WriteEntryAsync.Entry.V7.Tests.cs @@ -93,5 +93,15 @@ public async Task WriteDirectory_Async() VerifyDirectory(directory); } } + + [Theory] + [InlineData(TarEntryType.HardLink)] + [InlineData(TarEntryType.SymbolicLink)] + public async Task Write_LinkEntry_EmptyLinkName_Throws_Async(TarEntryType entryType) + { + await using MemoryStream archiveStream = new MemoryStream(); + await using TarWriter writer = new TarWriter(archiveStream, leaveOpen: false); + await Assert.ThrowsAsync("entry", () => writer.WriteEntryAsync(new V7TarEntry(entryType, "link"))); + } } } From abe020871bf57e285e3d1242957e1402e00eff05 Mon Sep 17 00:00:00 2001 From: Elinor Fung Date: Thu, 1 Sep 2022 19:14:49 -0700 Subject: [PATCH 080/107] Fix testhost build with different libraries and host configurations (#74903) * Fix testhost build with different libraries and host configurations * Allow specifying host configuration in build script --- Directory.Build.props | 3 ++- eng/Subsets.props | 3 +++ eng/build.ps1 | 4 ++++ eng/build.sh | 22 ++++++++++++++++++++++ 4 files changed, 31 insertions(+), 1 deletion(-) diff --git a/Directory.Build.props b/Directory.Build.props index 60a661e66ca444..6f9b97c0a9c579 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -129,6 +129,7 @@ Debug $(Configuration) + $(Configuration) @@ -231,7 +232,7 @@ - $([MSBuild]::NormalizeDirectory('$(ArtifactsBinDir)', '$(OutputRid).$(Configuration)', 'corehost')) + $([MSBuild]::NormalizeDirectory('$(ArtifactsBinDir)', '$(OutputRid).$(HostConfiguration)', 'corehost')) diff --git a/eng/Subsets.props b/eng/Subsets.props index 911c24dbde65e5..dfd34ef59e6ea8 100644 --- a/eng/Subsets.props +++ b/eng/Subsets.props @@ -483,6 +483,9 @@ %(AdditionalProperties);Configuration=$(CoreCLRConfiguration) %(AdditionalProperties);Configuration=$(MonoConfiguration) %(AdditionalProperties);Configuration=$(LibrariesConfiguration) + + %(AdditionalProperties);HostConfiguration=$(HostConfiguration) + %(AdditionalProperties);Configuration=$(HostConfiguration) diff --git a/eng/build.ps1 b/eng/build.ps1 index 2fedf06a3711dc..3ad0afd80074c1 100644 --- a/eng/build.ps1 +++ b/eng/build.ps1 @@ -16,6 +16,7 @@ Param( [ValidateSet("Debug","Release","Checked")][string][Alias('rc')]$runtimeConfiguration, [ValidateSet("Debug","Release")][string][Alias('lc')]$librariesConfiguration, [ValidateSet("CoreCLR","Mono")][string][Alias('rf')]$runtimeFlavor, + [ValidateSet("Debug","Release","Checked")][string][Alias('hc')]$hostConfiguration, [switch]$ninja, [switch]$msbuild, [string]$cmakeargs, @@ -35,6 +36,8 @@ function Get-Help() { Write-Host " Pass a comma-separated list to build for multiple configurations." Write-Host " [Default: Debug]" Write-Host " -help (-h) Print help and exit." + Write-Host " -hostConfiguration (-hc) Host build configuration: Debug, Release or Checked." + Write-Host " [Default: Debug]" Write-Host " -librariesConfiguration (-lc) Libraries build configuration: Debug or Release." Write-Host " [Default: Debug]" Write-Host " -os Target operating system: windows, Linux, OSX, Android or Browser." @@ -246,6 +249,7 @@ foreach ($argument in $PSBoundParameters.Keys) "runtimeConfiguration" { $arguments += " /p:RuntimeConfiguration=$((Get-Culture).TextInfo.ToTitleCase($($PSBoundParameters[$argument])))" } "runtimeFlavor" { $arguments += " /p:RuntimeFlavor=$($PSBoundParameters[$argument].ToLowerInvariant())" } "librariesConfiguration" { $arguments += " /p:LibrariesConfiguration=$((Get-Culture).TextInfo.ToTitleCase($($PSBoundParameters[$argument])))" } + "hostConfiguration" { $arguments += " /p:HostConfiguration=$((Get-Culture).TextInfo.ToTitleCase($($PSBoundParameters[$argument])))" } "framework" { $arguments += " /p:BuildTargetFramework=$($PSBoundParameters[$argument].ToLowerInvariant())" } "os" { $arguments += " /p:TargetOS=$($PSBoundParameters[$argument])" } "allconfigurations" { $arguments += " /p:BuildAllConfigurations=true" } diff --git a/eng/build.sh b/eng/build.sh index 84a4fd746c9177..ca8402cf6a570f 100755 --- a/eng/build.sh +++ b/eng/build.sh @@ -26,6 +26,8 @@ usage() echo " compiled with optimizations enabled." echo " [Default: Debug]" echo " --help (-h) Print help and exit." + echo " --hostConfiguration (-hc) Host build configuration: Debug, Release or Checked." + echo " [Default: Debug]" echo " --librariesConfiguration (-lc) Libraries build configuration: Debug or Release." echo " [Default: Debug]" echo " --os Target operating system: windows, Linux, FreeBSD, OSX, MacCatalyst, tvOS," @@ -375,6 +377,26 @@ while [[ $# > 0 ]]; do shift 2 ;; + -hostconfiguration|-hc) + if [ -z ${2+x} ]; then + echo "No host configuration supplied. See help (--help) for supported host configurations." 1>&2 + exit 1 + fi + passedHostConf="$(echo "$2" | tr "[:upper:]" "[:lower:]")" + case "$passedHostConf" in + debug|release|checked) + val="$(tr '[:lower:]' '[:upper:]' <<< ${passedHostConf:0:1})${passedHostConf:1}" + ;; + *) + echo "Unsupported host configuration '$2'." + echo "The allowed values are Debug, Release, and Checked." + exit 1 + ;; + esac + arguments="$arguments /p:HostConfiguration=$val" + shift 2 + ;; + -cross) crossBuild=1 arguments="$arguments /p:CrossBuild=True" From ca82565a60380bf4220255c65e493deb44314346 Mon Sep 17 00:00:00 2001 From: Tanner Gooding Date: Thu, 1 Sep 2022 20:08:54 -0700 Subject: [PATCH 081/107] Ensure that the SSE fallback for Vector3.Dot masks off the unused element of op1 and op2 (#74932) * Ensure that the SSE fallback for Vector3.Dot masks off the unused element of op1 and op2 * Applying formatting patch * Ensure we use TYP_SIMD16 in for the simdType when generating the fallback Dot nodes --- src/coreclr/jit/lowerxarch.cpp | 66 +++++++++++++++++++++++++--------- 1 file changed, 49 insertions(+), 17 deletions(-) diff --git a/src/coreclr/jit/lowerxarch.cpp b/src/coreclr/jit/lowerxarch.cpp index a7b1747d54bc09..103bffe15cb21f 100644 --- a/src/coreclr/jit/lowerxarch.cpp +++ b/src/coreclr/jit/lowerxarch.cpp @@ -3419,6 +3419,20 @@ GenTree* Lowering::LowerHWIntrinsicDot(GenTreeHWIntrinsic* node) { assert(simdBaseType == TYP_FLOAT); + // We need to mask off the most significant element to avoid the shuffle + add + // from including it in the computed result. We need to do this for both op1 and + // op2 in case one of them is `NaN` (because Zero * NaN == NaN) + + simd16_t simd16Val = {}; + + simd16Val.i32[0] = -1; + simd16Val.i32[1] = -1; + simd16Val.i32[2] = -1; + simd16Val.i32[3] = +0; + + simdType = TYP_SIMD16; + simdSize = 16; + // We will be constructing the following parts: // ... // +--* CNS_INT int -1 @@ -3426,7 +3440,7 @@ GenTree* Lowering::LowerHWIntrinsicDot(GenTreeHWIntrinsic* node) // +--* CNS_INT int -1 // +--* CNS_INT int 0 // tmp1 = * HWINTRINSIC simd16 T Create - // /--* op2 simd16 + // /--* op1 simd16 // +--* tmp1 simd16 // op1 = * HWINTRINSIC simd16 T And // ... @@ -3434,30 +3448,48 @@ GenTree* Lowering::LowerHWIntrinsicDot(GenTreeHWIntrinsic* node) // This is roughly the following managed code: // ... // tmp1 = Vector128.Create(-1, -1, -1, 0); - // op1 = Sse.And(op1, tmp2); + // op1 = Sse.And(op1, tmp1); // ... - GenTree* cns0 = comp->gtNewIconNode(-1, TYP_INT); - BlockRange().InsertAfter(op1, cns0); + GenTreeVecCon* vecCon1 = comp->gtNewVconNode(simdType, simdBaseJitType); + vecCon1->gtSimd16Val = simd16Val; - GenTree* cns1 = comp->gtNewIconNode(-1, TYP_INT); - BlockRange().InsertAfter(cns0, cns1); + BlockRange().InsertAfter(op1, vecCon1); - GenTree* cns2 = comp->gtNewIconNode(-1, TYP_INT); - BlockRange().InsertAfter(cns1, cns2); + op1 = comp->gtNewSimdHWIntrinsicNode(simdType, op1, vecCon1, NI_SSE_And, simdBaseJitType, simdSize); + BlockRange().InsertAfter(vecCon1, op1); - GenTree* cns3 = comp->gtNewIconNode(0, TYP_INT); - BlockRange().InsertAfter(cns2, cns3); + LowerNode(vecCon1); + LowerNode(op1); - tmp1 = comp->gtNewSimdHWIntrinsicNode(simdType, cns0, cns1, cns2, cns3, NI_Vector128_Create, - CORINFO_TYPE_INT, 16); - BlockRange().InsertAfter(cns3, tmp1); + // We will be constructing the following parts: + // ... + // +--* CNS_INT int -1 + // +--* CNS_INT int -1 + // +--* CNS_INT int -1 + // +--* CNS_INT int 0 + // tmp2 = * HWINTRINSIC simd16 T Create + // /--* op2 simd16 + // +--* tmp2 simd16 + // op2 = * HWINTRINSIC simd16 T And + // ... - op1 = comp->gtNewSimdHWIntrinsicNode(simdType, op1, tmp1, NI_SSE_And, simdBaseJitType, simdSize); - BlockRange().InsertAfter(tmp1, op1); + // This is roughly the following managed code: + // ... + // tmp2 = Vector128.Create(-1, -1, -1, 0); + // op2 = Sse.And(op2, tmp2); + // ... - LowerNode(tmp1); - LowerNode(op1); + GenTreeVecCon* vecCon2 = comp->gtNewVconNode(simdType, simdBaseJitType); + vecCon2->gtSimd16Val = simd16Val; + + BlockRange().InsertAfter(op2, vecCon2); + + op2 = comp->gtNewSimdHWIntrinsicNode(simdType, op2, vecCon2, NI_SSE_And, simdBaseJitType, simdSize); + BlockRange().InsertAfter(vecCon2, op2); + + LowerNode(vecCon2); + LowerNode(op2); } } From 953f52482ac2460e4b3faff33e4f73c9b30cd7b4 Mon Sep 17 00:00:00 2001 From: Radek Zikmund <32671551+rzikm@users.noreply.github.com> Date: Fri, 2 Sep 2022 04:09:40 -0700 Subject: [PATCH 082/107] Revert "Unload MsQuic after checking for QUIC support to free resources. (#74749)" (#74984) This reverts commit 7a45201181d37329b7ab0bee541ed7c42b5d94b6. --- .../src/System/Net/Quic/Internal/MsQuicApi.cs | 83 ++++++------------- 1 file changed, 24 insertions(+), 59 deletions(-) diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Internal/MsQuicApi.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Internal/MsQuicApi.cs index eb06b9dce8e645..e2866454356dd2 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Internal/MsQuicApi.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Internal/MsQuicApi.cs @@ -1,7 +1,6 @@ // 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.Runtime.InteropServices; using Microsoft.Quic; @@ -48,8 +47,7 @@ private MsQuicApi(QUIC_API_TABLE* apiTable) } } - private static readonly Lazy _api = new Lazy(AllocateMsQuicApi); - internal static MsQuicApi Api => _api.Value; + internal static MsQuicApi Api { get; } = null!; internal static bool IsQuicSupported { get; } @@ -60,21 +58,29 @@ private MsQuicApi(QUIC_API_TABLE* apiTable) static MsQuicApi() { - if (!TryLoadMsQuic(out IntPtr msQuicHandle)) + IntPtr msQuicHandle; + if (!NativeLibrary.TryLoad($"{Interop.Libraries.MsQuic}.{MsQuicVersion.Major}", typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out msQuicHandle) && + !NativeLibrary.TryLoad(Interop.Libraries.MsQuic, typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out msQuicHandle)) { return; } try { - if (!TryOpenMsQuic(msQuicHandle, out QUIC_API_TABLE* apiTable)) + if (!NativeLibrary.TryGetExport(msQuicHandle, "MsQuicOpenVersion", out IntPtr msQuicOpenVersionAddress)) + { + return; + } + + QUIC_API_TABLE* apiTable = null; + delegate* unmanaged[Cdecl] msQuicOpenVersion = (delegate* unmanaged[Cdecl])msQuicOpenVersionAddress; + if (StatusFailed(msQuicOpenVersion((uint)MsQuicVersion.Major, &apiTable))) { return; } try { - // Check version int arraySize = 4; uint* libVersion = stackalloc uint[arraySize]; uint size = (uint)arraySize * sizeof(uint); @@ -93,7 +99,7 @@ static MsQuicApi() return; } - // Assume SChannel is being used on windows and query for the actual provider from the library if querying is supported + // Assume SChannel is being used on windows and query for the actual provider from the library QUIC_TLS_PROVIDER provider = OperatingSystem.IsWindows() ? QUIC_TLS_PROVIDER.SCHANNEL : QUIC_TLS_PROVIDER.OPENSSL; size = sizeof(QUIC_TLS_PROVIDER); apiTable->GetParam(null, QUIC_PARAM_GLOBAL_TLS_PROVIDER, &size, &provider); @@ -116,67 +122,26 @@ static MsQuicApi() Tls13ClientMayBeDisabled = IsTls13Disabled(isServer: false); } + Api = new MsQuicApi(apiTable); IsQuicSupported = true; } finally { - // Gracefully close the API table to free resources. The API table will be allocated lazily again if needed - bool closed = TryCloseMsQuic(msQuicHandle, apiTable); - Debug.Assert(closed, "Failed to close MsQuic"); + if (!IsQuicSupported && NativeLibrary.TryGetExport(msQuicHandle, "MsQuicClose", out IntPtr msQuicClose)) + { + // Gracefully close the API table + ((delegate* unmanaged[Cdecl])msQuicClose)(apiTable); + } } - } - finally - { - // Unload the library, we will load it again when we actually use QUIC - NativeLibrary.Free(msQuicHandle); - } - } - - private static MsQuicApi AllocateMsQuicApi() - { - Debug.Assert(IsQuicSupported); - - if (TryLoadMsQuic(out IntPtr msQuicHandle) && - TryOpenMsQuic(msQuicHandle, out QUIC_API_TABLE* apiTable)) - { - return new MsQuicApi(apiTable); - } - - throw new Exception("Failed to create MsQuicApi instance"); - } - private static bool TryLoadMsQuic(out IntPtr msQuicHandle) => - NativeLibrary.TryLoad($"{Interop.Libraries.MsQuic}.{MsQuicVersion.Major}", typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out msQuicHandle) || - NativeLibrary.TryLoad(Interop.Libraries.MsQuic, typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out msQuicHandle); - - private static bool TryOpenMsQuic(IntPtr msQuicHandle, out QUIC_API_TABLE* apiTable) - { - apiTable = null; - if (!NativeLibrary.TryGetExport(msQuicHandle, "MsQuicOpenVersion", out IntPtr msQuicOpenVersionAddress)) - { - return false; } - - QUIC_API_TABLE* table = null; - delegate* unmanaged[Cdecl] msQuicOpenVersion = (delegate* unmanaged[Cdecl])msQuicOpenVersionAddress; - if (StatusFailed(msQuicOpenVersion((uint)MsQuicVersion.Major, &table))) - { - return false; - } - - apiTable = table; - return true; - } - - private static bool TryCloseMsQuic(IntPtr msQuicHandle, QUIC_API_TABLE* apiTable) - { - if (NativeLibrary.TryGetExport(msQuicHandle, "MsQuicClose", out IntPtr msQuicClose)) + finally { - ((delegate* unmanaged[Cdecl])msQuicClose)(apiTable); - return true; + if (!IsQuicSupported) + { + NativeLibrary.Free(msQuicHandle); + } } - - return false; } private static bool IsWindowsVersionSupported() => OperatingSystem.IsWindowsVersionAtLeast(MinWindowsVersion.Major, From f723d4630d2465bd9a90618e172af4bb2ba1588d Mon Sep 17 00:00:00 2001 From: Vlad Brezae Date: Fri, 2 Sep 2022 14:56:56 +0300 Subject: [PATCH 083/107] [mono][jit] Zero extend the return when we might be invoking llvm generated code (#74796) --- src/mono/mono/mini/method-to-ir.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/mono/mono/mini/method-to-ir.c b/src/mono/mono/mini/method-to-ir.c index cfb8f7cc1ff888..41bece492d72db 100644 --- a/src/mono/mono/mini/method-to-ir.c +++ b/src/mono/mono/mini/method-to-ir.c @@ -2232,7 +2232,16 @@ static MonoInst* mono_emit_widen_call_res (MonoCompile *cfg, MonoInst *ins, MonoMethodSignature *fsig) { if (!MONO_TYPE_IS_VOID (fsig->ret)) { - if ((fsig->pinvoke || LLVM_ENABLED) && !m_type_is_byref (fsig->ret)) { + // FIXME + // LLVM code doesn't uses zero extend the full word while jit expects it. + // A proper fix would be to detect if we are actually using llvm code from aot images + // or make sure llvm code actually zero extends the return. +#ifdef MONO_ARCH_LLVM_SUPPORTED + gboolean might_use_llvm = TRUE; +#else + gboolean might_use_llvm = FALSE; +#endif + if ((fsig->pinvoke || might_use_llvm) && !m_type_is_byref (fsig->ret)) { int widen_op = -1; /* From 5639f8985978c44d422216905a78704b780d2b79 Mon Sep 17 00:00:00 2001 From: Bill Holmes Date: Fri, 2 Sep 2022 08:44:36 -0400 Subject: [PATCH 084/107] Avoid a crash when the debugger code fails to lookup the signature (#74957) In this particular case, one of the method arguments has a type that can not be resolved and the signature code returns null. --- src/mono/mono/component/debugger-agent.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/mono/mono/component/debugger-agent.c b/src/mono/mono/component/debugger-agent.c index 45404d5967b3f5..6a0ea5a49e708f 100644 --- a/src/mono/mono/component/debugger-agent.c +++ b/src/mono/mono/component/debugger-agent.c @@ -8573,6 +8573,8 @@ method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, g } case CMD_METHOD_GET_PARAM_INFO: { MonoMethodSignature *sig = mono_method_signature_internal (method); + if (!sig) + return ERR_INVALID_ARGUMENT; char **names; /* FIXME: mono_class_from_mono_type_internal () and byrefs */ From c8b0d87cb175512be55ac0d585770f9dcdee7557 Mon Sep 17 00:00:00 2001 From: Jo Shields Date: Fri, 2 Sep 2022 09:05:58 -0400 Subject: [PATCH 085/107] Don't try to build PGO tools on platforms with no CoreCLR port. (#74147) * Don't try to build PGO tools on platforms with no CoreCLR port. * Use PrimaryRuntimeFlavor for pgo exclusion conditional Closes: #74102 --- eng/Subsets.props | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/eng/Subsets.props b/eng/Subsets.props index dfd34ef59e6ea8..0ccf99e83f7223 100644 --- a/eng/Subsets.props +++ b/eng/Subsets.props @@ -62,7 +62,8 @@ mono.llvm+ $(DefaultMonoSubsets)mono.wasmruntime+ $(DefaultMonoSubsets)mono.aotcross+ - $(DefaultMonoSubsets)mono.runtime+mono.corelib+mono.packages+mono.tools+ + $(DefaultMonoSubsets)mono.runtime+mono.corelib+mono.packages+ + $(DefaultMonoSubsets)mono.tools+ $(DefaultMonoSubsets)host.native+ Invalid type for ParameterInfo member in Attribute class. - - Illegal characters in path. + + Null character in path. The given culture name '{0}' cannot be used to locate a resource file. Resource filenames must consist of only letters, numbers, hyphens or underscores. diff --git a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems index c334d0a1dbd908..e0c795ebb994a5 100644 --- a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems +++ b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems @@ -1644,9 +1644,6 @@ Common\Interop\Windows\Kernel32\Interop.GetSystemTimes.cs - - Common\Interop\Windows\Kernel32\Interop.GetTempFileNameW.cs - Common\Interop\Windows\Kernel32\Interop.GetVolumeInformation.cs diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerableFactory.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerableFactory.cs index 085983305bea9c..dbe0a624ed82b0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerableFactory.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerableFactory.cs @@ -30,10 +30,10 @@ internal static bool NormalizeInputs(ref string directory, ref string expression throw new ArgumentException(SR.Arg_Path2IsRooted, nameof(expression)); if (expression.Contains('\0')) - throw new ArgumentException(SR.Argument_InvalidPathChars, expression); + throw new ArgumentException(SR.Argument_NullCharInPath, expression); if (directory.Contains('\0')) - throw new ArgumentException(SR.Argument_InvalidPathChars, directory); + throw new ArgumentException(SR.Argument_NullCharInPath, directory); // We always allowed breaking the passed ref directory and filter to be separated // any way the user wanted. Looking for "C:\foo\*.cs" could be passed as "C:\" and diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.cs b/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.cs index 392791fd462b68..21f54d0c864eff 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.cs @@ -24,7 +24,7 @@ internal static void VerifyValidPath(string path, string argName) ArgumentException.ThrowIfNullOrEmpty(path, argName); if (path.Contains('\0')) { - throw new ArgumentException(SR.Argument_InvalidPathChars, argName); + throw new ArgumentException(SR.Argument_NullCharInPath, argName); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Path.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Path.Unix.cs index edb8f35dee500f..c6b4d904e25865 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Path.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Path.Unix.cs @@ -28,7 +28,7 @@ public static string GetFullPath(string path) ArgumentException.ThrowIfNullOrEmpty(path); if (path.Contains('\0')) - throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path)); + throw new ArgumentException(SR.Argument_NullCharInPath, nameof(path)); return GetFullPathInternal(path); } @@ -42,7 +42,7 @@ public static string GetFullPath(string path, string basePath) throw new ArgumentException(SR.Arg_BasePathNotFullyQualified, nameof(basePath)); if (basePath.Contains('\0') || path.Contains('\0')) - throw new ArgumentException(SR.Argument_InvalidPathChars); + throw new ArgumentException(SR.Argument_NullCharInPath); if (IsPathFullyQualified(path)) return GetFullPathInternal(path); @@ -111,7 +111,8 @@ public static unsafe string GetTempFileName() // Create, open, and close the temp file. fixed (byte* pPath = path) { - IntPtr fd = Interop.CheckIo(Interop.Sys.MksTemps(pPath, SuffixByteLength)); + // if this returns ENOENT it's because TMPDIR doesn't exist, so isDirError:true + IntPtr fd = Interop.CheckIo(Interop.Sys.MksTemps(pPath, SuffixByteLength), tempPath, isDirError:true); Interop.Sys.Close(fd); // ignore any errors from close; nothing to do if cleanup isn't possible } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Path.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Path.Windows.cs index cb5943720131fa..8f31c70c96cb86 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Path.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Path.Windows.cs @@ -53,7 +53,7 @@ public static string GetFullPath(string path) // This is because the nulls will signal the end of the string to Win32 and therefore have // unpredictable results. if (path.Contains('\0')) - throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path)); + throw new ArgumentException(SR.Argument_NullCharInPath, nameof(path)); return GetFullPathInternal(path); } @@ -67,7 +67,7 @@ public static string GetFullPath(string path, string basePath) throw new ArgumentException(SR.Arg_BasePathNotFullyQualified, nameof(basePath)); if (basePath.Contains('\0') || path.Contains('\0')) - throw new ArgumentException(SR.Argument_InvalidPathChars); + throw new ArgumentException(SR.Argument_NullCharInPath); if (IsPathFullyQualified(path)) return GetFullPathInternal(path); @@ -208,25 +208,57 @@ static uint GetTempPathW(int bufferLen, ref char buffer) // name on disk. public static string GetTempFileName() { - var tempPathBuilder = new ValueStringBuilder(stackalloc char[PathInternal.MaxShortPath]); - - GetTempPath(ref tempPathBuilder); - - var builder = new ValueStringBuilder(stackalloc char[PathInternal.MaxShortPath]); + // Avoid GetTempFileNameW because it is limited to 0xFFFF possibilities, which both + // means that it may have to make many attempts to create the file before + // finding an unused name, and also that if an app "leaks" such temp files, + // it can prevent GetTempFileNameW succeeding at all. + // + // To make this a little more robust, generate our own name with more + // entropy. We could use GetRandomFileName() here, but for consistency + // with Unix and to retain the ".tmp" extension we will use the "tmpXXXXXX.tmp" pattern. + // Using 32 characters for convenience, that gives us 32^^6 ~= 10^^9 possibilities, + // but we'll still loop to handle the unlikely case the file already exists. + + const int KeyLength = 4; + byte* bytes = stackalloc byte[KeyLength]; + + Span span = stackalloc char[13]; // tmpXXXXXX.tmp + span[0] = span[10] = 't'; + span[1] = span[11] = 'm'; + span[2] = span[12] = 'p'; + span[9] = '.'; + + int i = 0; + while (true) + { + Interop.GetRandomBytes(bytes, KeyLength); // 4 bytes = more than 6 x 5 bits - uint result = Interop.Kernel32.GetTempFileNameW( - ref tempPathBuilder.GetPinnableReference(), "tmp", 0, ref builder.GetPinnableReference()); + byte b0 = bytes[0]; + byte b1 = bytes[1]; + byte b2 = bytes[2]; + byte b3 = bytes[3]; - tempPathBuilder.Dispose(); + span[3] = (char)Base32Char[b0 & 0b0001_1111]; + span[4] = (char)Base32Char[b1 & 0b0001_1111]; + span[5] = (char)Base32Char[b2 & 0b0001_1111]; + span[6] = (char)Base32Char[b3 & 0b0001_1111]; + span[7] = (char)Base32Char[((b0 & 0b1110_0000) >> 5) | ((b1 & 0b1100_0000) >> 3)]; + span[8] = (char)Base32Char[((b2 & 0b1110_0000) >> 5) | ((b3 & 0b1100_0000) >> 3)]; - if (result == 0) - throw Win32Marshal.GetExceptionForLastWin32Error(); + string path = string.Concat(Path.GetTempPath(), span); - builder.Length = builder.RawChars.IndexOf('\0'); + try + { + File.OpenHandle(path, FileMode.CreateNew, FileAccess.Write).Dispose(); + } + catch (IOException ex) when (i < 100 && Win32Marshal.TryMakeWin32ErrorCodeFromHR(ex.HResult) == Interop.Errors.ERROR_FILE_EXISTS) + { + i++; // Don't let unforeseen circumstances cause us to loop forever + continue; // File already exists: very, very unlikely + } - string path = PathHelper.Normalize(ref builder); - builder.Dispose(); - return path; + return path; + } } // Tests if the given path contains a root. A path is considered rooted diff --git a/src/libraries/System.Runtime.Extensions/tests/System/IO/PathTests.cs b/src/libraries/System.Runtime.Extensions/tests/System/IO/PathTests.cs index aa1709024868b7..b248728a79da0a 100644 --- a/src/libraries/System.Runtime.Extensions/tests/System/IO/PathTests.cs +++ b/src/libraries/System.Runtime.Extensions/tests/System/IO/PathTests.cs @@ -182,7 +182,18 @@ public void GetTempFileName() try { Assert.True(File.Exists(tmpFile)); - Assert.Equal(".tmp", Path.GetExtension(tmpFile), ignoreCase: true, ignoreLineEndingDifferences: false, ignoreWhiteSpaceDifferences: false); + string fileName = Path.GetFileName(tmpFile); + Assert.StartsWith("tmp", fileName); + Assert.Equal("tmpXXXXXX.tmp".Length, fileName.Length); + Assert.EndsWith(".tmp", fileName); + + const string ValidChars = "abcdefghijklmnopqrstuvwxyz0123456789"; + for (int i = 3; i < 9; i++) + { + // Unix allows upper and lower case + Assert.True(ValidChars.Contains(char.ToLowerInvariant(fileName[i]))); + } + Assert.Equal(-1, tmpFile.IndexOfAny(Path.GetInvalidPathChars())); using (FileStream fs = File.OpenRead(tmpFile)) { @@ -222,6 +233,42 @@ public void GetTempFileNameTempUnicode() }).Dispose(); } + [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] + public void GetTempFileNameTempInvalidTemp() + { + // GetTempFileName has retries in it. It shouldn't hang in the face of a + // bad temp path. + RemoteExecutor.Invoke(() => + { + string goodTemp = Path.GetTempPath(); + string tempEnvVar = OperatingSystem.IsWindows() ? "TMP" : "TMPDIR"; + + try + { + string badTemp = Path.GetTempFileName(); + Assert.True(File.Exists(badTemp)); + + Environment.SetEnvironmentVariable(tempEnvVar, badTemp); + + Assert.StartsWith(badTemp, Path.GetTempPath()); + + Assert.Throws(() => Path.GetTempFileName()); // file not directory + File.Delete(badTemp); + Assert.Throws(() => Path.GetTempFileName()); // non existent + + if (OperatingSystem.IsWindows()) + { + Environment.SetEnvironmentVariable(tempEnvVar, "|||"); + Assert.Throws(() => Path.GetTempFileName()); // invalid path + } + } + finally + { + Environment.SetEnvironmentVariable(tempEnvVar, goodTemp); + } + }).Dispose(); + } + [Fact] public void GetFullPath_InvalidArgs() { From 85a1c65f9545bc1f3cf240b805094183b1221658 Mon Sep 17 00:00:00 2001 From: Alan Hayward Date: Fri, 2 Sep 2022 16:31:03 +0100 Subject: [PATCH 087/107] Fix inclusion for tests/run.sh (#74866) (#74875) * Fix inclusion for tests/run.sh * Resolve paths --- src/tests/run.sh | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/tests/run.sh b/src/tests/run.sh index d2a74b457482ee..68b2be192e70fe 100755 --- a/src/tests/run.sh +++ b/src/tests/run.sh @@ -44,8 +44,11 @@ readonly EXIT_CODE_SUCCESS=0 # Script ran normally. readonly EXIT_CODE_EXCEPTION=1 # Script exited because something exceptional happened (e.g. bad arguments, Ctrl-C interrupt). readonly EXIT_CODE_TEST_FAILURE=2 # Script completed successfully, but one or more tests failed. -# Argument variables +scriptPath="$(cd "$(dirname "$BASH_SOURCE[0]")"; pwd -P)" +repoRootDir="$(cd "$scriptPath"/../..; pwd -P)" source "$repoRootDir/eng/native/init-os-and-arch.sh" + +# Argument variables buildArch="$arch" buildOS= buildConfiguration="Debug" @@ -196,8 +199,6 @@ fi ################################################################################ runtestPyArguments=("-arch" "${buildArch}" "-build_type" "${buildConfiguration}") -scriptPath="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )" -repoRootDir=$scriptPath/../.. echo "Build Architecture : ${buildArch}" echo "Build Configuration : ${buildConfiguration}" From 28a6c07ecd407ac7bed91d2e242661973a042b94 Mon Sep 17 00:00:00 2001 From: Eric StJohn Date: Fri, 2 Sep 2022 08:34:12 -0700 Subject: [PATCH 088/107] Ensure Microsoft.Interop.SourceGeneration ships (#74943) * Ensure Microsoft.Interop.SourceGeneration ships Also fix the LibraryImportGenerator and JSImportGenerator to package Microsoft.Interop.SourceGeneration correctly (should IsPackable ever be set). * Fix project path * Remove packaging logic from interop source generator projects * Add back Microsoft.Interop.LibraryImportGenerator.props These are referenced by eng\generators.targets not just the package. --- src/libraries/NetCoreAppLibrary.props | 1 + .../JSImportGenerator/JSImportGenerator.csproj | 16 +--------------- .../LibraryImportGenerator.csproj | 18 ++---------------- .../Microsoft.Interop.SourceGeneration.csproj | 1 + 4 files changed, 5 insertions(+), 31 deletions(-) diff --git a/src/libraries/NetCoreAppLibrary.props b/src/libraries/NetCoreAppLibrary.props index 9d008faa152e17..9f8552592523e0 100644 --- a/src/libraries/NetCoreAppLibrary.props +++ b/src/libraries/NetCoreAppLibrary.props @@ -185,6 +185,7 @@ LibraryImportGenerator; JSImportGenerator; + Microsoft.Interop.SourceGeneration; System.Text.Json.SourceGeneration.Roslyn4.0; System.Text.RegularExpressions.Generator; diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportGenerator.csproj b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportGenerator.csproj index 90bdaf34e53dd3..7a1c2f9bb9caff 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportGenerator.csproj +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportGenerator.csproj @@ -9,15 +9,6 @@ RS2008;$(NoWarn) - - - - false - false - true - https://github.com/dotnet/runtime/tree/main/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator - JSImportGenerator - JSImportGenerator, analyzers $(DefineConstants);JSIMPORTGENERATOR cs @@ -28,12 +19,7 @@ - - - - - - + diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.csproj b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.csproj index c3cf1a6370f1e8..9a3f5a5d8e2df7 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.csproj +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/LibraryImportGenerator.csproj @@ -9,16 +9,7 @@ RS2008;$(NoWarn) - cs - - - - false - false - true - https://github.com/dotnet/runtime/tree/main/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator - LibraryImportGenerator - LibraryImportGenerator, analyzers + cs @@ -27,12 +18,7 @@ - - - - - - + diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Microsoft.Interop.SourceGeneration.csproj b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Microsoft.Interop.SourceGeneration.csproj index f9304841f0b346..e6e1b9f9e41a90 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Microsoft.Interop.SourceGeneration.csproj +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Microsoft.Interop.SourceGeneration.csproj @@ -5,6 +5,7 @@ Microsoft.Interop $(DefineConstants);MICROSOFT_INTEROP_SOURCEGENERATION true + cs From 72a82fe8e7f13972c4798d095453f5f799c58301 Mon Sep 17 00:00:00 2001 From: Brennan Date: Fri, 2 Sep 2022 09:14:31 -0700 Subject: [PATCH 089/107] [RateLimiting] Handle Timer jitter (#74360) --- .../RateLimiting/FixedWindowRateLimiter.cs | 13 +- .../FixedWindowRateLimiterOptions.cs | 1 + .../RateLimiting/SlidingWindowRateLimiter.cs | 6 +- .../SlidingWindowRateLimiterOptions.cs | 1 + .../RateLimiting/TokenBucketRateLimiter.cs | 36 +-- .../TokenBucketRateLimiterOptions.cs | 1 + .../tests/FixedWindowRateLimiterTests.cs | 211 +++++++----- .../tests/SlidingWindowRateLimiterTests.cs | 303 ++++++++++------- .../tests/TokenBucketRateLimiterTests.cs | 305 +++++++++++------- 9 files changed, 527 insertions(+), 350 deletions(-) diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/FixedWindowRateLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/FixedWindowRateLimiter.cs index fe4b0c29c3a627..774a6876c245ed 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/FixedWindowRateLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/FixedWindowRateLimiter.cs @@ -287,7 +287,7 @@ private void ReplenishInternal(long nowTicks) return; } - if ((long)((nowTicks - _lastReplenishmentTick) * TickFrequency) < _options.Window.Ticks) + if (((nowTicks - _lastReplenishmentTick) * TickFrequency) < _options.Window.Ticks && !_options.AutoReplenishment) { return; } @@ -295,21 +295,14 @@ private void ReplenishInternal(long nowTicks) _lastReplenishmentTick = nowTicks; int availableRequestCounters = _requestCount; - int maxPermits = _options.PermitLimit; - int resourcesToAdd; - if (availableRequestCounters < maxPermits) - { - resourcesToAdd = maxPermits - availableRequestCounters; - } - else + if (availableRequestCounters >= _options.PermitLimit) { // All counters available, nothing to do return; } - _requestCount += resourcesToAdd; - Debug.Assert(_requestCount == _options.PermitLimit); + _requestCount = _options.PermitLimit; // Process queued requests while (_queue.Count > 0) diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/FixedWindowRateLimiterOptions.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/FixedWindowRateLimiterOptions.cs index 92cac84012c064..a6d2b164755520 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/FixedWindowRateLimiterOptions.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/FixedWindowRateLimiterOptions.cs @@ -12,6 +12,7 @@ public sealed class FixedWindowRateLimiterOptions /// Specifies the time window that takes in the requests. /// Must be set to a value >= by the time these options are passed to the constructor of . /// + /// means the limiter will never replenish. public TimeSpan Window { get; set; } = TimeSpan.Zero; /// diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiter.cs index 1ccf40775e2d87..a1fe3e2839ed28 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiter.cs @@ -26,6 +26,7 @@ public sealed class SlidingWindowRateLimiter : ReplenishingRateLimiter private readonly Timer? _renewTimer; private readonly SlidingWindowRateLimiterOptions _options; + private readonly TimeSpan _replenishmentPeriod; private readonly Deque _queue = new Deque(); // Use the queue as the lock field so we don't need to allocate another object for a lock and have another field in the object @@ -42,7 +43,7 @@ public sealed class SlidingWindowRateLimiter : ReplenishingRateLimiter public override bool IsAutoReplenishing => _options.AutoReplenishment; /// - public override TimeSpan ReplenishmentPeriod => new TimeSpan(_options.Window.Ticks / _options.SegmentsPerWindow); + public override TimeSpan ReplenishmentPeriod => _replenishmentPeriod; /// /// Initializes the . @@ -78,6 +79,7 @@ public SlidingWindowRateLimiter(SlidingWindowRateLimiterOptions options) }; _requestCount = options.PermitLimit; + _replenishmentPeriod = new TimeSpan(_options.Window.Ticks / _options.SegmentsPerWindow); // _requestsPerSegment holds the no. of acquired requests in each window segment _requestsPerSegment = new int[options.SegmentsPerWindow]; @@ -287,7 +289,7 @@ private void ReplenishInternal(long nowTicks) return; } - if ((long)((nowTicks - _lastReplenishmentTick) * TickFrequency) < ReplenishmentPeriod.Ticks) + if (((nowTicks - _lastReplenishmentTick) * TickFrequency) < ReplenishmentPeriod.Ticks && !_options.AutoReplenishment) { return; } diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiterOptions.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiterOptions.cs index 8e1d397a57f11c..f7f399e175b1fc 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiterOptions.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/SlidingWindowRateLimiterOptions.cs @@ -12,6 +12,7 @@ public sealed class SlidingWindowRateLimiterOptions /// Specifies the minimum period between replenishments. /// Must be set to a value >= by the time these options are passed to the constructor of . /// + /// means the limiter will never replenish. public TimeSpan Window { get; set; } = TimeSpan.Zero; /// diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs index 7baf91ea590804..9238a62a0c03ee 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs @@ -13,7 +13,7 @@ namespace System.Threading.RateLimiting /// public sealed class TokenBucketRateLimiter : ReplenishingRateLimiter { - private int _tokenCount; + private double _tokenCount; private int _queueCount; private long _lastReplenishmentTick; private long? _idleSince; @@ -22,6 +22,7 @@ public sealed class TokenBucketRateLimiter : ReplenishingRateLimiter private long _failedLeasesCount; private long _successfulLeasesCount; + private readonly double _fillRate; private readonly Timer? _renewTimer; private readonly TokenBucketRateLimiterOptions _options; private readonly Deque _queue = new Deque(); @@ -76,6 +77,7 @@ public TokenBucketRateLimiter(TokenBucketRateLimiterOptions options) }; _tokenCount = options.TokenLimit; + _fillRate = (double)options.TokensPerPeriod / options.ReplenishmentPeriod.Ticks; _idleSince = _lastReplenishmentTick = Stopwatch.GetTimestamp(); @@ -91,7 +93,7 @@ public TokenBucketRateLimiter(TokenBucketRateLimiterOptions options) ThrowIfDisposed(); return new RateLimiterStatistics() { - CurrentAvailablePermits = _tokenCount, + CurrentAvailablePermits = (long)_tokenCount, CurrentQueuedCount = _queueCount, TotalFailedLeases = Interlocked.Read(ref _failedLeasesCount), TotalSuccessfulLeases = Interlocked.Read(ref _successfulLeasesCount), @@ -210,7 +212,7 @@ protected override ValueTask AcquireAsyncCore(int tokenCount, Ca private RateLimitLease CreateFailedTokenLease(int tokenCount) { - int replenishAmount = tokenCount - _tokenCount + _queueCount; + int replenishAmount = tokenCount - (int)_tokenCount + _queueCount; // can't have 0 replenish periods, that would mean it should be a successful lease // if TokensPerPeriod is larger than the replenishAmount needed then it would be 0 Debug.Assert(_options.TokensPerPeriod > 0); @@ -278,7 +280,7 @@ private static void Replenish(object? state) limiter!.ReplenishInternal(nowTicks); } - // Used in tests that test behavior with specific time intervals + // Used in tests to avoid dealing with real time private void ReplenishInternal(long nowTicks) { // method is re-entrant (from Timer), lock to avoid multiple simultaneous replenishes @@ -289,37 +291,35 @@ private void ReplenishInternal(long nowTicks) return; } - if ((long)((nowTicks - _lastReplenishmentTick) * TickFrequency) < _options.ReplenishmentPeriod.Ticks) + if (_tokenCount == _options.TokenLimit) { return; } - _lastReplenishmentTick = nowTicks; - - int availablePermits = _tokenCount; - TokenBucketRateLimiterOptions options = _options; - int maxPermits = options.TokenLimit; - int resourcesToAdd; + double add; - if (availablePermits < maxPermits) + // Trust the timer to be close enough to when we want to replenish, this avoids issues with Timer jitter where it might be .99 seconds instead of 1, and 1.1 seconds the next time etc. + if (_options.AutoReplenishment) { - resourcesToAdd = Math.Min(options.TokensPerPeriod, maxPermits - availablePermits); + add = _options.TokensPerPeriod; } else { - // All tokens available, nothing to do - return; + add = _fillRate * (nowTicks - _lastReplenishmentTick) * TickFrequency; } + _tokenCount = Math.Min(_options.TokenLimit, _tokenCount + add); + + _lastReplenishmentTick = nowTicks; + // Process queued requests Deque queue = _queue; - _tokenCount += resourcesToAdd; Debug.Assert(_tokenCount <= _options.TokenLimit); while (queue.Count > 0) { RequestRegistration nextPendingRequest = - options.QueueProcessingOrder == QueueProcessingOrder.OldestFirst + _options.QueueProcessingOrder == QueueProcessingOrder.OldestFirst ? queue.PeekHead() : queue.PeekTail(); @@ -327,7 +327,7 @@ private void ReplenishInternal(long nowTicks) { // Request can be fulfilled nextPendingRequest = - options.QueueProcessingOrder == QueueProcessingOrder.OldestFirst + _options.QueueProcessingOrder == QueueProcessingOrder.OldestFirst ? queue.DequeueHead() : queue.DequeueTail(); diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiterOptions.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiterOptions.cs index 55b63f65d36bc5..b0371119ce3c00 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiterOptions.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiterOptions.cs @@ -12,6 +12,7 @@ public sealed class TokenBucketRateLimiterOptions /// Specifies the minimum period between replenishments. /// Must be set to a value >= by the time these options are passed to the constructor of . /// + /// means the limiter will never replenish. public TimeSpan ReplenishmentPeriod { get; set; } = TimeSpan.Zero; /// diff --git a/src/libraries/System.Threading.RateLimiting/tests/FixedWindowRateLimiterTests.cs b/src/libraries/System.Threading.RateLimiting/tests/FixedWindowRateLimiterTests.cs index 6830a1ce742816..f5c75a0308ab28 100644 --- a/src/libraries/System.Threading.RateLimiting/tests/FixedWindowRateLimiterTests.cs +++ b/src/libraries/System.Threading.RateLimiting/tests/FixedWindowRateLimiterTests.cs @@ -17,7 +17,7 @@ public override void CanAcquireResource() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(); @@ -27,7 +27,7 @@ public override void CanAcquireResource() lease.Dispose(); Assert.False(limiter.AttemptAcquire().IsAcquired); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.True(limiter.AttemptAcquire().IsAcquired); } @@ -37,31 +37,40 @@ public override void InvalidOptionsThrows() { Assert.Throws( () => new FixedWindowRateLimiter(new FixedWindowRateLimiterOptions - { - PermitLimit = -1, - QueueProcessingOrder = QueueProcessingOrder.NewestFirst, - QueueLimit = 1, - Window = TimeSpan.FromMinutes(2), - AutoReplenishment = false - })); + { + PermitLimit = -1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = 1, + Window = TimeSpan.FromMinutes(2), + AutoReplenishment = false + })); Assert.Throws( () => new FixedWindowRateLimiter(new FixedWindowRateLimiterOptions - { - PermitLimit = 1, - QueueProcessingOrder = QueueProcessingOrder.NewestFirst, - QueueLimit = -1, - Window = TimeSpan.FromMinutes(2), - AutoReplenishment = false - })); + { + PermitLimit = 1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = -1, + Window = TimeSpan.FromMinutes(2), + AutoReplenishment = false + })); Assert.Throws( () => new FixedWindowRateLimiter(new FixedWindowRateLimiterOptions - { - PermitLimit = 1, - QueueProcessingOrder = QueueProcessingOrder.NewestFirst, - QueueLimit = 1, - Window = TimeSpan.MinValue, - AutoReplenishment = false - })); + { + PermitLimit = 1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = 1, + Window = TimeSpan.MinValue, + AutoReplenishment = false + })); + Assert.Throws( + () => new FixedWindowRateLimiter(new FixedWindowRateLimiterOptions + { + PermitLimit = 1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = 1, + Window = TimeSpan.FromMinutes(-2), + AutoReplenishment = false, + })); } [Fact] @@ -72,7 +81,7 @@ public override async Task CanAcquireResourceAsync() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); @@ -82,7 +91,7 @@ public override async Task CanAcquireResourceAsync() var wait = limiter.AcquireAsync(); Assert.False(wait.IsCompleted); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.True((await wait).IsAcquired); } @@ -95,7 +104,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsOldest() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 2, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = await limiter.AcquireAsync(); @@ -107,7 +116,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsOldest() Assert.False(wait2.IsCompleted); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); lease = await wait1; Assert.True(lease.IsAcquired); @@ -115,7 +124,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsOldest() lease.Dispose(); Assert.Equal(0, limiter.GetStatistics().CurrentAvailablePermits); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); lease = await wait2; Assert.True(lease.IsAcquired); @@ -129,7 +138,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsNewest() PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 3, - Window = TimeSpan.FromMinutes(0), + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); @@ -142,7 +151,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsNewest() Assert.False(wait2.IsCompleted); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); // second queued item completes first with NewestFirst lease = await wait2; @@ -151,7 +160,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsNewest() lease.Dispose(); Assert.Equal(1, limiter.GetStatistics().CurrentAvailablePermits); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); lease = await wait1; Assert.True(lease.IsAcquired); @@ -165,7 +174,7 @@ public override async Task FailsWhenQueuingMoreThanLimit_OldestFirst() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); using var lease = limiter.AttemptAcquire(1); @@ -174,7 +183,7 @@ public override async Task FailsWhenQueuingMoreThanLimit_OldestFirst() var failedLease = await limiter.AcquireAsync(1); Assert.False(failedLease.IsAcquired); Assert.True(failedLease.TryGetMetadata(MetadataName.RetryAfter, out var timeSpan)); - Assert.Equal(TimeSpan.Zero, timeSpan); + Assert.Equal(TimeSpan.FromMilliseconds(2), timeSpan); } [Fact] @@ -185,7 +194,7 @@ public override async Task DropsOldestWhenQueuingMoreThanLimit_NewestFirst() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(1); @@ -197,7 +206,7 @@ public override async Task DropsOldestWhenQueuingMoreThanLimit_NewestFirst() Assert.False(lease1.IsAcquired); Assert.False(wait2.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait2; Assert.True(lease.IsAcquired); @@ -211,7 +220,7 @@ public override async Task DropsMultipleOldestWhenQueuingMoreThanLimit_NewestFir PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 2, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(2); @@ -229,7 +238,7 @@ public override async Task DropsMultipleOldestWhenQueuingMoreThanLimit_NewestFir Assert.False(lease2.IsAcquired); Assert.False(wait3.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait3; Assert.True(lease.IsAcquired); @@ -243,7 +252,7 @@ public override async Task DropsRequestedLeaseIfPermitCountGreaterThanQueueLimit PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(2); @@ -256,7 +265,7 @@ public override async Task DropsRequestedLeaseIfPermitCountGreaterThanQueueLimit var lease1 = await limiter.AcquireAsync(2); Assert.False(lease1.IsAcquired); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); @@ -270,7 +279,7 @@ public override async Task QueueAvailableAfterQueueLimitHitAndResources_BecomeAv PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(1); @@ -279,14 +288,14 @@ public override async Task QueueAvailableAfterQueueLimitHitAndResources_BecomeAv var failedLease = await limiter.AcquireAsync(1); Assert.False(failedLease.IsAcquired); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); wait = limiter.AcquireAsync(1); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); } @@ -299,7 +308,7 @@ public override async Task LargeAcquiresAndQueuesDoNotIntegerOverflow() PermitLimit = int.MaxValue, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = int.MaxValue, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(int.MaxValue); @@ -315,7 +324,7 @@ public override async Task LargeAcquiresAndQueuesDoNotIntegerOverflow() var lease1 = await wait; Assert.False(lease1.IsAcquired); - limiter.TryReplenish(); + Replenish(limiter, 1L); var lease2 = await wait2; Assert.True(lease2.IsAcquired); } @@ -328,7 +337,7 @@ public override void ThrowsWhenAcquiringMoreThanLimit() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); Assert.Throws(() => limiter.AttemptAcquire(2)); @@ -342,7 +351,7 @@ public override async Task ThrowsWhenWaitingForMoreThanLimit() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); await Assert.ThrowsAsync(async () => await limiter.AcquireAsync(2)); @@ -356,7 +365,7 @@ public override void ThrowsWhenAcquiringLessThanZero() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); Assert.Throws(() => limiter.AttemptAcquire(-1)); @@ -370,7 +379,7 @@ public override async Task ThrowsWhenWaitingForLessThanZero() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); await Assert.ThrowsAsync(async () => await limiter.AcquireAsync(-1)); @@ -384,7 +393,7 @@ public override void AcquireZero_WithAvailability() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); @@ -400,7 +409,7 @@ public override void AcquireZero_WithoutAvailability() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); using var lease = limiter.AttemptAcquire(1); @@ -419,7 +428,7 @@ public override async Task AcquireAsyncZero_WithAvailability() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); @@ -435,7 +444,7 @@ public override async Task AcquireAsyncZero_WithoutAvailabilityWaitsForAvailabil PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = await limiter.AcquireAsync(1); @@ -445,7 +454,7 @@ public override async Task AcquireAsyncZero_WithoutAvailabilityWaitsForAvailabil Assert.False(wait.IsCompleted); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); using var lease2 = await wait; Assert.True(lease2.IsAcquired); } @@ -458,7 +467,7 @@ public override async Task CanDequeueMultipleResourcesAtOnce() PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 2, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); using var lease = await limiter.AcquireAsync(2); @@ -470,7 +479,7 @@ public override async Task CanDequeueMultipleResourcesAtOnce() Assert.False(wait2.IsCompleted); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); var lease1 = await wait1; var lease2 = await wait2; @@ -486,7 +495,7 @@ public override async Task CanCancelAcquireAsyncAfterQueuing() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(1); @@ -500,7 +509,7 @@ public override async Task CanCancelAcquireAsyncAfterQueuing() Assert.Equal(cts.Token, ex.CancellationToken); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.Equal(1, limiter.GetStatistics().CurrentAvailablePermits); } @@ -513,7 +522,7 @@ public override async Task CanCancelAcquireAsyncBeforeQueuing() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(1); @@ -526,7 +535,7 @@ public override async Task CanCancelAcquireAsyncBeforeQueuing() Assert.Equal(cts.Token, ex.CancellationToken); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.Equal(1, limiter.GetStatistics().CurrentAvailablePermits); } @@ -539,7 +548,7 @@ public override async Task CancelUpdatesQueueLimit() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(1); @@ -555,7 +564,7 @@ public override async Task CancelUpdatesQueueLimit() wait = limiter.AcquireAsync(1); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); } @@ -568,7 +577,7 @@ public override void NoMetadataOnAcquiredLease() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); using var lease = limiter.AttemptAcquire(1); @@ -583,7 +592,7 @@ public override void MetadataNamesContainsAllMetadata() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); using var lease = limiter.AttemptAcquire(1); @@ -598,7 +607,7 @@ public override async Task DisposeReleasesQueuedAcquires() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 3, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(1); @@ -631,7 +640,7 @@ public override async Task DisposeAsyncReleasesQueuedAcquires() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 3, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(1); @@ -770,7 +779,7 @@ public override async Task CanAcquireResourcesWithAcquireAsyncWithQueuedItemsIfN PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 2, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); @@ -785,7 +794,7 @@ public override async Task CanAcquireResourcesWithAcquireAsyncWithQueuedItemsIfN Assert.True(lease.IsAcquired); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); @@ -799,7 +808,7 @@ public override async Task CannotAcquireResourcesWithAcquireAsyncWithQueuedItems PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 3, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); @@ -811,13 +820,13 @@ public override async Task CannotAcquireResourcesWithAcquireAsyncWithQueuedItems Assert.False(wait.IsCompleted); Assert.False(wait2.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); Assert.False(wait2.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait2; Assert.True(lease.IsAcquired); @@ -831,7 +840,7 @@ public override async Task CanAcquireResourcesWithAcquireWithQueuedItemsIfNewest PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 3, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); @@ -845,7 +854,7 @@ public override async Task CanAcquireResourcesWithAcquireWithQueuedItemsIfNewest Assert.True(lease.IsAcquired); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); @@ -859,7 +868,7 @@ public override async Task CannotAcquireResourcesWithAcquireWithQueuedItemsIfOld PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 3, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); @@ -872,7 +881,7 @@ public override async Task CannotAcquireResourcesWithAcquireWithQueuedItemsIfOld lease = limiter.AttemptAcquire(1); Assert.False(lease.IsAcquired); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); @@ -918,11 +927,11 @@ public override void IdleDurationUpdatesWhenChangingFromActive() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 2, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); limiter.AttemptAcquire(1); - limiter.TryReplenish(); + Replenish(limiter, 1L); Assert.NotNull(limiter.IdleDuration); } @@ -962,7 +971,7 @@ public override async Task CanFillQueueWithNewestFirstAfterCancelingQueuedReques PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 2, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(2); @@ -988,7 +997,7 @@ public override async Task CanFillQueueWithNewestFirstAfterCancelingQueuedReques lease = await wait2; Assert.False(lease.IsAcquired); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait3; Assert.True(lease.IsAcquired); } @@ -1001,7 +1010,7 @@ public override async Task CanDisposeAfterCancelingQueuedRequest() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(1); @@ -1026,7 +1035,7 @@ public override void GetStatisticsReturnsNewInstances() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); @@ -1049,7 +1058,7 @@ public override async Task GetStatisticsHasCorrectValues() PermitLimit = 100, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 50, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); @@ -1093,7 +1102,7 @@ public override async Task GetStatisticsHasCorrectValues() Assert.Equal(2, stats.TotalFailedLeases); Assert.Equal(1, stats.TotalSuccessfulLeases); - limiter.TryReplenish(); + Replenish(limiter, 1); await lease2Task; // success from wait + available + queue @@ -1112,7 +1121,7 @@ public override async Task GetStatisticsWithZeroPermitCount() PermitLimit = 100, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 50, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); var lease = limiter.AttemptAcquire(0); @@ -1145,11 +1154,45 @@ public override void GetStatisticsThrowsAfterDispose() PermitLimit = 100, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 50, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), AutoReplenishment = false }); limiter.Dispose(); Assert.Throws(limiter.GetStatistics); } + + [Fact] + public void AutoReplenishIgnoresTimerJitter() + { + var replenishmentPeriod = TimeSpan.FromMinutes(10); + using var limiter = new FixedWindowRateLimiter(new FixedWindowRateLimiterOptions + { + PermitLimit = 10, + QueueProcessingOrder = QueueProcessingOrder.OldestFirst, + QueueLimit = 1, + Window = replenishmentPeriod, + AutoReplenishment = true, + }); + + var lease = limiter.AttemptAcquire(permitCount: 3); + Assert.True(lease.IsAcquired); + + Assert.Equal(7, limiter.GetStatistics().CurrentAvailablePermits); + + // Replenish 1 millisecond less than ReplenishmentPeriod while AutoReplenishment is enabled + Replenish(limiter, (long)replenishmentPeriod.TotalMilliseconds - 1); + + Assert.Equal(10, limiter.GetStatistics().CurrentAvailablePermits); + } + + private static readonly double TickFrequency = (double)TimeSpan.TicksPerSecond / Stopwatch.Frequency; + + static internal void Replenish(FixedWindowRateLimiter limiter, long addMilliseconds) + { + var replenishInternalMethod = typeof(FixedWindowRateLimiter).GetMethod("ReplenishInternal", Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance)!; + var internalTick = typeof(FixedWindowRateLimiter).GetField("_lastReplenishmentTick", Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance)!; + var currentTick = (long)internalTick.GetValue(limiter); + replenishInternalMethod.Invoke(limiter, new object[] { currentTick + addMilliseconds * (long)(TimeSpan.TicksPerMillisecond / TickFrequency) }); + } } } diff --git a/src/libraries/System.Threading.RateLimiting/tests/SlidingWindowRateLimiterTests.cs b/src/libraries/System.Threading.RateLimiting/tests/SlidingWindowRateLimiterTests.cs index 7241a39e0f1f4d..bd0d0d298d5adf 100644 --- a/src/libraries/System.Threading.RateLimiting/tests/SlidingWindowRateLimiterTests.cs +++ b/src/libraries/System.Threading.RateLimiting/tests/SlidingWindowRateLimiterTests.cs @@ -17,7 +17,7 @@ public override void CanAcquireResource() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -28,8 +28,8 @@ public override void CanAcquireResource() lease.Dispose(); Assert.False(limiter.AttemptAcquire().IsAcquired); - Assert.True(limiter.TryReplenish()); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); + Replenish(limiter, 1L); Assert.True(limiter.AttemptAcquire().IsAcquired); } @@ -39,44 +39,54 @@ public override void InvalidOptionsThrows() { Assert.Throws( () => new SlidingWindowRateLimiter(new SlidingWindowRateLimiterOptions - { - PermitLimit = -1, - QueueProcessingOrder = QueueProcessingOrder.NewestFirst, - QueueLimit = 1, - Window = TimeSpan.FromMinutes(2), - SegmentsPerWindow = 1, - AutoReplenishment = false - })); + { + PermitLimit = -1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = 1, + Window = TimeSpan.FromMinutes(2), + SegmentsPerWindow = 1, + AutoReplenishment = false + })); Assert.Throws( () => new SlidingWindowRateLimiter(new SlidingWindowRateLimiterOptions - { - PermitLimit = 1, - QueueProcessingOrder = QueueProcessingOrder.NewestFirst, - QueueLimit = -1, - Window = TimeSpan.FromMinutes(2), - SegmentsPerWindow = 1, - AutoReplenishment = false - })); + { + PermitLimit = 1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = -1, + Window = TimeSpan.FromMinutes(2), + SegmentsPerWindow = 1, + AutoReplenishment = false + })); Assert.Throws( () => new SlidingWindowRateLimiter(new SlidingWindowRateLimiterOptions - { - PermitLimit = 1, - QueueProcessingOrder = QueueProcessingOrder.NewestFirst, - QueueLimit = 1, - Window = TimeSpan.FromMinutes(2), - SegmentsPerWindow = -1, - AutoReplenishment = false - })); + { + PermitLimit = 1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = 1, + Window = TimeSpan.FromMinutes(2), + SegmentsPerWindow = -1, + AutoReplenishment = false + })); Assert.Throws( () => new SlidingWindowRateLimiter(new SlidingWindowRateLimiterOptions - { - PermitLimit = 1, - QueueProcessingOrder = QueueProcessingOrder.NewestFirst, - QueueLimit = 1, - Window = TimeSpan.MinValue, - SegmentsPerWindow = 1, - AutoReplenishment = false - })); + { + PermitLimit = 1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = 1, + Window = TimeSpan.MinValue, + SegmentsPerWindow = 1, + AutoReplenishment = false + })); + Assert.Throws( + () => new SlidingWindowRateLimiter(new SlidingWindowRateLimiterOptions + { + PermitLimit = 1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = 1, + Window = TimeSpan.FromMinutes(-2), + SegmentsPerWindow = 1, + AutoReplenishment = false + })); } [Fact] @@ -87,7 +97,7 @@ public override async Task CanAcquireResourceAsync() PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 4, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(2), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -98,14 +108,14 @@ public override async Task CanAcquireResourceAsync() var wait = limiter.AcquireAsync(2); Assert.False(wait.IsCompleted); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.False(wait.IsCompleted); var wait2 = limiter.AcquireAsync(2); Assert.False(wait2.IsCompleted); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.True((await wait2).IsAcquired); } @@ -121,7 +131,7 @@ public async Task CanAcquireMultipleRequestsAsync() PermitLimit = 4, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 4, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(3), SegmentsPerWindow = 3, AutoReplenishment = false }); @@ -132,19 +142,19 @@ public async Task CanAcquireMultipleRequestsAsync() var wait = limiter.AcquireAsync(3); Assert.False(wait.IsCompleted); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.False(wait.IsCompleted); var wait2 = limiter.AcquireAsync(2); Assert.True(wait2.IsCompleted); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); var wait3 = limiter.AcquireAsync(2); Assert.False(wait3.IsCompleted); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.True((await wait3).IsAcquired); Assert.False((await wait).IsAcquired); @@ -159,7 +169,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsOldest() PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 3, - Window = TimeSpan.FromMinutes(0), + Window = TimeSpan.FromMilliseconds(2), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -172,10 +182,10 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsOldest() Assert.False(wait2.IsCompleted); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.False(wait1.IsCompleted); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); lease = await wait1; Assert.True(lease.IsAcquired); @@ -183,8 +193,8 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsOldest() lease.Dispose(); Assert.Equal(1, limiter.GetStatistics().CurrentAvailablePermits); - Assert.True(limiter.TryReplenish()); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); + Replenish(limiter, 1L); lease = await wait2; Assert.True(lease.IsAcquired); @@ -198,7 +208,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsNewest() PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 3, - Window = TimeSpan.FromMinutes(0), + Window = TimeSpan.FromMilliseconds(2), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -212,10 +222,10 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsNewest() Assert.False(wait2.IsCompleted); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.False(wait2.IsCompleted); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); // second queued item completes first with NewestFirst lease = await wait2; Assert.True(lease.IsAcquired); @@ -223,8 +233,8 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsNewest() lease.Dispose(); Assert.Equal(1, limiter.GetStatistics().CurrentAvailablePermits); - Assert.True(limiter.TryReplenish()); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); + Replenish(limiter, 1L); lease = await wait1; Assert.True(lease.IsAcquired); @@ -238,7 +248,7 @@ public override async Task FailsWhenQueuingMoreThanLimit_OldestFirst() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -257,7 +267,7 @@ public override async Task DropsOldestWhenQueuingMoreThanLimit_NewestFirst() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -270,8 +280,8 @@ public override async Task DropsOldestWhenQueuingMoreThanLimit_NewestFirst() Assert.False(lease1.IsAcquired); Assert.False(wait2.IsCompleted); - limiter.TryReplenish(); - limiter.TryReplenish(); + Replenish(limiter, 1L); + Replenish(limiter, 1L); lease = await wait2; Assert.True(lease.IsAcquired); @@ -285,7 +295,7 @@ public override async Task DropsMultipleOldestWhenQueuingMoreThanLimit_NewestFir PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 2, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -304,8 +314,8 @@ public override async Task DropsMultipleOldestWhenQueuingMoreThanLimit_NewestFir Assert.False(lease2.IsAcquired); Assert.False(wait3.IsCompleted); - limiter.TryReplenish(); - limiter.TryReplenish(); + Replenish(limiter, 1L); + Replenish(limiter, 1L); lease = await wait3; Assert.True(lease.IsAcquired); @@ -319,7 +329,7 @@ public override async Task DropsRequestedLeaseIfPermitCountGreaterThanQueueLimit PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -333,8 +343,8 @@ public override async Task DropsRequestedLeaseIfPermitCountGreaterThanQueueLimit var lease1 = await limiter.AcquireAsync(2); Assert.False(lease1.IsAcquired); - limiter.TryReplenish(); - limiter.TryReplenish(); + Replenish(limiter, 1L); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); @@ -348,7 +358,7 @@ public override async Task QueueAvailableAfterQueueLimitHitAndResources_BecomeAv PermitLimit = 3, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 2, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(3), SegmentsPerWindow = 3, AutoReplenishment = false }); @@ -358,20 +368,20 @@ public override async Task QueueAvailableAfterQueueLimitHitAndResources_BecomeAv var failedLease = await limiter.AcquireAsync(2); Assert.False(failedLease.IsAcquired); - limiter.TryReplenish(); - limiter.TryReplenish(); + Replenish(limiter, 1L); + Replenish(limiter, 1L); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); wait = limiter.AcquireAsync(2); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); - limiter.TryReplenish(); - limiter.TryReplenish(); + Replenish(limiter, 1L); + Replenish(limiter, 1L); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); @@ -385,7 +395,7 @@ public override async Task LargeAcquiresAndQueuesDoNotIntegerOverflow() PermitLimit = int.MaxValue, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = int.MaxValue, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -402,8 +412,8 @@ public override async Task LargeAcquiresAndQueuesDoNotIntegerOverflow() var lease1 = await wait; Assert.False(lease1.IsAcquired); - limiter.TryReplenish(); - limiter.TryReplenish(); + Replenish(limiter, 1L); + Replenish(limiter, 1L); var lease2 = await wait2; Assert.True(lease2.IsAcquired); } @@ -416,7 +426,7 @@ public override void ThrowsWhenAcquiringMoreThanLimit() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 1, AutoReplenishment = false }); @@ -431,7 +441,7 @@ public override async Task ThrowsWhenWaitingForMoreThanLimit() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 1, AutoReplenishment = false }); @@ -446,7 +456,7 @@ public override void ThrowsWhenAcquiringLessThanZero() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 1, AutoReplenishment = false }); @@ -461,7 +471,7 @@ public override async Task ThrowsWhenWaitingForLessThanZero() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 1, AutoReplenishment = false }); @@ -476,7 +486,7 @@ public override void AcquireZero_WithAvailability() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 1, AutoReplenishment = false }); @@ -493,7 +503,7 @@ public override void AcquireZero_WithoutAvailability() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 1, AutoReplenishment = false }); @@ -513,7 +523,7 @@ public override async Task AcquireAsyncZero_WithAvailability() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 1, AutoReplenishment = false }); @@ -530,7 +540,7 @@ public override async Task AcquireAsyncZero_WithoutAvailabilityWaitsForAvailabil PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -541,8 +551,8 @@ public override async Task AcquireAsyncZero_WithoutAvailabilityWaitsForAvailabil Assert.False(wait.IsCompleted); lease.Dispose(); - Assert.True(limiter.TryReplenish()); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); + Replenish(limiter, 1L); using var lease2 = await wait; Assert.True(lease2.IsAcquired); } @@ -555,7 +565,7 @@ public override async Task CanDequeueMultipleResourcesAtOnce() PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 4, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -568,8 +578,8 @@ public override async Task CanDequeueMultipleResourcesAtOnce() Assert.False(wait2.IsCompleted); lease.Dispose(); - Assert.True(limiter.TryReplenish()); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); + Replenish(limiter, 1L); var lease1 = await wait1; var lease2 = await wait2; @@ -585,7 +595,7 @@ public override async Task CanCancelAcquireAsyncAfterQueuing() PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(2), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -600,7 +610,7 @@ public override async Task CanCancelAcquireAsyncAfterQueuing() Assert.Equal(cts.Token, ex.CancellationToken); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.Equal(0, limiter.GetStatistics().CurrentAvailablePermits); } @@ -613,7 +623,7 @@ public override async Task CanCancelAcquireAsyncBeforeQueuing() PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(2), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -627,7 +637,7 @@ public override async Task CanCancelAcquireAsyncBeforeQueuing() Assert.Equal(cts.Token, ex.CancellationToken); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.Equal(0, limiter.GetStatistics().CurrentAvailablePermits); } @@ -640,7 +650,7 @@ public override async Task CancelUpdatesQueueLimit() PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(2), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -657,8 +667,8 @@ public override async Task CancelUpdatesQueueLimit() wait = limiter.AcquireAsync(1); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); - limiter.TryReplenish(); + Replenish(limiter, 1L); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); @@ -673,7 +683,7 @@ public override void NoMetadataOnAcquiredLease() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -689,7 +699,7 @@ public override void MetadataNamesContainsAllMetadata() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 1, AutoReplenishment = false }); @@ -705,7 +715,7 @@ public override async Task DisposeReleasesQueuedAcquires() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 3, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 1, AutoReplenishment = false }); @@ -739,7 +749,7 @@ public override async Task DisposeAsyncReleasesQueuedAcquires() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 3, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -809,7 +819,7 @@ public override async Task CanAcquireResourcesWithAcquireAsyncWithQueuedItemsIfN PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 2, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(3), SegmentsPerWindow = 3, AutoReplenishment = false }); @@ -825,12 +835,12 @@ public override async Task CanAcquireResourcesWithAcquireAsyncWithQueuedItemsIfN Assert.True(lease.IsAcquired); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); + Replenish(limiter, 1L); Assert.False(wait.IsCompleted); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); } @@ -843,7 +853,7 @@ public override async Task CannotAcquireResourcesWithAcquireAsyncWithQueuedItems PermitLimit = 3, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 5, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(2), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -856,18 +866,18 @@ public override async Task CannotAcquireResourcesWithAcquireAsyncWithQueuedItems Assert.False(wait.IsCompleted); Assert.False(wait2.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); Assert.False(wait.IsCompleted); Assert.False(wait2.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); - limiter.TryReplenish(); - limiter.TryReplenish(); + Replenish(limiter, 1L); + Replenish(limiter, 1L); lease = await wait2; Assert.True(lease.IsAcquired); @@ -881,7 +891,7 @@ public override async Task CanAcquireResourcesWithAcquireWithQueuedItemsIfNewest PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 3, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -896,8 +906,8 @@ public override async Task CanAcquireResourcesWithAcquireWithQueuedItemsIfNewest Assert.True(lease.IsAcquired); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); - limiter.TryReplenish(); + Replenish(limiter, 1L); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); @@ -911,7 +921,7 @@ public override async Task CannotAcquireResourcesWithAcquireWithQueuedItemsIfOld PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 3, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -925,8 +935,8 @@ public override async Task CannotAcquireResourcesWithAcquireWithQueuedItemsIfOld lease = limiter.AttemptAcquire(1); Assert.False(lease.IsAcquired); - limiter.TryReplenish(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); @@ -974,13 +984,13 @@ public override void IdleDurationUpdatesWhenChangingFromActive() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 2, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); limiter.AttemptAcquire(1); - limiter.TryReplenish(); - limiter.TryReplenish(); + Replenish(limiter, 1L); + Replenish(limiter, 1L); Assert.NotNull(limiter.IdleDuration); } @@ -1022,7 +1032,7 @@ public override async Task CanFillQueueWithNewestFirstAfterCancelingQueuedReques PermitLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 2, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(2), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -1041,7 +1051,7 @@ public override async Task CanFillQueueWithNewestFirstAfterCancelingQueuedReques Assert.Equal(cts.Token, ex.CancellationToken); lease.Dispose(); - limiter.TryReplenish(); + Replenish(limiter, 1L); var wait3 = limiter.AcquireAsync(2); Assert.False(wait3.IsCompleted); @@ -1050,7 +1060,7 @@ public override async Task CanFillQueueWithNewestFirstAfterCancelingQueuedReques lease = await wait2; Assert.False(lease.IsAcquired); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait3; Assert.True(lease.IsAcquired); } @@ -1063,7 +1073,7 @@ public override async Task CanDisposeAfterCancelingQueuedRequest() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(1), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -1089,7 +1099,7 @@ public override void GetStatisticsReturnsNewInstances() PermitLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(2), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -1113,7 +1123,7 @@ public override async Task GetStatisticsHasCorrectValues() PermitLimit = 100, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 50, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(2), SegmentsPerWindow = 2, AutoReplenishment = false }); @@ -1138,7 +1148,7 @@ public override async Task GetStatisticsHasCorrectValues() Assert.Equal(0, stats.TotalFailedLeases); Assert.Equal(1, stats.TotalSuccessfulLeases); - limiter.TryReplenish(); + Replenish(limiter, 1); var lease3 = await limiter.AcquireAsync(1); Assert.False(lease3.IsAcquired); @@ -1156,7 +1166,7 @@ public override async Task GetStatisticsHasCorrectValues() Assert.Equal(2, stats.TotalFailedLeases); Assert.Equal(1, stats.TotalSuccessfulLeases); - limiter.TryReplenish(); + Replenish(limiter, 1); await lease2Task; stats = limiter.GetStatistics(); @@ -1174,7 +1184,7 @@ public override async Task GetStatisticsWithZeroPermitCount() PermitLimit = 100, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 50, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(3), SegmentsPerWindow = 3, AutoReplenishment = false }); @@ -1208,12 +1218,57 @@ public override void GetStatisticsThrowsAfterDispose() PermitLimit = 100, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 50, - Window = TimeSpan.Zero, + Window = TimeSpan.FromMilliseconds(3), SegmentsPerWindow = 3, AutoReplenishment = false }); limiter.Dispose(); Assert.Throws(limiter.GetStatistics); } + + [Fact] + public void AutoReplenishIgnoresTimerJitter() + { + var replenishmentPeriod = TimeSpan.FromMinutes(10); + using var limiter = new SlidingWindowRateLimiter(new SlidingWindowRateLimiterOptions + { + PermitLimit = 10, + QueueProcessingOrder = QueueProcessingOrder.OldestFirst, + QueueLimit = 1, + Window = replenishmentPeriod, + SegmentsPerWindow = 2, + AutoReplenishment = true, + }); + + var lease = limiter.AttemptAcquire(permitCount: 3); + Assert.True(lease.IsAcquired); + + Assert.Equal(7, limiter.GetStatistics().CurrentAvailablePermits); + + // Replenish 1 millisecond less than ReplenishmentPeriod while AutoReplenishment is enabled + Replenish(limiter, (long)replenishmentPeriod.TotalMilliseconds / 2 - 1); + + Assert.Equal(7, limiter.GetStatistics().CurrentAvailablePermits); + + lease = limiter.AttemptAcquire(permitCount: 3); + Assert.True(lease.IsAcquired); + + Assert.Equal(4, limiter.GetStatistics().CurrentAvailablePermits); + + // Replenish 1 millisecond longer than ReplenishmentPeriod while AutoReplenishment is enabled + Replenish(limiter, (long)replenishmentPeriod.TotalMilliseconds / 2 + 1); + + Assert.Equal(7, limiter.GetStatistics().CurrentAvailablePermits); + } + + private static readonly double TickFrequency = (double)TimeSpan.TicksPerSecond / Stopwatch.Frequency; + + static internal void Replenish(SlidingWindowRateLimiter limiter, long addMilliseconds) + { + var replenishInternalMethod = typeof(SlidingWindowRateLimiter).GetMethod("ReplenishInternal", Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance)!; + var internalTick = typeof(SlidingWindowRateLimiter).GetField("_lastReplenishmentTick", Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance)!; + var currentTick = (long)internalTick.GetValue(limiter); + replenishInternalMethod.Invoke(limiter, new object[] { currentTick + addMilliseconds * (long)(TimeSpan.TicksPerMillisecond / TickFrequency) }); + } } } diff --git a/src/libraries/System.Threading.RateLimiting/tests/TokenBucketRateLimiterTests.cs b/src/libraries/System.Threading.RateLimiting/tests/TokenBucketRateLimiterTests.cs index 272c294a09b345..69876938fdfba7 100644 --- a/src/libraries/System.Threading.RateLimiting/tests/TokenBucketRateLimiterTests.cs +++ b/src/libraries/System.Threading.RateLimiting/tests/TokenBucketRateLimiterTests.cs @@ -17,7 +17,7 @@ public override void CanAcquireResource() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -26,9 +26,10 @@ public override void CanAcquireResource() Assert.True(lease.IsAcquired); Assert.False(limiter.AttemptAcquire().IsAcquired); + // Dispose doesn't change token count lease.Dispose(); Assert.False(limiter.AttemptAcquire().IsAcquired); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.True(limiter.AttemptAcquire().IsAcquired); } @@ -38,44 +39,54 @@ public override void InvalidOptionsThrows() { Assert.Throws( () => new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions - { - TokenLimit = -1, - QueueProcessingOrder = QueueProcessingOrder.NewestFirst, - QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.FromMinutes(2), - TokensPerPeriod = 1, - AutoReplenishment = false - })); + { + TokenLimit = -1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = 1, + ReplenishmentPeriod = TimeSpan.FromMinutes(2), + TokensPerPeriod = 1, + AutoReplenishment = false + })); Assert.Throws( () => new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions - { - TokenLimit = 1, - QueueProcessingOrder = QueueProcessingOrder.NewestFirst, - QueueLimit = -1, - ReplenishmentPeriod = TimeSpan.FromMinutes(2), - TokensPerPeriod = 1, - AutoReplenishment = false - })); + { + TokenLimit = 1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = -1, + ReplenishmentPeriod = TimeSpan.FromMinutes(2), + TokensPerPeriod = 1, + AutoReplenishment = false + })); Assert.Throws( () => new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions - { - TokenLimit = 1, - QueueProcessingOrder = QueueProcessingOrder.NewestFirst, - QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.FromMinutes(2), - TokensPerPeriod = -1, - AutoReplenishment = false - })); + { + TokenLimit = 1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = 1, + ReplenishmentPeriod = TimeSpan.FromMinutes(2), + TokensPerPeriod = -1, + AutoReplenishment = false + })); Assert.Throws( () => new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions - { - TokenLimit = 1, - QueueProcessingOrder = QueueProcessingOrder.NewestFirst, - QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.MinValue, - TokensPerPeriod = 1, - AutoReplenishment = false - })); + { + TokenLimit = 1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = 1, + ReplenishmentPeriod = TimeSpan.MinValue, + TokensPerPeriod = 1, + AutoReplenishment = false + })); + Assert.Throws( + () => new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions + { + TokenLimit = 1, + QueueProcessingOrder = QueueProcessingOrder.NewestFirst, + QueueLimit = 1, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(-1), + TokensPerPeriod = 1, + AutoReplenishment = false + })); } [Fact] @@ -86,7 +97,7 @@ public override async Task CanAcquireResourceAsync() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -97,7 +108,7 @@ public override async Task CanAcquireResourceAsync() var wait = limiter.AcquireAsync(); Assert.False(wait.IsCompleted); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.True((await wait).IsAcquired); } @@ -110,7 +121,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsOldest() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 2, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -123,7 +134,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsOldest() Assert.False(wait2.IsCompleted); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); lease = await wait1; Assert.True(lease.IsAcquired); @@ -131,7 +142,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsOldest() lease.Dispose(); Assert.Equal(0, limiter.GetStatistics().CurrentAvailablePermits); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); lease = await wait2; Assert.True(lease.IsAcquired); @@ -145,7 +156,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsNewest() TokenLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 3, - ReplenishmentPeriod = TimeSpan.FromMinutes(0), + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -159,7 +170,7 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsNewest() Assert.False(wait2.IsCompleted); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); // second queued item completes first with NewestFirst lease = await wait2; @@ -168,8 +179,9 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsNewest() lease.Dispose(); Assert.Equal(0, limiter.GetStatistics().CurrentAvailablePermits); - Assert.True(limiter.TryReplenish()); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); + Assert.Equal(1, limiter.GetStatistics().CurrentAvailablePermits); + Replenish(limiter, 1L); lease = await wait1; Assert.True(lease.IsAcquired); @@ -183,7 +195,7 @@ public override async Task FailsWhenQueuingMoreThanLimit_OldestFirst() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -193,7 +205,7 @@ public override async Task FailsWhenQueuingMoreThanLimit_OldestFirst() var failedLease = await limiter.AcquireAsync(1); Assert.False(failedLease.IsAcquired); Assert.True(failedLease.TryGetMetadata(MetadataName.RetryAfter, out var timeSpan)); - Assert.Equal(TimeSpan.Zero, timeSpan); + Assert.Equal(TimeSpan.FromMilliseconds(2), timeSpan); } [Fact] @@ -204,7 +216,7 @@ public override async Task DropsOldestWhenQueuingMoreThanLimit_NewestFirst() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -217,7 +229,7 @@ public override async Task DropsOldestWhenQueuingMoreThanLimit_NewestFirst() Assert.False(lease1.IsAcquired); Assert.False(wait2.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait2; Assert.True(lease.IsAcquired); @@ -231,7 +243,7 @@ public override async Task DropsMultipleOldestWhenQueuingMoreThanLimit_NewestFir TokenLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 2, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -250,8 +262,8 @@ public override async Task DropsMultipleOldestWhenQueuingMoreThanLimit_NewestFir Assert.False(lease2.IsAcquired); Assert.False(wait3.IsCompleted); - limiter.TryReplenish(); - limiter.TryReplenish(); + Replenish(limiter, 1L); + Replenish(limiter, 1L); lease = await wait3; Assert.True(lease.IsAcquired); @@ -265,7 +277,7 @@ public override async Task DropsRequestedLeaseIfPermitCountGreaterThanQueueLimit TokenLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -279,7 +291,7 @@ public override async Task DropsRequestedLeaseIfPermitCountGreaterThanQueueLimit var lease1 = await limiter.AcquireAsync(2); Assert.False(lease1.IsAcquired); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); @@ -293,7 +305,7 @@ public override async Task QueueAvailableAfterQueueLimitHitAndResources_BecomeAv TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -303,14 +315,14 @@ public override async Task QueueAvailableAfterQueueLimitHitAndResources_BecomeAv var failedLease = await limiter.AcquireAsync(1); Assert.False(failedLease.IsAcquired); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); wait = limiter.AcquireAsync(1); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); } @@ -323,7 +335,7 @@ public override async Task LargeAcquiresAndQueuesDoNotIntegerOverflow() TokenLimit = int.MaxValue, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = int.MaxValue, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = int.MaxValue, AutoReplenishment = false }); @@ -340,7 +352,7 @@ public override async Task LargeAcquiresAndQueuesDoNotIntegerOverflow() var lease1 = await wait; Assert.False(lease1.IsAcquired); - limiter.TryReplenish(); + Replenish(limiter, 1L); var lease2 = await wait2; Assert.True(lease2.IsAcquired); } @@ -353,7 +365,7 @@ public override void ThrowsWhenAcquiringMoreThanLimit() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -368,7 +380,7 @@ public override async Task ThrowsWhenWaitingForMoreThanLimit() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -383,7 +395,7 @@ public override void ThrowsWhenAcquiringLessThanZero() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -398,7 +410,7 @@ public override async Task ThrowsWhenWaitingForLessThanZero() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -413,7 +425,7 @@ public override void AcquireZero_WithAvailability() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -430,7 +442,7 @@ public override void AcquireZero_WithoutAvailability() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -450,7 +462,7 @@ public override async Task AcquireAsyncZero_WithAvailability() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -467,7 +479,7 @@ public override async Task AcquireAsyncZero_WithoutAvailabilityWaitsForAvailabil TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -478,7 +490,7 @@ public override async Task AcquireAsyncZero_WithoutAvailabilityWaitsForAvailabil Assert.False(wait.IsCompleted); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); using var lease2 = await wait; Assert.True(lease2.IsAcquired); } @@ -491,7 +503,7 @@ public override async Task CanDequeueMultipleResourcesAtOnce() TokenLimit = 2, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 2, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 2, AutoReplenishment = false }); @@ -504,7 +516,7 @@ public override async Task CanDequeueMultipleResourcesAtOnce() Assert.False(wait2.IsCompleted); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); var lease1 = await wait1; var lease2 = await wait2; @@ -520,7 +532,7 @@ public override async Task CanCancelAcquireAsyncAfterQueuing() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -535,7 +547,7 @@ public override async Task CanCancelAcquireAsyncAfterQueuing() Assert.Equal(cts.Token, ex.CancellationToken); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.Equal(1, limiter.GetStatistics().CurrentAvailablePermits); } @@ -548,7 +560,7 @@ public override async Task CanFillQueueWithNewestFirstAfterCancelingQueuedReques TokenLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 2, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 2, AutoReplenishment = false }); @@ -575,7 +587,7 @@ public override async Task CanFillQueueWithNewestFirstAfterCancelingQueuedReques lease = await wait2; Assert.False(lease.IsAcquired); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait3; Assert.True(lease.IsAcquired); } @@ -588,7 +600,7 @@ public override async Task CanDisposeAfterCancelingQueuedRequest() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -614,7 +626,7 @@ public override async Task CanCancelAcquireAsyncBeforeQueuing() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -628,7 +640,7 @@ public override async Task CanCancelAcquireAsyncBeforeQueuing() Assert.Equal(cts.Token, ex.CancellationToken); lease.Dispose(); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.Equal(1, limiter.GetStatistics().CurrentAvailablePermits); } @@ -641,7 +653,7 @@ public override async Task CancelUpdatesQueueLimit() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -658,7 +670,7 @@ public override async Task CancelUpdatesQueueLimit() wait = limiter.AcquireAsync(1); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); } @@ -671,7 +683,7 @@ public override void NoMetadataOnAcquiredLease() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -687,7 +699,7 @@ public override void MetadataNamesContainsAllMetadata() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -703,7 +715,7 @@ public override async Task DisposeReleasesQueuedAcquires() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 3, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -737,7 +749,7 @@ public override async Task DisposeAsyncReleasesQueuedAcquires() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 3, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); @@ -888,14 +900,14 @@ public async Task CorrectRetryMetadataWithNonZeroAvailableItems() } [Fact] - public void TryReplenishHonorsTokensPerPeriod() + public void ReplenishHonorsTokensPerPeriod() { var limiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions { TokenLimit = 7, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 3, AutoReplenishment = false }); @@ -903,27 +915,28 @@ public void TryReplenishHonorsTokensPerPeriod() Assert.False(limiter.AttemptAcquire(3).IsAcquired); Assert.Equal(2, limiter.GetStatistics().CurrentAvailablePermits); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.Equal(5, limiter.GetStatistics().CurrentAvailablePermits); - Assert.True(limiter.TryReplenish()); + Replenish(limiter, 1L); Assert.Equal(7, limiter.GetStatistics().CurrentAvailablePermits); } [Fact] - public void TryReplenishWithAllTokensAvailable_Noops() + public async void TryReplenishWithAllTokensAvailable_Noops() { var limiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions { TokenLimit = 2, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(30), TokensPerPeriod = 1, AutoReplenishment = false }); Assert.Equal(2, limiter.GetStatistics().CurrentAvailablePermits); - Assert.True(limiter.TryReplenish()); + await Task.Delay(100); + limiter.TryReplenish(); Assert.Equal(2, limiter.GetStatistics().CurrentAvailablePermits); } @@ -971,7 +984,7 @@ public override async Task CanAcquireResourcesWithAcquireAsyncWithQueuedItemsIfN TokenLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 2, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 2, AutoReplenishment = false }); @@ -987,7 +1000,7 @@ public override async Task CanAcquireResourcesWithAcquireAsyncWithQueuedItemsIfN Assert.True(lease.IsAcquired); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); @@ -1001,7 +1014,7 @@ public override async Task CannotAcquireResourcesWithAcquireAsyncWithQueuedItems TokenLimit = 2, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 3, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 2, AutoReplenishment = false }); @@ -1014,13 +1027,13 @@ public override async Task CannotAcquireResourcesWithAcquireAsyncWithQueuedItems Assert.False(wait.IsCompleted); Assert.False(wait2.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); Assert.False(wait2.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait2; Assert.True(lease.IsAcquired); @@ -1034,7 +1047,7 @@ public override async Task CanAcquireResourcesWithAcquireWithQueuedItemsIfNewest TokenLimit = 2, QueueProcessingOrder = QueueProcessingOrder.NewestFirst, QueueLimit = 3, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 2, AutoReplenishment = false }); @@ -1049,7 +1062,7 @@ public override async Task CanAcquireResourcesWithAcquireWithQueuedItemsIfNewest Assert.True(lease.IsAcquired); Assert.False(wait.IsCompleted); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); @@ -1063,7 +1076,7 @@ public override async Task CannotAcquireResourcesWithAcquireWithQueuedItemsIfOld TokenLimit = 2, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 3, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 2, AutoReplenishment = false }); @@ -1077,14 +1090,12 @@ public override async Task CannotAcquireResourcesWithAcquireWithQueuedItemsIfOld lease = limiter.AttemptAcquire(1); Assert.False(lease.IsAcquired); - limiter.TryReplenish(); + Replenish(limiter, 1L); lease = await wait; Assert.True(lease.IsAcquired); } - private static readonly double TickFrequency = (double)TimeSpan.TicksPerSecond / Stopwatch.Frequency; - [Fact] public async Task ReplenishWorksWithTicksOverInt32Max() { @@ -1098,16 +1109,16 @@ public async Task ReplenishWorksWithTicksOverInt32Max() AutoReplenishment = false }); + // Ensure next tick is over uint.MaxValue + Replenish(limiter, uint.MaxValue); + var lease = limiter.AttemptAcquire(10); Assert.True(lease.IsAcquired); var wait = limiter.AcquireAsync(1); Assert.False(wait.IsCompleted); - var replenishInternalMethod = typeof(TokenBucketRateLimiter).GetMethod("ReplenishInternal", Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance)!; - // Ensure next tick is over uint.MaxValue - var tick = Stopwatch.GetTimestamp() + uint.MaxValue; - replenishInternalMethod.Invoke(limiter, new object[] { tick }); + Replenish(limiter, 2L); lease = await wait; Assert.True(lease.IsAcquired); @@ -1116,11 +1127,11 @@ public async Task ReplenishWorksWithTicksOverInt32Max() Assert.False(wait.IsCompleted); // Tick 1 millisecond too soon and verify that the queued item wasn't completed - replenishInternalMethod.Invoke(limiter, new object[] { tick + 1L * (long)(TimeSpan.TicksPerMillisecond / TickFrequency) }); + Replenish(limiter, 1L); Assert.False(wait.IsCompleted); // ticks would wrap if using uint - replenishInternalMethod.Invoke(limiter, new object[] { tick + 2L * (long)(TimeSpan.TicksPerMillisecond / TickFrequency) }); + Replenish(limiter, 2L); lease = await wait; Assert.True(lease.IsAcquired); } @@ -1167,12 +1178,12 @@ public override void IdleDurationUpdatesWhenChangingFromActive() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 2, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 1, AutoReplenishment = false }); limiter.AttemptAcquire(1); - limiter.TryReplenish(); + Replenish(limiter, 1L); Assert.NotNull(limiter.IdleDuration); } @@ -1214,7 +1225,7 @@ public override void GetStatisticsReturnsNewInstances() TokenLimit = 1, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 1, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 2, AutoReplenishment = false }); @@ -1238,7 +1249,7 @@ public override async Task GetStatisticsHasCorrectValues() TokenLimit = 100, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 50, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 30, AutoReplenishment = false }); @@ -1279,7 +1290,7 @@ public override async Task GetStatisticsHasCorrectValues() Assert.Equal(2, stats.TotalFailedLeases); Assert.Equal(1, stats.TotalSuccessfulLeases); - limiter.TryReplenish(); + Replenish(limiter, 1); await lease2Task; stats = limiter.GetStatistics(); @@ -1297,7 +1308,7 @@ public override async Task GetStatisticsWithZeroPermitCount() TokenLimit = 100, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 50, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 30, AutoReplenishment = false }); @@ -1331,12 +1342,82 @@ public override void GetStatisticsThrowsAfterDispose() TokenLimit = 100, QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 50, - ReplenishmentPeriod = TimeSpan.Zero, + ReplenishmentPeriod = TimeSpan.FromMilliseconds(1), TokensPerPeriod = 30, AutoReplenishment = false }); limiter.Dispose(); Assert.Throws(limiter.GetStatistics); } + + [Fact] + public void AutoReplenishIgnoresTimerJitter() + { + var replenishmentPeriod = TimeSpan.FromMinutes(10); + using var limiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions + { + TokenLimit = 10, + QueueProcessingOrder = QueueProcessingOrder.OldestFirst, + QueueLimit = 1, + ReplenishmentPeriod = replenishmentPeriod, + AutoReplenishment = true, + TokensPerPeriod = 1, + }); + + var lease = limiter.AttemptAcquire(permitCount: 3); + Assert.True(lease.IsAcquired); + + Assert.Equal(7, limiter.GetStatistics().CurrentAvailablePermits); + + // Replenish 1 millisecond less than ReplenishmentPeriod while AutoReplenishment is enabled + Replenish(limiter, (long)replenishmentPeriod.TotalMilliseconds - 1); + + Assert.Equal(8, limiter.GetStatistics().CurrentAvailablePermits); + + // Replenish 1 millisecond longer than ReplenishmentPeriod while AutoReplenishment is enabled + Replenish(limiter, (long)replenishmentPeriod.TotalMilliseconds + 1); + + Assert.Equal(9, limiter.GetStatistics().CurrentAvailablePermits); + } + + [Fact] + public void ManualReplenishPreservesTimeWithTimerJitter() + { + var replenishmentPeriod = TimeSpan.FromMinutes(10); + using var limiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions + { + TokenLimit = 10, + QueueProcessingOrder = QueueProcessingOrder.OldestFirst, + QueueLimit = 1, + ReplenishmentPeriod = replenishmentPeriod, + AutoReplenishment = false, + TokensPerPeriod = 1, + }); + + var lease = limiter.AttemptAcquire(permitCount: 3); + Assert.True(lease.IsAcquired); + + Assert.Equal(7, limiter.GetStatistics().CurrentAvailablePermits); + + // Replenish 1 millisecond less than ReplenishmentPeriod while AutoReplenishment is enabled + Replenish(limiter, (long)replenishmentPeriod.TotalMilliseconds - 1); + + Assert.Equal(7, limiter.GetStatistics().CurrentAvailablePermits); + + // Replenish 1 millisecond longer than ReplenishmentPeriod while AutoReplenishment is enabled + Replenish(limiter, (long)replenishmentPeriod.TotalMilliseconds + 1); + + Assert.Equal(9, limiter.GetStatistics().CurrentAvailablePermits); + } + + private static readonly double TickFrequency = (double)TimeSpan.TicksPerSecond / Stopwatch.Frequency; + + static internal void Replenish(TokenBucketRateLimiter limiter, long addMilliseconds) + { + var replenishInternalMethod = typeof(TokenBucketRateLimiter).GetMethod("ReplenishInternal", Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance)!; + var internalTick = typeof(TokenBucketRateLimiter).GetField("_lastReplenishmentTick", Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance)!; + var currentTick = (long)internalTick.GetValue(limiter); + replenishInternalMethod.Invoke(limiter, new object[] { currentTick + addMilliseconds * (long)(TimeSpan.TicksPerMillisecond / TickFrequency) }); + } } } From 2f64bc7bc8b84951f39f8da5359be176cd8bdb2e Mon Sep 17 00:00:00 2001 From: Nick Stanton Date: Fri, 2 Sep 2022 09:35:18 -0700 Subject: [PATCH 090/107] Remove Unending Task from Background Service (#74789) * Change StopAsync to include new API functionality with else-case for previous versions * Accept Stephen revision and update for coding style rule 10 * Wrap in try-catch as previous behavior also ignored this exception * Generalize across all TFMs --- .../src/BackgroundService.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/BackgroundService.cs b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/BackgroundService.cs index 3837a695279d72..4e9a62d53b9a86 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/BackgroundService.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/BackgroundService.cs @@ -74,7 +74,10 @@ public virtual async Task StopAsync(CancellationToken cancellationToken) finally { // Wait until the task completes or the stop token triggers - await Task.WhenAny(_executeTask, Task.Delay(Timeout.Infinite, cancellationToken)).ConfigureAwait(false); + var tcs = new TaskCompletionSource(); + using CancellationTokenRegistration registration = cancellationToken.Register(s => ((TaskCompletionSource)s!).SetCanceled(), tcs); + // Do not await the _executeTask because cancelling it will throw an OperationCanceledException which we are explicitly ignoring + await Task.WhenAny(_executeTask, tcs.Task).ConfigureAwait(false); } } From 635ecd663af7996eea9988cf7e4092bb730a00ba Mon Sep 17 00:00:00 2001 From: Andy Ayers Date: Fri, 2 Sep 2022 09:38:23 -0700 Subject: [PATCH 091/107] JIT: assign plausible loop number to new throw helper blocks (#74978) These can get added during CSE and may appear in a span of blocks that comprise an existing loop. Annotate the new blocks as belonging to an appropriate loop, even though by rights they don't belong to any loop. Closes #74739. --- src/coreclr/jit/fgbasic.cpp | 52 +++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/coreclr/jit/fgbasic.cpp b/src/coreclr/jit/fgbasic.cpp index f4e078cbaa1bc2..20c880ddc66646 100644 --- a/src/coreclr/jit/fgbasic.cpp +++ b/src/coreclr/jit/fgbasic.cpp @@ -6495,6 +6495,58 @@ BasicBlock* Compiler::fgNewBBinRegionWorker(BBjumpKinds jumpKind, /* If afterBlk falls through, we insert a jump around newBlk */ fgConnectFallThrough(afterBlk, newBlk->bbNext); + // If the loop table is valid, add this block to the appropriate loop. + // Note we don't verify (via flow) that this block actually belongs + // to the loop, just that it is lexically within the span of blocks + // in the loop. + // + if (optLoopTableValid) + { + BasicBlock* const bbPrev = newBlk->bbPrev; + BasicBlock* const bbNext = newBlk->bbNext; + + if ((bbPrev != nullptr) && (bbNext != nullptr)) + { + BasicBlock::loopNumber const prevLoopNum = bbPrev->bbNatLoopNum; + BasicBlock::loopNumber const nextLoopNum = bbNext->bbNatLoopNum; + + if ((prevLoopNum != BasicBlock::NOT_IN_LOOP) && (nextLoopNum != BasicBlock::NOT_IN_LOOP)) + { + if (prevLoopNum == nextLoopNum) + { + newBlk->bbNatLoopNum = prevLoopNum; + } + else + { + BasicBlock::loopNumber const prevParentLoopNum = optLoopTable[prevLoopNum].lpParent; + BasicBlock::loopNumber const nextParentLoopNum = optLoopTable[nextLoopNum].lpParent; + + if (nextParentLoopNum == prevLoopNum) + { + // next is in child loop + newBlk->bbNatLoopNum = prevLoopNum; + } + else if (prevParentLoopNum == nextLoopNum) + { + // prev is in child loop + newBlk->bbNatLoopNum = nextLoopNum; + } + else + { + // next and prev are siblings + assert(prevParentLoopNum == nextParentLoopNum); + newBlk->bbNatLoopNum = prevParentLoopNum; + } + } + } + } + + if (newBlk->bbNatLoopNum != BasicBlock::NOT_IN_LOOP) + { + JITDUMP("Marked " FMT_BB " as lying within " FMT_LP "\n", newBlk->bbNum, newBlk->bbNatLoopNum); + } + } + #ifdef DEBUG fgVerifyHandlerTab(); #endif From bf895c96f8b72de0788af332152d92813d84f668 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 2 Sep 2022 19:26:16 +0200 Subject: [PATCH 092/107] [main] Update dependencies from 7 repositories (#74705) * Update dependencies from https://github.com/dotnet/roslyn-analyzers build 20220826.2 Microsoft.CodeAnalysis.NetAnalyzers From Version 7.0.0-preview1.22419.4 -> To Version 7.0.0-preview1.22426.2 * Update dependencies from https://github.com/dotnet/llvm-project build 20220826.3 runtime.linux-arm64.Microsoft.NETCore.Runtime.ObjWriter , runtime.linux-musl-arm64.Microsoft.NETCore.Runtime.ObjWriter , runtime.linux-musl-x64.Microsoft.NETCore.Runtime.ObjWriter , runtime.linux-x64.Microsoft.NETCore.Runtime.ObjWriter , runtime.osx.11.0-arm64.Microsoft.NETCore.Runtime.ObjWriter , runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.ObjWriter , runtime.win-arm64.Microsoft.NETCore.Runtime.ObjWriter , runtime.win-x64.Microsoft.NETCore.Runtime.ObjWriter From Version 1.0.0-alpha.1.22411.1 -> To Version 1.0.0-alpha.1.22426.3 * Update dependencies from https://github.com/dotnet/runtime build 20220827.5 Microsoft.NET.Sdk.IL , Microsoft.NETCore.App.Runtime.win-x64 , Microsoft.NETCore.ILAsm , runtime.native.System.IO.Ports , System.Text.Json From Version 8.0.0-alpha.1.22421.15 -> To Version 8.0.0-alpha.1.22427.5 * Update dependencies from https://github.com/dotnet/icu build 20220829.1 Microsoft.NETCore.Runtime.ICU.Transport From Version 8.0.0-alpha.1.22422.1 -> To Version 8.0.0-alpha.1.22429.1 * Update dependencies from https://github.com/dotnet/xharness build 20220829.1 Microsoft.DotNet.XHarness.CLI , Microsoft.DotNet.XHarness.TestRunners.Common , Microsoft.DotNet.XHarness.TestRunners.Xunit From Version 1.0.0-prerelease.22422.1 -> To Version 1.0.0-prerelease.22429.1 * Update dependencies from https://github.com/dotnet/runtime-assets build 20220830.1 Microsoft.DotNet.CilStrip.Sources , System.ComponentModel.TypeConverter.TestData , System.Drawing.Common.TestData , System.Formats.Tar.TestData , System.IO.Compression.TestData , System.IO.Packaging.TestData , System.Net.TestData , System.Private.Runtime.UnicodeData , System.Runtime.Numerics.TestData , System.Runtime.TimeZoneData , System.Security.Cryptography.X509Certificates.TestData , System.Text.RegularExpressions.TestData , System.Windows.Extensions.TestData From Version 7.0.0-beta.22422.1 -> To Version 7.0.0-beta.22430.1 * Update dependencies from https://github.com/dotnet/roslyn-analyzers build 20220829.1 Microsoft.CodeAnalysis.NetAnalyzers From Version 7.0.0-preview1.22419.4 -> To Version 7.0.0-preview1.22429.1 * Update dependencies from https://github.com/dotnet/llvm-project build 20220829.2 runtime.linux-arm64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk , runtime.linux-arm64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools , runtime.linux-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk , runtime.linux-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools , runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk , runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools , runtime.win-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk , runtime.win-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools From Version 11.1.0-alpha.1.22425.1 -> To Version 11.1.0-alpha.1.22429.2 * Update dependencies from https://github.com/dotnet/icu build 20220901.1 Microsoft.NETCore.Runtime.ICU.Transport From Version 8.0.0-alpha.1.22422.1 -> To Version 8.0.0-alpha.1.22451.1 * Update dependencies from https://github.com/dotnet/xharness build 20220901.1 Microsoft.DotNet.XHarness.CLI , Microsoft.DotNet.XHarness.TestRunners.Common , Microsoft.DotNet.XHarness.TestRunners.Xunit From Version 1.0.0-prerelease.22422.1 -> To Version 1.0.0-prerelease.22451.1 * Update dependencies from https://github.com/dotnet/roslyn-analyzers build 20220831.2 Microsoft.CodeAnalysis.NetAnalyzers From Version 7.0.0-preview1.22419.4 -> To Version 7.0.0-preview1.22431.2 * Update dependencies from https://github.com/dotnet/llvm-project build 20220831.4 runtime.linux-arm64.Microsoft.NETCore.Runtime.ObjWriter , runtime.linux-musl-arm64.Microsoft.NETCore.Runtime.ObjWriter , runtime.linux-musl-x64.Microsoft.NETCore.Runtime.ObjWriter , runtime.linux-x64.Microsoft.NETCore.Runtime.ObjWriter , runtime.osx.11.0-arm64.Microsoft.NETCore.Runtime.ObjWriter , runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.ObjWriter , runtime.win-arm64.Microsoft.NETCore.Runtime.ObjWriter , runtime.win-x64.Microsoft.NETCore.Runtime.ObjWriter From Version 1.0.0-alpha.1.22411.1 -> To Version 1.0.0-alpha.1.22431.4 * Update dependencies from https://github.com/dotnet/icu build 20220901.5 Microsoft.NETCore.Runtime.ICU.Transport From Version 8.0.0-alpha.1.22422.1 -> To Version 8.0.0-alpha.1.22451.5 * Update dependencies from https://github.com/dotnet/runtime-assets build 20220901.1 Microsoft.DotNet.CilStrip.Sources , System.ComponentModel.TypeConverter.TestData , System.Drawing.Common.TestData , System.Formats.Tar.TestData , System.IO.Compression.TestData , System.IO.Packaging.TestData , System.Net.TestData , System.Private.Runtime.UnicodeData , System.Runtime.Numerics.TestData , System.Runtime.TimeZoneData , System.Security.Cryptography.X509Certificates.TestData , System.Text.RegularExpressions.TestData , System.Windows.Extensions.TestData From Version 7.0.0-beta.22422.1 -> To Version 7.0.0-beta.22451.1 * Update dependencies from https://github.com/dotnet/roslyn-analyzers build 20220901.2 Microsoft.CodeAnalysis.NetAnalyzers From Version 7.0.0-preview1.22419.4 -> To Version 7.0.0-preview1.22451.2 * Update dependencies from https://github.com/dotnet/hotreload-utils build 20220901.2 Microsoft.DotNet.HotReload.Utils.Generator.BuildTool From Version 1.1.0-alpha.0.22422.2 -> To Version 1.1.0-alpha.0.22451.2 * Update dependencies from https://github.com/dotnet/llvm-project build 20220901.2 runtime.linux-arm64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk , runtime.linux-arm64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools , runtime.linux-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk , runtime.linux-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools , runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk , runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools , runtime.win-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk , runtime.win-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools From Version 11.1.0-alpha.1.22425.1 -> To Version 11.1.0-alpha.1.22451.2 Co-authored-by: dotnet-maestro[bot] --- .config/dotnet-tools.json | 2 +- eng/Version.Details.xml | 160 +++++++++++++++++++------------------- eng/Versions.props | 78 +++++++++---------- global.json | 2 +- 4 files changed, 121 insertions(+), 121 deletions(-) diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 458b57e69da4ab..35ce79965cd3ed 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -15,7 +15,7 @@ ] }, "microsoft.dotnet.xharness.cli": { - "version": "1.0.0-prerelease.22422.1", + "version": "1.0.0-prerelease.22451.1", "commands": [ "xharness" ] diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 50e5a17cb5ff5b..91cae987e76b84 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,8 +1,8 @@ - + https://github.com/dotnet/icu - beb0f0f092f161eac2ef7b6322e5a397ddab96a7 + 6746a706f7bf80c43e672d26bc98d9f45fdfb651 https://github.com/dotnet/msquic @@ -16,37 +16,37 @@ https://github.com/dotnet/wcf 7f504aabb1988e9a093c1e74d8040bd52feb2f01 - + https://github.com/dotnet/llvm-project - e73d65f0f80655b463162bd41a8365377ba6565d + ce127716e4d7e310739a1cd8fbd45f3552a3a62b - + https://github.com/dotnet/llvm-project - e73d65f0f80655b463162bd41a8365377ba6565d + ce127716e4d7e310739a1cd8fbd45f3552a3a62b - + https://github.com/dotnet/llvm-project - e73d65f0f80655b463162bd41a8365377ba6565d + ce127716e4d7e310739a1cd8fbd45f3552a3a62b - + https://github.com/dotnet/llvm-project - e73d65f0f80655b463162bd41a8365377ba6565d + ce127716e4d7e310739a1cd8fbd45f3552a3a62b - + https://github.com/dotnet/llvm-project - e73d65f0f80655b463162bd41a8365377ba6565d + ce127716e4d7e310739a1cd8fbd45f3552a3a62b - + https://github.com/dotnet/llvm-project - e73d65f0f80655b463162bd41a8365377ba6565d + ce127716e4d7e310739a1cd8fbd45f3552a3a62b - + https://github.com/dotnet/llvm-project - e73d65f0f80655b463162bd41a8365377ba6565d + ce127716e4d7e310739a1cd8fbd45f3552a3a62b - + https://github.com/dotnet/llvm-project - e73d65f0f80655b463162bd41a8365377ba6565d + ce127716e4d7e310739a1cd8fbd45f3552a3a62b https://github.com/dotnet/command-line-api @@ -126,121 +126,121 @@ https://github.com/dotnet/arcade 258a37cd6a7884f771d0f991d9f24d29e292abd0 - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/llvm-project - 26987b5218f1a9fa7009cfee559ca631f63791b2 + 30887307035be29a93a01709ac9a33f7b82177e1 - + https://github.com/dotnet/llvm-project - 26987b5218f1a9fa7009cfee559ca631f63791b2 + 30887307035be29a93a01709ac9a33f7b82177e1 - + https://github.com/dotnet/llvm-project - 26987b5218f1a9fa7009cfee559ca631f63791b2 + 30887307035be29a93a01709ac9a33f7b82177e1 - + https://github.com/dotnet/llvm-project - 26987b5218f1a9fa7009cfee559ca631f63791b2 + 30887307035be29a93a01709ac9a33f7b82177e1 - + https://github.com/dotnet/llvm-project - 26987b5218f1a9fa7009cfee559ca631f63791b2 + 30887307035be29a93a01709ac9a33f7b82177e1 - + https://github.com/dotnet/llvm-project - 26987b5218f1a9fa7009cfee559ca631f63791b2 + 30887307035be29a93a01709ac9a33f7b82177e1 - + https://github.com/dotnet/llvm-project - 26987b5218f1a9fa7009cfee559ca631f63791b2 + 30887307035be29a93a01709ac9a33f7b82177e1 - + https://github.com/dotnet/llvm-project - 26987b5218f1a9fa7009cfee559ca631f63791b2 + 30887307035be29a93a01709ac9a33f7b82177e1 - + https://github.com/dotnet/runtime - f6166429381a4205207930d673c86a35da9ff40f + 48a3dbe5509f53f89db0a48c8285a2eec0758fea - + https://github.com/dotnet/runtime - f6166429381a4205207930d673c86a35da9ff40f + 48a3dbe5509f53f89db0a48c8285a2eec0758fea - + https://github.com/dotnet/runtime - f6166429381a4205207930d673c86a35da9ff40f + 48a3dbe5509f53f89db0a48c8285a2eec0758fea - + https://github.com/dotnet/runtime - f6166429381a4205207930d673c86a35da9ff40f + 48a3dbe5509f53f89db0a48c8285a2eec0758fea - + https://github.com/dotnet/runtime - f6166429381a4205207930d673c86a35da9ff40f + 48a3dbe5509f53f89db0a48c8285a2eec0758fea https://github.com/dotnet/linker b23be78205b79d60c1ea2cab5306f530a0faade2 - + https://github.com/dotnet/xharness - fbeb09787a4cdcf8a375382cf7a4f5edfaf1b9d7 + 919daad8a314e5b0e16f15db62352c367a306c85 - + https://github.com/dotnet/xharness - fbeb09787a4cdcf8a375382cf7a4f5edfaf1b9d7 + 919daad8a314e5b0e16f15db62352c367a306c85 - + https://github.com/dotnet/xharness - fbeb09787a4cdcf8a375382cf7a4f5edfaf1b9d7 + 919daad8a314e5b0e16f15db62352c367a306c85 https://github.com/dotnet/arcade @@ -262,17 +262,17 @@ https://dev.azure.com/dnceng/internal/_git/dotnet-optimization 45633fd5ebcbf81ffa26fb2348bdefbd8014cca3 - + https://github.com/dotnet/hotreload-utils - 2c67637067292f0cd16d4794ec688eefc8b1e8d6 + 0352ad5372767d455ab32dbd57b9ca5381abb9ad - + https://github.com/dotnet/runtime-assets - d31bcd3e4f8d4f49eff1ce9d9a1ea6d41182f903 + a2bc40b6bcd0c0262f01811b1e360c09c8a18fd5 - + https://github.com/dotnet/roslyn-analyzers - d80e535c08bf3eace650005ac2e7e061ed8692cd + 03344a064a80c1f66e50b67e3abe7335cb8ba072 https://github.com/dotnet/sdk diff --git a/eng/Versions.props b/eng/Versions.props index 3775e42248c8f3..01c6f4fd7c3134 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -44,7 +44,7 @@ 4.4.0-1.final 4.4.0-1.final 4.4.0-1.final - 7.0.0-preview1.22419.4 + 7.0.0-preview1.22451.2 4.4.0-1.final 6.0.0-preview.1.102 - 8.0.0-alpha.1.22421.15 + 8.0.0-alpha.1.22427.5 6.0.0 - 8.0.0-alpha.1.22421.15 - 1.0.0-alpha.1.22411.1 - 1.0.0-alpha.1.22411.1 - 1.0.0-alpha.1.22411.1 - 1.0.0-alpha.1.22411.1 - 1.0.0-alpha.1.22411.1 - 1.0.0-alpha.1.22411.1 - 1.0.0-alpha.1.22411.1 - 1.0.0-alpha.1.22411.1 + 8.0.0-alpha.1.22427.5 + 1.0.0-alpha.1.22431.4 + 1.0.0-alpha.1.22431.4 + 1.0.0-alpha.1.22431.4 + 1.0.0-alpha.1.22431.4 + 1.0.0-alpha.1.22431.4 + 1.0.0-alpha.1.22431.4 + 1.0.0-alpha.1.22431.4 + 1.0.0-alpha.1.22431.4 6.0.0 1.1.1 @@ -111,25 +111,25 @@ 5.0.0 5.0.0 4.9.0 - 8.0.0-alpha.1.22421.15 + 8.0.0-alpha.1.22427.5 6.0.0 4.5.4 4.5.0 - 8.0.0-alpha.1.22421.15 + 8.0.0-alpha.1.22427.5 - 7.0.0-beta.22422.1 - 7.0.0-beta.22422.1 - 7.0.0-beta.22422.1 - 7.0.0-beta.22422.1 - 7.0.0-beta.22422.1 - 7.0.0-beta.22422.1 - 7.0.0-beta.22422.1 - 7.0.0-beta.22422.1 - 7.0.0-beta.22422.1 - 7.0.0-beta.22422.1 - 7.0.0-beta.22422.1 - 7.0.0-beta.22422.1 - 7.0.0-beta.22422.1 + 7.0.0-beta.22451.1 + 7.0.0-beta.22451.1 + 7.0.0-beta.22451.1 + 7.0.0-beta.22451.1 + 7.0.0-beta.22451.1 + 7.0.0-beta.22451.1 + 7.0.0-beta.22451.1 + 7.0.0-beta.22451.1 + 7.0.0-beta.22451.1 + 7.0.0-beta.22451.1 + 7.0.0-beta.22451.1 + 7.0.0-beta.22451.1 + 7.0.0-beta.22451.1 1.0.0-prerelease.22415.6 1.0.0-prerelease.22415.6 @@ -152,10 +152,10 @@ 1.1.0 17.4.0-preview-20220707-01 - 1.0.0-prerelease.22422.1 - 1.0.0-prerelease.22422.1 - 1.0.0-prerelease.22422.1 - 1.1.0-alpha.0.22422.2 + 1.0.0-prerelease.22451.1 + 1.0.0-prerelease.22451.1 + 1.0.0-prerelease.22451.1 + 1.1.0-alpha.0.22451.2 2.4.2 1.0.0 2.4.5 @@ -182,19 +182,19 @@ 7.0.100-1.22425.2 $(MicrosoftNETILLinkTasksVersion) - 8.0.0-alpha.1.22422.1 + 8.0.0-alpha.1.22451.5 2.1 7.0.0-alpha.1.22406.1 - 11.1.0-alpha.1.22425.1 - 11.1.0-alpha.1.22425.1 - 11.1.0-alpha.1.22425.1 - 11.1.0-alpha.1.22425.1 - 11.1.0-alpha.1.22425.1 - 11.1.0-alpha.1.22425.1 - 11.1.0-alpha.1.22425.1 - 11.1.0-alpha.1.22425.1 + 11.1.0-alpha.1.22451.2 + 11.1.0-alpha.1.22451.2 + 11.1.0-alpha.1.22451.2 + 11.1.0-alpha.1.22451.2 + 11.1.0-alpha.1.22451.2 + 11.1.0-alpha.1.22451.2 + 11.1.0-alpha.1.22451.2 + 11.1.0-alpha.1.22451.2 8.0.0-alpha.1.22417.1 $(MicrosoftNETWorkloadEmscriptenManifest70100Version) diff --git a/global.json b/global.json index cb2f93120d3d8d..99d901afa7a1eb 100644 --- a/global.json +++ b/global.json @@ -13,6 +13,6 @@ "Microsoft.DotNet.SharedFramework.Sdk": "7.0.0-beta.22424.3", "Microsoft.Build.NoTargets": "3.5.0", "Microsoft.Build.Traversal": "3.1.6", - "Microsoft.NET.Sdk.IL": "8.0.0-alpha.1.22421.15" + "Microsoft.NET.Sdk.IL": "8.0.0-alpha.1.22427.5" } } From f9fb8ed9c9530cd3a65e79249c4d2e1fd73c0700 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 2 Sep 2022 19:28:27 +0200 Subject: [PATCH 093/107] [main] Update dependencies from dotnet/arcade (#74646) * Update dependencies from https://github.com/dotnet/arcade build 20220825.1 Microsoft.DotNet.ApiCompat , Microsoft.DotNet.Arcade.Sdk , Microsoft.DotNet.Build.Tasks.Archives , Microsoft.DotNet.Build.Tasks.Feed , Microsoft.DotNet.Build.Tasks.Installers , Microsoft.DotNet.Build.Tasks.Packaging , Microsoft.DotNet.Build.Tasks.TargetFramework , Microsoft.DotNet.Build.Tasks.Templating , Microsoft.DotNet.Build.Tasks.Workloads , Microsoft.DotNet.CodeAnalysis , Microsoft.DotNet.GenAPI , Microsoft.DotNet.GenFacades , Microsoft.DotNet.Helix.Sdk , Microsoft.DotNet.PackageTesting , Microsoft.DotNet.RemoteExecutor , Microsoft.DotNet.SharedFramework.Sdk , Microsoft.DotNet.VersionTools.Tasks , Microsoft.DotNet.XUnitConsoleRunner , Microsoft.DotNet.XUnitExtensions From Version 7.0.0-beta.22424.3 -> To Version 7.0.0-beta.22425.1 * Update dependencies from https://github.com/dotnet/arcade build 20220826.1 Microsoft.DotNet.ApiCompat , Microsoft.DotNet.Arcade.Sdk , Microsoft.DotNet.Build.Tasks.Archives , Microsoft.DotNet.Build.Tasks.Feed , Microsoft.DotNet.Build.Tasks.Installers , Microsoft.DotNet.Build.Tasks.Packaging , Microsoft.DotNet.Build.Tasks.TargetFramework , Microsoft.DotNet.Build.Tasks.Templating , Microsoft.DotNet.Build.Tasks.Workloads , Microsoft.DotNet.CodeAnalysis , Microsoft.DotNet.GenAPI , Microsoft.DotNet.GenFacades , Microsoft.DotNet.Helix.Sdk , Microsoft.DotNet.PackageTesting , Microsoft.DotNet.RemoteExecutor , Microsoft.DotNet.SharedFramework.Sdk , Microsoft.DotNet.VersionTools.Tasks , Microsoft.DotNet.XUnitConsoleRunner , Microsoft.DotNet.XUnitExtensions From Version 7.0.0-beta.22424.3 -> To Version 7.0.0-beta.22426.1 * Update dependencies from https://github.com/dotnet/arcade build 20220826.8 Microsoft.DotNet.ApiCompat , Microsoft.DotNet.Arcade.Sdk , Microsoft.DotNet.Build.Tasks.Archives , Microsoft.DotNet.Build.Tasks.Feed , Microsoft.DotNet.Build.Tasks.Installers , Microsoft.DotNet.Build.Tasks.Packaging , Microsoft.DotNet.Build.Tasks.TargetFramework , Microsoft.DotNet.Build.Tasks.Templating , Microsoft.DotNet.Build.Tasks.Workloads , Microsoft.DotNet.CodeAnalysis , Microsoft.DotNet.GenAPI , Microsoft.DotNet.GenFacades , Microsoft.DotNet.Helix.Sdk , Microsoft.DotNet.PackageTesting , Microsoft.DotNet.RemoteExecutor , Microsoft.DotNet.SharedFramework.Sdk , Microsoft.DotNet.VersionTools.Tasks , Microsoft.DotNet.XUnitConsoleRunner , Microsoft.DotNet.XUnitExtensions From Version 7.0.0-beta.22424.3 -> To Version 7.0.0-beta.22426.8 * Update dependencies from https://github.com/dotnet/arcade build 20220830.3 Microsoft.DotNet.ApiCompat , Microsoft.DotNet.Arcade.Sdk , Microsoft.DotNet.Build.Tasks.Archives , Microsoft.DotNet.Build.Tasks.Feed , Microsoft.DotNet.Build.Tasks.Installers , Microsoft.DotNet.Build.Tasks.Packaging , Microsoft.DotNet.Build.Tasks.TargetFramework , Microsoft.DotNet.Build.Tasks.Templating , Microsoft.DotNet.Build.Tasks.Workloads , Microsoft.DotNet.CodeAnalysis , Microsoft.DotNet.GenAPI , Microsoft.DotNet.GenFacades , Microsoft.DotNet.Helix.Sdk , Microsoft.DotNet.PackageTesting , Microsoft.DotNet.RemoteExecutor , Microsoft.DotNet.SharedFramework.Sdk , Microsoft.DotNet.VersionTools.Tasks , Microsoft.DotNet.XUnitConsoleRunner , Microsoft.DotNet.XUnitExtensions From Version 7.0.0-beta.22424.3 -> To Version 8.0.0-beta.22430.3 * Update dependencies from https://github.com/dotnet/arcade build 20220831.1 Microsoft.DotNet.ApiCompat , Microsoft.DotNet.Arcade.Sdk , Microsoft.DotNet.Build.Tasks.Archives , Microsoft.DotNet.Build.Tasks.Feed , Microsoft.DotNet.Build.Tasks.Installers , Microsoft.DotNet.Build.Tasks.Packaging , Microsoft.DotNet.Build.Tasks.TargetFramework , Microsoft.DotNet.Build.Tasks.Templating , Microsoft.DotNet.Build.Tasks.Workloads , Microsoft.DotNet.CodeAnalysis , Microsoft.DotNet.GenAPI , Microsoft.DotNet.GenFacades , Microsoft.DotNet.Helix.Sdk , Microsoft.DotNet.PackageTesting , Microsoft.DotNet.RemoteExecutor , Microsoft.DotNet.SharedFramework.Sdk , Microsoft.DotNet.VersionTools.Tasks , Microsoft.DotNet.XUnitConsoleRunner , Microsoft.DotNet.XUnitExtensions From Version 7.0.0-beta.22424.3 -> To Version 8.0.0-beta.22431.1 * Update dependencies from https://github.com/dotnet/arcade build 20220902.1 Microsoft.DotNet.ApiCompat , Microsoft.DotNet.Arcade.Sdk , Microsoft.DotNet.Build.Tasks.Archives , Microsoft.DotNet.Build.Tasks.Feed , Microsoft.DotNet.Build.Tasks.Installers , Microsoft.DotNet.Build.Tasks.Packaging , Microsoft.DotNet.Build.Tasks.TargetFramework , Microsoft.DotNet.Build.Tasks.Templating , Microsoft.DotNet.Build.Tasks.Workloads , Microsoft.DotNet.CodeAnalysis , Microsoft.DotNet.GenAPI , Microsoft.DotNet.GenFacades , Microsoft.DotNet.Helix.Sdk , Microsoft.DotNet.PackageTesting , Microsoft.DotNet.RemoteExecutor , Microsoft.DotNet.SharedFramework.Sdk , Microsoft.DotNet.VersionTools.Tasks , Microsoft.DotNet.XUnitConsoleRunner , Microsoft.DotNet.XUnitExtensions From Version 7.0.0-beta.22424.3 -> To Version 8.0.0-beta.22452.1 Co-authored-by: dotnet-maestro[bot] --- eng/Version.Details.xml | 76 +++++++++++------------ eng/Versions.props | 32 +++++----- eng/common/cross/arm/sources.list.focal | 11 ++++ eng/common/cross/arm/sources.list.jammy | 11 ++++ eng/common/cross/arm64/sources.list.focal | 11 ++++ eng/common/cross/arm64/sources.list.jammy | 11 ++++ eng/common/cross/build-rootfs.sh | 41 ++++++------ eng/common/cross/x86/sources.list.focal | 11 ++++ eng/common/cross/x86/sources.list.jammy | 11 ++++ global.json | 6 +- 10 files changed, 146 insertions(+), 75 deletions(-) create mode 100644 eng/common/cross/arm/sources.list.focal create mode 100644 eng/common/cross/arm/sources.list.jammy create mode 100644 eng/common/cross/arm64/sources.list.focal create mode 100644 eng/common/cross/arm64/sources.list.jammy create mode 100644 eng/common/cross/x86/sources.list.focal create mode 100644 eng/common/cross/x86/sources.list.jammy diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 91cae987e76b84..0176f725cf00e3 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -54,77 +54,77 @@ - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 https://github.com/dotnet/runtime-assets @@ -242,9 +242,9 @@ https://github.com/dotnet/xharness 919daad8a314e5b0e16f15db62352c367a306c85 - + https://github.com/dotnet/arcade - 258a37cd6a7884f771d0f991d9f24d29e292abd0 + 87531ff8de2e6501ff85973c9af44953a2c5b687 https://dev.azure.com/dnceng/internal/_git/dotnet-optimization diff --git a/eng/Versions.props b/eng/Versions.props index 01c6f4fd7c3134..d3aaf37ff60c05 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -54,22 +54,22 @@ 7.0.100-rc.1.22402.1 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 - 2.5.1-beta.22424.3 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 - 7.0.0-beta.22424.3 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 + 2.5.1-beta.22452.1 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 + 8.0.0-beta.22452.1 6.0.0-preview.1.102 diff --git a/eng/common/cross/arm/sources.list.focal b/eng/common/cross/arm/sources.list.focal new file mode 100644 index 00000000000000..4de2600c17478c --- /dev/null +++ b/eng/common/cross/arm/sources.list.focal @@ -0,0 +1,11 @@ +deb http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe +deb-src http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe + +deb http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe +deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe + +deb http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted +deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted + +deb http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse +deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse diff --git a/eng/common/cross/arm/sources.list.jammy b/eng/common/cross/arm/sources.list.jammy new file mode 100644 index 00000000000000..6bb0453029cc47 --- /dev/null +++ b/eng/common/cross/arm/sources.list.jammy @@ -0,0 +1,11 @@ +deb http://ports.ubuntu.com/ubuntu-ports/ jammy main restricted universe +deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy main restricted universe + +deb http://ports.ubuntu.com/ubuntu-ports/ jammy-updates main restricted universe +deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-updates main restricted universe + +deb http://ports.ubuntu.com/ubuntu-ports/ jammy-backports main restricted +deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-backports main restricted + +deb http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse +deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse diff --git a/eng/common/cross/arm64/sources.list.focal b/eng/common/cross/arm64/sources.list.focal new file mode 100644 index 00000000000000..4de2600c17478c --- /dev/null +++ b/eng/common/cross/arm64/sources.list.focal @@ -0,0 +1,11 @@ +deb http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe +deb-src http://ports.ubuntu.com/ubuntu-ports/ focal main restricted universe + +deb http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe +deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-updates main restricted universe + +deb http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted +deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-backports main restricted + +deb http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse +deb-src http://ports.ubuntu.com/ubuntu-ports/ focal-security main restricted universe multiverse diff --git a/eng/common/cross/arm64/sources.list.jammy b/eng/common/cross/arm64/sources.list.jammy new file mode 100644 index 00000000000000..6bb0453029cc47 --- /dev/null +++ b/eng/common/cross/arm64/sources.list.jammy @@ -0,0 +1,11 @@ +deb http://ports.ubuntu.com/ubuntu-ports/ jammy main restricted universe +deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy main restricted universe + +deb http://ports.ubuntu.com/ubuntu-ports/ jammy-updates main restricted universe +deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-updates main restricted universe + +deb http://ports.ubuntu.com/ubuntu-ports/ jammy-backports main restricted +deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-backports main restricted + +deb http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse +deb-src http://ports.ubuntu.com/ubuntu-ports/ jammy-security main restricted universe multiverse diff --git a/eng/common/cross/build-rootfs.sh b/eng/common/cross/build-rootfs.sh index 032f5f193732a1..5680980fa296e3 100755 --- a/eng/common/cross/build-rootfs.sh +++ b/eng/common/cross/build-rootfs.sh @@ -186,32 +186,27 @@ while :; do __UbuntuArch=i386 __UbuntuRepo="http://archive.ubuntu.com/ubuntu/" ;; - lldb3.6) - __LLDB_Package="lldb-3.6-dev" - ;; - lldb3.8) - __LLDB_Package="lldb-3.8-dev" - ;; - lldb3.9) - __LLDB_Package="liblldb-3.9-dev" - ;; - lldb4.0) - __LLDB_Package="liblldb-4.0-dev" - ;; - lldb5.0) - __LLDB_Package="liblldb-5.0-dev" - ;; - lldb6.0) - __LLDB_Package="liblldb-6.0-dev" + lldb*) + version="${lowerI/lldb/}" + parts=(${version//./ }) + + # for versions > 6.0, lldb has dropped the minor version + if [[ "${parts[0]}" -gt 6 ]]; then + version="${parts[0]}" + fi + + __LLDB_Package="liblldb-${version}-dev" ;; no-lldb) unset __LLDB_Package ;; llvm*) - version="$(echo "$lowerI" | tr -d '[:alpha:]-=')" + version="${lowerI/llvm/}" parts=(${version//./ }) __LLVM_MajorVersion="${parts[0]}" __LLVM_MinorVersion="${parts[1]}" + + # for versions > 6.0, llvm has dropped the minor version if [[ -z "$__LLVM_MinorVersion" && "$__LLVM_MajorVersion" -le 6 ]]; then __LLVM_MinorVersion=0; fi @@ -231,6 +226,16 @@ while :; do __CodeName=bionic fi ;; + focal) # Ubuntu 20.04 + if [[ "$__CodeName" != "jessie" ]]; then + __CodeName=focal + fi + ;; + jammy) # Ubuntu 22.04 + if [[ "$__CodeName" != "jessie" ]]; then + __CodeName=jammy + fi + ;; jessie) # Debian 8 __CodeName=jessie __UbuntuRepo="http://ftp.debian.org/debian/" diff --git a/eng/common/cross/x86/sources.list.focal b/eng/common/cross/x86/sources.list.focal new file mode 100644 index 00000000000000..99d5731330e79d --- /dev/null +++ b/eng/common/cross/x86/sources.list.focal @@ -0,0 +1,11 @@ +deb http://archive.ubuntu.com/ubuntu/ focal main restricted universe +deb-src http://archive.ubuntu.com/ubuntu/ focal main restricted universe + +deb http://archive.ubuntu.com/ubuntu/ focal-updates main restricted universe +deb-src http://archive.ubuntu.com/ubuntu/ focal-updates main restricted universe + +deb http://archive.ubuntu.com/ubuntu/ focal-backports main restricted +deb-src http://archive.ubuntu.com/ubuntu/ focal-backports main restricted + +deb http://archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse +deb-src http://archive.ubuntu.com/ubuntu/ focal-security main restricted universe multiverse diff --git a/eng/common/cross/x86/sources.list.jammy b/eng/common/cross/x86/sources.list.jammy new file mode 100644 index 00000000000000..af1c1feaeac1bd --- /dev/null +++ b/eng/common/cross/x86/sources.list.jammy @@ -0,0 +1,11 @@ +deb http://archive.ubuntu.com/ubuntu/ jammy main restricted universe +deb-src http://archive.ubuntu.com/ubuntu/ jammy main restricted universe + +deb http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted universe +deb-src http://archive.ubuntu.com/ubuntu/ jammy-updates main restricted universe + +deb http://archive.ubuntu.com/ubuntu/ jammy-backports main restricted +deb-src http://archive.ubuntu.com/ubuntu/ jammy-backports main restricted + +deb http://archive.ubuntu.com/ubuntu/ jammy-security main restricted universe multiverse +deb-src http://archive.ubuntu.com/ubuntu/ jammy-security main restricted universe multiverse diff --git a/global.json b/global.json index 99d901afa7a1eb..45e4d8c7394722 100644 --- a/global.json +++ b/global.json @@ -8,9 +8,9 @@ "dotnet": "7.0.100-preview.7.22377.5" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "7.0.0-beta.22424.3", - "Microsoft.DotNet.Helix.Sdk": "7.0.0-beta.22424.3", - "Microsoft.DotNet.SharedFramework.Sdk": "7.0.0-beta.22424.3", + "Microsoft.DotNet.Arcade.Sdk": "8.0.0-beta.22452.1", + "Microsoft.DotNet.Helix.Sdk": "8.0.0-beta.22452.1", + "Microsoft.DotNet.SharedFramework.Sdk": "8.0.0-beta.22452.1", "Microsoft.Build.NoTargets": "3.5.0", "Microsoft.Build.Traversal": "3.1.6", "Microsoft.NET.Sdk.IL": "8.0.0-alpha.1.22427.5" From 941ec70ad37943762a18b2d1a4c45eb8e914cb4f Mon Sep 17 00:00:00 2001 From: Will Smith Date: Fri, 2 Sep 2022 10:44:52 -0700 Subject: [PATCH 094/107] [ARM64] - `IsValidCompareChain` should return `false` if both operands are not integral types (#74853) * IsValidCompareChain should return 'false' if both operands are not integral types * Add integral type checks in ContainCheckCompareChain * Check if op is CMP or AND * feedback --- src/coreclr/jit/lowerarmarch.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/coreclr/jit/lowerarmarch.cpp b/src/coreclr/jit/lowerarmarch.cpp index 9cab1d427ad1f2..76cba89ae81eaa 100644 --- a/src/coreclr/jit/lowerarmarch.cpp +++ b/src/coreclr/jit/lowerarmarch.cpp @@ -2141,7 +2141,8 @@ bool Lowering::IsValidCompareChain(GenTree* child, GenTree* parent) return IsValidCompareChain(child->AsOp()->gtGetOp2(), child) && IsValidCompareChain(child->AsOp()->gtGetOp1(), child); } - else if (child->OperIsCmpCompare()) + else if (child->OperIsCmpCompare() && varTypeIsIntegral(child->gtGetOp1()) && + varTypeIsIntegral(child->gtGetOp2())) { // Can the child compare be contained. return IsSafeToContainMem(parent, child); @@ -2203,7 +2204,8 @@ bool Lowering::ContainCheckCompareChain(GenTree* child, GenTree* parent, GenTree child->SetContained(); return true; } - else if (child->OperIsCmpCompare()) + else if (child->OperIsCmpCompare() && varTypeIsIntegral(child->gtGetOp1()) && + varTypeIsIntegral(child->gtGetOp2())) { child->AsOp()->SetContained(); From 9ea5d2d6cdc536fbe1dacc477ef2b2dea2b4845c Mon Sep 17 00:00:00 2001 From: Miha Zupan Date: Fri, 2 Sep 2022 21:05:45 +0200 Subject: [PATCH 095/107] Throw on incompatible WebSocket options (#74473) * Throw on incompatible WebSocket options * Don't set ServerCertificateCustomValidationCallback on Browser * Update exception messages * Skip new H2 test on Browser --- .../src/Resources/Strings.resx | 6 + .../Net/WebSockets/ClientWebSocketOptions.cs | 8 + .../Net/WebSockets/WebSocketHandle.Managed.cs | 26 ++- .../tests/AbortTest.cs | 4 +- .../tests/CancelTest.cs | 4 +- .../tests/ClientWebSocketTestBase.cs | 39 +++- .../tests/CloseTest.cs | 4 +- .../tests/ConnectTest.Http2.cs | 171 ++++++++++-------- .../tests/ConnectTest.cs | 80 +++++++- .../tests/DeflateTests.cs | 4 +- .../tests/SendReceiveTest.Http2.cs | 49 +++-- .../tests/SendReceiveTest.cs | 8 +- 12 files changed, 268 insertions(+), 135 deletions(-) diff --git a/src/libraries/System.Net.WebSockets.Client/src/Resources/Strings.resx b/src/libraries/System.Net.WebSockets.Client/src/Resources/Strings.resx index 401be8dc707616..e3d5079aafc0bc 100644 --- a/src/libraries/System.Net.WebSockets.Client/src/Resources/Strings.resx +++ b/src/libraries/System.Net.WebSockets.Client/src/Resources/Strings.resx @@ -129,4 +129,10 @@ The WebSocket failed to negotiate max client window bits. The client requested {0} but the server responded with {1}. + + UseDefaultCredentials, Credentials, Proxy, ClientCertificates, RemoteCertificateValidationCallback and Cookies must not be set on ClientWebSocketOptions when an HttpMessageInvoker instance is also specified. These options should be set on the HttpMessageInvoker's underlying HttpMessageHandler instead. + + + An HttpMessageInvoker instance must be passed to ConnectAsync when using HTTP/2. + diff --git a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocketOptions.cs b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocketOptions.cs index 6a8de0a712f581..c4069223db053f 100644 --- a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocketOptions.cs +++ b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocketOptions.cs @@ -30,6 +30,14 @@ public sealed class ClientWebSocketOptions private HttpVersionPolicy _versionPolicy = HttpVersionPolicy.RequestVersionOrLower; private bool _collectHttpResponseDetails; + internal bool AreCompatibleWithCustomInvoker() => + !UseDefaultCredentials && + Credentials is null && + (_clientCertificates?.Count ?? 0) == 0 && + RemoteCertificateValidationCallback is null && + Cookies is null && + (Proxy is null || Proxy == WebSocketHandle.DefaultWebProxy.Instance); + internal ClientWebSocketOptions() { } // prevent external instantiation #region HTTP Settings diff --git a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs index 6bb365012ef779..e27661ea29efff 100644 --- a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs +++ b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs @@ -48,9 +48,22 @@ public void Abort() public async Task ConnectAsync(Uri uri, HttpMessageInvoker? invoker, CancellationToken cancellationToken, ClientWebSocketOptions options) { bool disposeHandler = false; - invoker ??= new HttpMessageInvoker(SetupHandler(options, out disposeHandler)); - HttpResponseMessage? response = null; + if (invoker is null) + { + if (options.HttpVersion.Major >= 2 || options.HttpVersionPolicy == HttpVersionPolicy.RequestVersionOrHigher) + { + throw new ArgumentException(SR.net_WebSockets_CustomInvokerRequiredForHttp2, nameof(options)); + } + invoker = new HttpMessageInvoker(SetupHandler(options, out disposeHandler)); + } + else if (!options.AreCompatibleWithCustomInvoker()) + { + // This will not throw if the Proxy is a DefaultWebProxy. + throw new ArgumentException(SR.net_WebSockets_OptionsIncompatibleWithCustomInvoker, nameof(options)); + } + + HttpResponseMessage? response = null; bool disposeResponse = false; // force non-secure request to 1.1 whenever it is possible as HttpClient does @@ -237,12 +250,7 @@ private static SocketsHttpHandler SetupHandler(ClientWebSocketOptions options, o // Create the handler for this request and populate it with all of the options. // Try to use a shared handler rather than creating a new one just for this request, if // the options are compatible. - if (options.Credentials == null && - !options.UseDefaultCredentials && - options.Proxy == null && - options.Cookies == null && - options.RemoteCertificateValidationCallback == null && - (options._clientCertificates?.Count ?? 0) == 0) + if (options.AreCompatibleWithCustomInvoker() && options.Proxy is null) { disposeHandler = false; handler = s_defaultHandler; @@ -518,7 +526,7 @@ private static void ValidateHeader(HttpHeaders headers, string name, string expe } /// Used as a sentinel to indicate that ClientWebSocket should use the system's default proxy. - private sealed class DefaultWebProxy : IWebProxy + internal sealed class DefaultWebProxy : IWebProxy { public static DefaultWebProxy Instance { get; } = new DefaultWebProxy(); public ICredentials? Credentials { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } diff --git a/src/libraries/System.Net.WebSockets.Client/tests/AbortTest.cs b/src/libraries/System.Net.WebSockets.Client/tests/AbortTest.cs index 70cb6317f36635..d81baa53e4639b 100644 --- a/src/libraries/System.Net.WebSockets.Client/tests/AbortTest.cs +++ b/src/libraries/System.Net.WebSockets.Client/tests/AbortTest.cs @@ -16,14 +16,14 @@ public sealed class InvokerAbortTest : AbortTest { public InvokerAbortTest(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpMessageInvoker(new SocketsHttpHandler()); + protected override bool UseCustomInvoker => true; } public sealed class HttpClientAbortTest : AbortTest { public HttpClientAbortTest(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpClient(new HttpClientHandler()); + protected override bool UseHttpClient => true; } public class AbortTest : ClientWebSocketTestBase diff --git a/src/libraries/System.Net.WebSockets.Client/tests/CancelTest.cs b/src/libraries/System.Net.WebSockets.Client/tests/CancelTest.cs index 5919f63157d705..534f62cca17d51 100644 --- a/src/libraries/System.Net.WebSockets.Client/tests/CancelTest.cs +++ b/src/libraries/System.Net.WebSockets.Client/tests/CancelTest.cs @@ -14,14 +14,14 @@ public sealed class InvokerCancelTest : CancelTest { public InvokerCancelTest(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpMessageInvoker(new SocketsHttpHandler()); + protected override bool UseCustomInvoker => true; } public sealed class HttpClientCancelTest : CancelTest { public HttpClientCancelTest(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpClient(new HttpClientHandler()); + protected override bool UseHttpClient => true; } public class CancelTest : ClientWebSocketTestBase diff --git a/src/libraries/System.Net.WebSockets.Client/tests/ClientWebSocketTestBase.cs b/src/libraries/System.Net.WebSockets.Client/tests/ClientWebSocketTestBase.cs index a32587bc862fc9..0c8b94778a58ea 100644 --- a/src/libraries/System.Net.WebSockets.Client/tests/ClientWebSocketTestBase.cs +++ b/src/libraries/System.Net.WebSockets.Client/tests/ClientWebSocketTestBase.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; -using System.Net.Test.Common; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -10,13 +9,10 @@ using Xunit; using Xunit.Abstractions; using System.Net.Http; -using System.Net.WebSockets.Client.Tests; +using System.Diagnostics; namespace System.Net.WebSockets.Client.Tests { - /// - /// ClientWebSocket tests that do require a remote server. - /// public class ClientWebSocketTestBase { public static readonly object[][] EchoServers = System.Net.Test.Common.Configuration.WebSockets.EchoServers; @@ -112,7 +108,38 @@ protected static async Task ReceiveEntireMessageAsync(We } } - protected virtual HttpMessageInvoker? GetInvoker() => null; + protected virtual bool UseCustomInvoker => false; + + protected virtual bool UseHttpClient => false; + + protected bool UseSharedHandler => !UseCustomInvoker && !UseHttpClient; + + protected Action? ConfigureCustomHandler; + + internal HttpMessageInvoker? GetInvoker() + { + var handler = new HttpClientHandler(); + + if (PlatformDetection.IsNotBrowser) + { + handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; + } + + ConfigureCustomHandler?.Invoke(handler); + + if (UseCustomInvoker) + { + Debug.Assert(!UseHttpClient); + return new HttpMessageInvoker(handler); + } + + if (UseHttpClient) + { + return new HttpClient(handler); + } + + return null; + } protected Task GetConnectedWebSocket(Uri uri, int TimeOutMilliseconds, ITestOutputHelper output) => WebSocketHelper.GetConnectedWebSocket(uri, TimeOutMilliseconds, output, invoker: GetInvoker()); diff --git a/src/libraries/System.Net.WebSockets.Client/tests/CloseTest.cs b/src/libraries/System.Net.WebSockets.Client/tests/CloseTest.cs index c09df107c8538c..9034b38bd43f46 100644 --- a/src/libraries/System.Net.WebSockets.Client/tests/CloseTest.cs +++ b/src/libraries/System.Net.WebSockets.Client/tests/CloseTest.cs @@ -18,14 +18,14 @@ public sealed class InvokerCloseTest : CloseTest { public InvokerCloseTest(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpMessageInvoker(new SocketsHttpHandler()); + protected override bool UseCustomInvoker => true; } public sealed class HttpClientCloseTest : CloseTest { public HttpClientCloseTest(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpClient(new HttpClientHandler()); + protected override bool UseHttpClient => true; } public class CloseTest : ClientWebSocketTestBase diff --git a/src/libraries/System.Net.WebSockets.Client/tests/ConnectTest.Http2.cs b/src/libraries/System.Net.WebSockets.Client/tests/ConnectTest.Http2.cs index 1ec2f1ee39fa45..bdbbcb75222fa5 100644 --- a/src/libraries/System.Net.WebSockets.Client/tests/ConnectTest.Http2.cs +++ b/src/libraries/System.Net.WebSockets.Client/tests/ConnectTest.Http2.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; -using System.IO; using System.Net.Http; using System.Net.Test.Common; using System.Threading; @@ -11,34 +10,59 @@ using Xunit; using Xunit.Abstractions; -using static System.Net.Http.Functional.Tests.TestHelper; - namespace System.Net.WebSockets.Client.Tests { public sealed class InvokerConnectTest_Http2 : ConnectTest_Http2 { public InvokerConnectTest_Http2(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpClient(new HttpClientHandler()); + protected override bool UseCustomInvoker => true; } public sealed class HttpClientConnectTest_Http2 : ConnectTest_Http2 { public HttpClientConnectTest_Http2(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpClient(new HttpClientHandler()); + protected override bool UseHttpClient => true; } - public class ConnectTest_Http2 : ClientWebSocketTestBase + public sealed class HttpClientConnectTest_Http2_NoInvoker : ClientWebSocketTestBase { - public ConnectTest_Http2(ITestOutputHelper output) : base(output) { } + public HttpClientConnectTest_Http2_NoInvoker(ITestOutputHelper output) : base(output) { } + + public static IEnumerable ConnectAsync_Http2WithNoInvoker_ThrowsArgumentException_MemberData() + { + yield return Options(options => options.HttpVersion = HttpVersion.Version20); + yield return Options(options => options.HttpVersion = HttpVersion.Version30); + yield return Options(options => options.HttpVersion = new Version(2, 1)); + yield return Options(options => options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher); + static object[] Options(Action configureOptions) => + new object[] { configureOptions }; + } [Theory] - [InlineData(false)] - [InlineData(true)] + [MemberData(nameof(ConnectAsync_Http2WithNoInvoker_ThrowsArgumentException_MemberData))] + [SkipOnPlatform(TestPlatforms.Browser, "HTTP/2 WebSockets aren't supported on Browser")] + public async Task ConnectAsync_Http2WithNoInvoker_ThrowsArgumentException(Action configureOptions) + { + using var ws = new ClientWebSocket(); + configureOptions(ws.Options); + + Task connectTask = ws.ConnectAsync(new Uri("wss://dummy"), CancellationToken.None); + + Assert.Equal(TaskStatus.Faulted, connectTask.Status); + await Assert.ThrowsAsync("options", () => connectTask); + } + } + + public abstract class ConnectTest_Http2 : ClientWebSocketTestBase + { + public ConnectTest_Http2(ITestOutputHelper output) : base(output) { } + + [Fact] [SkipOnPlatform(TestPlatforms.Browser, "System.Net.Sockets is not supported on this platform")] - public async Task ConnectAsync_VersionNotSupported_NoSsl_Throws(bool useHandler) + public async Task ConnectAsync_VersionNotSupported_NoSsl_Throws() { await Http2LoopbackServer.CreateClientAndServerAsync(async uri => { @@ -46,17 +70,10 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async uri => using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { cws.Options.HttpVersion = HttpVersion.Version20; - cws.Options.HttpVersionPolicy = Http.HttpVersionPolicy.RequestVersionExact; - Task t; - if (useHandler) - { - var handler = new SocketsHttpHandler(); - t = cws.ConnectAsync(uri, new HttpMessageInvoker(handler), cts.Token); - } - else - { - t = cws.ConnectAsync(uri, cts.Token); - } + cws.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact; + + Task t = cws.ConnectAsync(uri, GetInvoker(), cts.Token); + var ex = await Assert.ThrowsAnyAsync(() => t); Assert.IsType(ex.InnerException); Assert.True(ex.InnerException.Data.Contains("SETTINGS_ENABLE_CONNECT_PROTOCOL")); @@ -65,8 +82,7 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async uri => async server => { Http2LoopbackConnection connection = await server.EstablishConnectionAsync(new SettingsEntry { SettingId = SettingId.EnableConnect, Value = 0 }); - }, new Http2Options() { WebSocketEndpoint = true, UseSsl = false } - ); + }, new Http2Options() { WebSocketEndpoint = true, UseSsl = false }); } [Fact] @@ -79,10 +95,9 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async uri => using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { cws.Options.HttpVersion = HttpVersion.Version20; - cws.Options.HttpVersionPolicy = Http.HttpVersionPolicy.RequestVersionExact; - Task t; - var handler = CreateSocketsHttpHandler(allowAllCertificates: true); - t = cws.ConnectAsync(uri, new HttpMessageInvoker(handler), cts.Token); + cws.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact; + + Task t = cws.ConnectAsync(uri, GetInvoker(), cts.Token); var ex = await Assert.ThrowsAnyAsync(() => t); Assert.IsType(ex.InnerException); @@ -92,31 +107,22 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async uri => async server => { Http2LoopbackConnection connection = await server.EstablishConnectionAsync(new SettingsEntry { SettingId = SettingId.EnableConnect, Value = 0 }); - }, new Http2Options() { WebSocketEndpoint = true } - ); + }, new Http2Options() { WebSocketEndpoint = true }); } [OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))] - [Theory] - [MemberData(nameof(SecureEchoServersAndBoolean))] + [Fact] [SkipOnPlatform(TestPlatforms.Browser, "System.Net.Sockets is not supported on this platform")] - public async Task ConnectAsync_Http11Server_DowngradeFail(Uri server, bool useHandler) + public async Task ConnectAsync_Http11Server_DowngradeFail() { using (var cws = new ClientWebSocket()) using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { cws.Options.HttpVersion = HttpVersion.Version20; - cws.Options.HttpVersionPolicy = Http.HttpVersionPolicy.RequestVersionExact; - Task t; - if (useHandler) - { - var handler = new SocketsHttpHandler(); - t = cws.ConnectAsync(server, new HttpMessageInvoker(handler), cts.Token); - } - else - { - t = cws.ConnectAsync(server, cts.Token); - } + cws.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact; + + Task t = cws.ConnectAsync(Test.Common.Configuration.WebSockets.SecureRemoteEchoServer, GetInvoker(), cts.Token); + var ex = await Assert.ThrowsAnyAsync(() => t); Assert.IsType(ex.InnerException); Assert.True(ex.InnerException.Data.Contains("HTTP2_ENABLED")); @@ -126,34 +132,23 @@ public async Task ConnectAsync_Http11Server_DowngradeFail(Uri server, bool useHa [OuterLoop("Uses external servers", typeof(PlatformDetection), nameof(PlatformDetection.LocalEchoServerIsNotAvailable))] [Theory] - [MemberData(nameof(EchoServersAndBoolean))] + [MemberData(nameof(EchoServers))] [SkipOnPlatform(TestPlatforms.Browser, "System.Net.Sockets is not supported on this platform")] - public async Task ConnectAsync_Http11Server_DowngradeSuccess(Uri server, bool useHandler) + public async Task ConnectAsync_Http11Server_DowngradeSuccess(Uri server) { using (var cws = new ClientWebSocket()) using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { cws.Options.HttpVersion = HttpVersion.Version20; - cws.Options.HttpVersionPolicy = Http.HttpVersionPolicy.RequestVersionOrLower; - if (useHandler) - { - var handler = new SocketsHttpHandler(); - await cws.ConnectAsync(server, new HttpMessageInvoker(handler), cts.Token); - } - else - { - await cws.ConnectAsync(server, cts.Token); - } + cws.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionOrLower; + await cws.ConnectAsync(server, GetInvoker(), cts.Token); Assert.Equal(WebSocketState.Open, cws.State); } } - - [Theory] - [InlineData(false)] - [InlineData(true)] + [Fact] [SkipOnPlatform(TestPlatforms.Browser, "System.Net.Sockets is not supported on this platform")] - public async Task ConnectAsync_VersionSupported_NoSsl_Success(bool useHandler) + public async Task ConnectAsync_VersionSupported_NoSsl_Success() { await Http2LoopbackServer.CreateClientAndServerAsync(async uri => { @@ -161,16 +156,8 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async uri => using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { cws.Options.HttpVersion = HttpVersion.Version20; - cws.Options.HttpVersionPolicy = Http.HttpVersionPolicy.RequestVersionExact; - if (useHandler) - { - var handler = new SocketsHttpHandler(); - await cws.ConnectAsync(uri, new HttpMessageInvoker(handler), cts.Token); - } - else - { - await cws.ConnectAsync(uri, cts.Token); - } + cws.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact; + await cws.ConnectAsync(uri, GetInvoker(), cts.Token); } }, async server => @@ -178,8 +165,7 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async uri => Http2LoopbackConnection connection = await server.EstablishConnectionAsync(new SettingsEntry { SettingId = SettingId.EnableConnect, Value = 1 }); (int streamId, HttpRequestData requestData) = await connection.ReadAndParseRequestHeaderAsync(readBody: false); await connection.SendResponseHeadersAsync(streamId, endStream: false, HttpStatusCode.OK); - }, new Http2Options() { WebSocketEndpoint = true, UseSsl = false } - ); + }, new Http2Options() { WebSocketEndpoint = true, UseSsl = false }); } [Fact] @@ -192,10 +178,8 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async uri => using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { cws.Options.HttpVersion = HttpVersion.Version20; - cws.Options.HttpVersionPolicy = Http.HttpVersionPolicy.RequestVersionExact; - - var handler = CreateSocketsHttpHandler(allowAllCertificates: true); - await cws.ConnectAsync(uri, new HttpMessageInvoker(handler), cts.Token); + cws.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact; + await cws.ConnectAsync(uri, GetInvoker(), cts.Token); } }, async server => @@ -203,8 +187,39 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async uri => Http2LoopbackConnection connection = await server.EstablishConnectionAsync(new SettingsEntry { SettingId = SettingId.EnableConnect, Value = 1 }); (int streamId, HttpRequestData requestData) = await connection.ReadAndParseRequestHeaderAsync(readBody: false); await connection.SendResponseHeadersAsync(streamId, endStream: false, HttpStatusCode.OK); - }, new Http2Options() { WebSocketEndpoint = true } - ); + }, new Http2Options() { WebSocketEndpoint = true }); + } + + [Fact] + [SkipOnPlatform(TestPlatforms.Browser, "HTTP/2 WebSockets aren't supported on Browser")] + public async Task ConnectAsync_SameHttp2ConnectionUsedForMultipleWebSocketConnection() + { + await Http2LoopbackServer.CreateClientAndServerAsync(async uri => + { + using var cws1 = new ClientWebSocket(); + cws1.Options.HttpVersion = HttpVersion.Version20; + cws1.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact; + + using var cws2 = new ClientWebSocket(); + cws2.Options.HttpVersion = HttpVersion.Version20; + cws2.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact; + + using var cts = new CancellationTokenSource(TimeOutMilliseconds); + HttpMessageInvoker? invoker = GetInvoker(); + + await cws1.ConnectAsync(uri, invoker, cts.Token); + await cws2.ConnectAsync(uri, invoker, cts.Token); + }, + async server => + { + await using Http2LoopbackConnection connection = await server.EstablishConnectionAsync(new SettingsEntry { SettingId = SettingId.EnableConnect, Value = 1 }); + + (int streamId1, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false); + await connection.SendResponseHeadersAsync(streamId1, endStream: false, HttpStatusCode.OK); + + (int streamId2, _) = await connection.ReadAndParseRequestHeaderAsync(readBody: false); + await connection.SendResponseHeadersAsync(streamId2, endStream: false, HttpStatusCode.OK); + }, new Http2Options() { WebSocketEndpoint = true, UseSsl = false }); } } } diff --git a/src/libraries/System.Net.WebSockets.Client/tests/ConnectTest.cs b/src/libraries/System.Net.WebSockets.Client/tests/ConnectTest.cs index fd0eee1265cfa1..3fd63fbbb7c61a 100644 --- a/src/libraries/System.Net.WebSockets.Client/tests/ConnectTest.cs +++ b/src/libraries/System.Net.WebSockets.Client/tests/ConnectTest.cs @@ -3,12 +3,11 @@ using System.Collections.Generic; using System.IO; -using System.Linq; using System.Net.Http; using System.Net.Test.Common; +using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; - using Xunit; using Xunit.Abstractions; @@ -17,14 +16,78 @@ namespace System.Net.WebSockets.Client.Tests public sealed class InvokerConnectTest : ConnectTest { public InvokerConnectTest(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpMessageInvoker(new SocketsHttpHandler()); + + protected override bool UseCustomInvoker => true; + + public static IEnumerable ConnectAsync_CustomInvokerWithIncompatibleWebSocketOptions_ThrowsArgumentException_MemberData() + { + yield return Throw(options => options.UseDefaultCredentials = true); + yield return NoThrow(options => options.UseDefaultCredentials = false); + yield return Throw(options => options.Credentials = new NetworkCredential()); + yield return Throw(options => options.Proxy = new WebProxy()); + yield return Throw(options => options.ClientCertificates.Add(Test.Common.Configuration.Certificates.GetClientCertificate())); + yield return NoThrow(options => options.ClientCertificates = new X509CertificateCollection()); + yield return Throw(options => options.RemoteCertificateValidationCallback = delegate { return true; }); + yield return Throw(options => options.Cookies = new CookieContainer()); + + // We allow no proxy or the default proxy to be used + yield return NoThrow(options => { }); + yield return NoThrow(options => options.Proxy = null); + + // These options don't conflict with the custom invoker + yield return NoThrow(options => options.HttpVersion = new Version(2, 0)); + yield return NoThrow(options => options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher); + yield return NoThrow(options => options.SetRequestHeader("foo", "bar")); + yield return NoThrow(options => options.AddSubProtocol("foo")); + yield return NoThrow(options => options.KeepAliveInterval = TimeSpan.FromSeconds(42)); + yield return NoThrow(options => options.DangerousDeflateOptions = new WebSocketDeflateOptions()); + yield return NoThrow(options => options.CollectHttpResponseDetails = true); + + static object[] Throw(Action configureOptions) => + new object[] { configureOptions, true }; + + static object[] NoThrow(Action configureOptions) => + new object[] { configureOptions, false }; + } + + [Theory] + [MemberData(nameof(ConnectAsync_CustomInvokerWithIncompatibleWebSocketOptions_ThrowsArgumentException_MemberData))] + [SkipOnPlatform(TestPlatforms.Browser, "Custom invoker is ignored on Browser")] + public async Task ConnectAsync_CustomInvokerWithIncompatibleWebSocketOptions_ThrowsArgumentException(Action configureOptions, bool shouldThrow) + { + using var invoker = new HttpMessageInvoker(new SocketsHttpHandler + { + ConnectCallback = (_, _) => ValueTask.FromException(new Exception("ConnectCallback")) + }); + + using var ws = new ClientWebSocket(); + configureOptions(ws.Options); + + Task connectTask = ws.ConnectAsync(new Uri("wss://dummy"), invoker, CancellationToken.None); + if (shouldThrow) + { + Assert.Equal(TaskStatus.Faulted, connectTask.Status); + await Assert.ThrowsAsync("options", () => connectTask); + } + else + { + WebSocketException ex = await Assert.ThrowsAsync(() => connectTask); + Assert.NotNull(ex.InnerException); + Assert.Contains("ConnectCallback", ex.InnerException.Message); + } + + foreach (X509Certificate cert in ws.Options.ClientCertificates) + { + cert.Dispose(); + } + } } public sealed class HttpClientConnectTest : ConnectTest { public HttpClientConnectTest(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpClient(new HttpClientHandler()); + protected override bool UseHttpClient => true; } public class ConnectTest : ClientWebSocketTestBase @@ -258,7 +321,13 @@ public async Task ConnectAndCloseAsync_UseProxyServer_ExpectedClosedState(Uri se using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create()) { - cws.Options.Proxy = new WebProxy(proxyServer.Uri); + ConfigureCustomHandler = handler => handler.Proxy = new WebProxy(proxyServer.Uri); + + if (UseSharedHandler) + { + cws.Options.Proxy = new WebProxy(proxyServer.Uri); + } + await ConnectAsync(cws, server, cts.Token); string expectedCloseStatusDescription = "Client close status"; @@ -267,6 +336,7 @@ public async Task ConnectAndCloseAsync_UseProxyServer_ExpectedClosedState(Uri se Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(WebSocketCloseStatus.NormalClosure, cws.CloseStatus); Assert.Equal(expectedCloseStatusDescription, cws.CloseStatusDescription); + Assert.Equal(1, proxyServer.Connections); } } diff --git a/src/libraries/System.Net.WebSockets.Client/tests/DeflateTests.cs b/src/libraries/System.Net.WebSockets.Client/tests/DeflateTests.cs index 262e45ae414db8..9836f31df16cb7 100644 --- a/src/libraries/System.Net.WebSockets.Client/tests/DeflateTests.cs +++ b/src/libraries/System.Net.WebSockets.Client/tests/DeflateTests.cs @@ -18,14 +18,14 @@ public sealed class InvokerDeflateTests : DeflateTests { public InvokerDeflateTests(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpMessageInvoker(new SocketsHttpHandler()); + protected override bool UseCustomInvoker => true; } public sealed class HttpClientDeflateTests : DeflateTests { public HttpClientDeflateTests(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpClient(new HttpClientHandler()); + protected override bool UseHttpClient => true; } [PlatformSpecific(~TestPlatforms.Browser)] diff --git a/src/libraries/System.Net.WebSockets.Client/tests/SendReceiveTest.Http2.cs b/src/libraries/System.Net.WebSockets.Client/tests/SendReceiveTest.Http2.cs index 5f3be83d5bfb79..ef21a36e44fa8f 100644 --- a/src/libraries/System.Net.WebSockets.Client/tests/SendReceiveTest.Http2.cs +++ b/src/libraries/System.Net.WebSockets.Client/tests/SendReceiveTest.Http2.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Net.Http; -using System.Net.Sockets; using System.Net.Test.Common; using System.Threading; using System.Threading.Tasks; @@ -11,19 +10,29 @@ using Xunit; using Xunit.Abstractions; -using static System.Net.Http.Functional.Tests.TestHelper; - namespace System.Net.WebSockets.Client.Tests { - public class SendReceiveTest_Http2 : ClientWebSocketTestBase + public sealed class HttpClientSendReceiveTest_Http2 : SendReceiveTest_Http2 + { + public HttpClientSendReceiveTest_Http2(ITestOutputHelper output) : base(output) { } + + protected override bool UseHttpClient => true; + } + + public sealed class InvokerSendReceiveTest_Http2 : SendReceiveTest_Http2 + { + public InvokerSendReceiveTest_Http2(ITestOutputHelper output) : base(output) { } + + protected override bool UseCustomInvoker => true; + } + + public abstract class SendReceiveTest_Http2 : ClientWebSocketTestBase { public SendReceiveTest_Http2(ITestOutputHelper output) : base(output) { } - [Theory] - [InlineData(false)] - [InlineData(true)] + [Fact] [SkipOnPlatform(TestPlatforms.Browser, "System.Net.Sockets is not supported on this platform")] - public async Task ReceiveNoThrowAfterSend_NoSsl(bool useHandler) + public async Task ReceiveNoThrowAfterSend_NoSsl() { var serverMessage = new byte[] { 4, 5, 6 }; await Http2LoopbackServer.CreateClientAndServerAsync(async uri => @@ -32,16 +41,9 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async uri => using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { cws.Options.HttpVersion = HttpVersion.Version20; - cws.Options.HttpVersionPolicy = Http.HttpVersionPolicy.RequestVersionExact; - if (useHandler) - { - var handler = new SocketsHttpHandler(); - await cws.ConnectAsync(uri, new HttpMessageInvoker(handler), cts.Token); - } - else - { - await cws.ConnectAsync(uri, cts.Token); - } + cws.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact; + + await cws.ConnectAsync(uri, GetInvoker(), cts.Token); await cws.SendAsync(new byte[] { 2, 3, 4 }, WebSocketMessageType.Binary, true, cts.Token); @@ -63,8 +65,7 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async uri => byte[] constructMessage = prefix.Concat(serverMessage).ToArray(); await connection.SendResponseDataAsync(streamId, constructMessage, endStream: false); - }, new Http2Options() { WebSocketEndpoint = true, UseSsl = false } - ); + }, new Http2Options() { WebSocketEndpoint = true, UseSsl = false }); } [Fact] @@ -78,10 +79,9 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async uri => using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { cws.Options.HttpVersion = HttpVersion.Version20; - cws.Options.HttpVersionPolicy = Http.HttpVersionPolicy.RequestVersionExact; + cws.Options.HttpVersionPolicy = HttpVersionPolicy.RequestVersionExact; - var handler = CreateSocketsHttpHandler(allowAllCertificates: true); - await cws.ConnectAsync(uri, new HttpMessageInvoker(handler), cts.Token); + await cws.ConnectAsync(uri, GetInvoker(), cts.Token); await cws.SendAsync(new byte[] { 2, 3, 4 }, WebSocketMessageType.Binary, true, cts.Token); @@ -103,8 +103,7 @@ await Http2LoopbackServer.CreateClientAndServerAsync(async uri => byte[] constructMessage = prefix.Concat(serverMessage).ToArray(); await connection.SendResponseDataAsync(streamId, constructMessage, endStream: false); - }, new Http2Options() { WebSocketEndpoint = true } - ); + }, new Http2Options() { WebSocketEndpoint = true }); } } } diff --git a/src/libraries/System.Net.WebSockets.Client/tests/SendReceiveTest.cs b/src/libraries/System.Net.WebSockets.Client/tests/SendReceiveTest.cs index 6597b6f9ec6315..ec3913c02c16c9 100644 --- a/src/libraries/System.Net.WebSockets.Client/tests/SendReceiveTest.cs +++ b/src/libraries/System.Net.WebSockets.Client/tests/SendReceiveTest.cs @@ -17,28 +17,28 @@ public sealed class InvokerMemorySendReceiveTest : MemorySendReceiveTest { public InvokerMemorySendReceiveTest(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpMessageInvoker(new SocketsHttpHandler()); + protected override bool UseCustomInvoker => true; } public sealed class HttpClientMemorySendReceiveTest : MemorySendReceiveTest { public HttpClientMemorySendReceiveTest(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpClient(new HttpClientHandler()); + protected override bool UseHttpClient => true; } public sealed class InvokerArraySegmentSendReceiveTest : ArraySegmentSendReceiveTest { public InvokerArraySegmentSendReceiveTest(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpMessageInvoker(new SocketsHttpHandler()); + protected override bool UseCustomInvoker => true; } public sealed class HttpClientArraySegmentSendReceiveTest : ArraySegmentSendReceiveTest { public HttpClientArraySegmentSendReceiveTest(ITestOutputHelper output) : base(output) { } - protected override HttpMessageInvoker? GetInvoker() => new HttpClient(new HttpClientHandler()); + protected override bool UseHttpClient => true; } public class MemorySendReceiveTest : SendReceiveTest From e6e4d222e93fea793be062a3211af0a735486f00 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 2 Sep 2022 16:53:33 -0400 Subject: [PATCH 096/107] Fix argument validation in RuntimeType.InvokeMember (#74998) The rollout of `!!` erroneously moved an ArgumentNullException to be thrown earlier in the method, preventing a null name from being used (which is valid with BindingFlags.CreateInstance). (Separately, we should consider fixing the nullable reference type annotation on `string name`, since null is allowed in some circumstances.) --- .../System.Private.CoreLib/src/System/RuntimeType.cs | 6 +++--- .../System.Reflection/tests/DefaultBinderTests.cs | 8 ++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs b/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs index 81d6f994da54f9..d4b45f21bc9d74 100644 --- a/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs @@ -459,8 +459,6 @@ public override bool IsAssignableFrom([NotNullWhen(true)] Type? c) string name, BindingFlags bindingFlags, Binder? binder, object? target, object?[]? providedArgs, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParams) { - ArgumentNullException.ThrowIfNull(name); - const BindingFlags MemberBindingMask = (BindingFlags)0x000000FF; const BindingFlags InvocationMask = (BindingFlags)0x0000FF00; const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField; @@ -567,10 +565,12 @@ public override bool IsAssignableFrom([NotNullWhen(true)] Type? c) // PutDispProperty and\or PutRefDispProperty ==> SetProperty. if ((bindingFlags & (BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) != 0) bindingFlags |= BindingFlags.SetProperty; + + ArgumentNullException.ThrowIfNull(name); if (name.Length == 0 || name.Equals("[DISPID=0]")) { // in InvokeMember we always pretend there is a default member if none is provided and we make it ToString - name = GetDefaultMemberName()! ?? "ToString"; + name = GetDefaultMemberName() ?? "ToString"; } // GetField or SetField diff --git a/src/libraries/System.Reflection/tests/DefaultBinderTests.cs b/src/libraries/System.Reflection/tests/DefaultBinderTests.cs index 99018fed4b6a1c..874e1f3d5864c6 100644 --- a/src/libraries/System.Reflection/tests/DefaultBinderTests.cs +++ b/src/libraries/System.Reflection/tests/DefaultBinderTests.cs @@ -167,6 +167,14 @@ public static void InvokeWithNamedParametersOutOfOrder() Assert.Equal(8, result); } + [Theory] + [InlineData("")] + [InlineData(null)] + public static void InvokeWithCreateInstance(string name) + { + Assert.IsType(typeof(Sample).InvokeMember(name, BindingFlags.CreateInstance, null, null, null)); + } + public class Test { public void TestMethod(int param1) { } From 5bec2946f8587fba500105545119b5833fc53fb8 Mon Sep 17 00:00:00 2001 From: "dotnet-maestro[bot]" <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Fri, 2 Sep 2022 21:07:56 +0000 Subject: [PATCH 097/107] [main] Update dependencies from dotnet/linker (#74704) [main] Update dependencies from dotnet/linker --- eng/Version.Details.xml | 4 ++-- eng/Versions.props | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 0176f725cf00e3..3eaeeab98e2c1b 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -226,9 +226,9 @@ https://github.com/dotnet/runtime 48a3dbe5509f53f89db0a48c8285a2eec0758fea - + https://github.com/dotnet/linker - b23be78205b79d60c1ea2cab5306f530a0faade2 + f0b2510bfd53a35df0aeae48996d2905c1067022 https://github.com/dotnet/xharness diff --git a/eng/Versions.props b/eng/Versions.props index d3aaf37ff60c05..b1f04ceb5d5b37 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -179,7 +179,7 @@ 7.0.0-preview-20220822.1 - 7.0.100-1.22425.2 + 7.0.100-1.22451.5 $(MicrosoftNETILLinkTasksVersion) 8.0.0-alpha.1.22451.5 From 01251a8eed36a144d33e19c8bd96ac39b67204f2 Mon Sep 17 00:00:00 2001 From: Lakshan Fernando Date: Fri, 2 Sep 2022 15:11:45 -0700 Subject: [PATCH 098/107] Add support so that SDK6 will continue to get the latest ILC packages (#75017) --- ...osoft.DotNet.ILCompiler.SingleEntry.targets | 16 +++++++++++----- .../Microsoft.DotNet.ILCompiler.targets | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) create mode 100644 src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.targets diff --git a/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.SingleEntry.targets b/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.SingleEntry.targets index 67cd1b2ceb5c0d..5e4110529b1c10 100644 --- a/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.SingleEntry.targets +++ b/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.SingleEntry.targets @@ -37,27 +37,33 @@ - + $([System.IO.Path]::GetFileName($([System.IO.Path]::GetDirectoryName($([System.IO.Path]::GetDirectoryName($(ILCompilerTargetsPath))))))) - + - - + + - + @(ResolvedILCompilerPack->'%(PackageDirectory)') @(ResolvedTargetILCompilerPack->'%(PackageDirectory)') @(ResolvedILCompilerPack->'%(PackageDirectory)') + + %(PackageDefinitions.ResolvedPath) + %(PackageDefinitions.ResolvedPath) + + diff --git a/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.targets b/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.targets new file mode 100644 index 00000000000000..28ca04be98b91b --- /dev/null +++ b/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.targets @@ -0,0 +1,18 @@ + + + + + $(NETCoreSdkVersion.StartsWith('6')) + + + From 2aed1fdf926d7052b5254660cc3bc2b4af17bcb9 Mon Sep 17 00:00:00 2001 From: SingleAccretion <62474226+SingleAccretion@users.noreply.github.com> Date: Sat, 3 Sep 2022 03:05:00 +0300 Subject: [PATCH 099/107] Do not retype small locals in `FIELD_LIST`s on x86 (#74030) * Add a test * Do not widen uses of normalize-on-load locals This breaks the assumption that all LCL_VAR uses of such locals, when typed small, are normalized (and equivalent to each other). Instead, explicitly check for legality of widening the loads in LSRA and codegen. * "Load/StoreWithPush" -> "Load/StoreFullSlot" The load variant in codegen now has double purpose. --- src/coreclr/jit/codegenxarch.cpp | 42 ++++++---- src/coreclr/jit/lowerxarch.cpp | 12 --- src/coreclr/jit/lsraxarch.cpp | 11 +-- .../JitBlue/Runtime_73951/Runtime_73951.cs | 76 +++++++++++++++++++ .../Runtime_73951/Runtime_73951.csproj | 9 +++ 5 files changed, 118 insertions(+), 32 deletions(-) create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_73951/Runtime_73951.cs create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_73951/Runtime_73951.csproj diff --git a/src/coreclr/jit/codegenxarch.cpp b/src/coreclr/jit/codegenxarch.cpp index 6cfe068be76b68..1f7b777f852887 100644 --- a/src/coreclr/jit/codegenxarch.cpp +++ b/src/coreclr/jit/codegenxarch.cpp @@ -7887,9 +7887,9 @@ void CodeGen::genPutArgStkFieldList(GenTreePutArgStk* putArgStk) for (GenTreeFieldList::Use& use : fieldList->Uses()) { - GenTree* const fieldNode = use.GetNode(); - const unsigned fieldOffset = use.GetOffset(); - var_types fieldType = use.GetType(); + GenTree* const fieldNode = use.GetNode(); + const unsigned fieldOffset = use.GetOffset(); + const var_types fieldType = use.GetType(); // Long-typed nodes should have been handled by the decomposition pass, and lowering should have sorted the // field list in descending order by offset. @@ -7912,8 +7912,7 @@ void CodeGen::genPutArgStkFieldList(GenTreePutArgStk* putArgStk) int adjustment = roundUp(currentOffset - fieldOffset, 4); if (fieldIsSlot && !varTypeIsSIMD(fieldType)) { - fieldType = genActualType(fieldType); - unsigned pushSize = genTypeSize(fieldType); + unsigned pushSize = genTypeSize(genActualType(fieldType)); assert((pushSize % 4) == 0); adjustment -= pushSize; while (adjustment != 0) @@ -7961,13 +7960,22 @@ void CodeGen::genPutArgStkFieldList(GenTreePutArgStk* putArgStk) } } - bool canStoreWithPush = fieldIsSlot; - bool canLoadWithPush = varTypeIsI(fieldNode) || genIsValidIntReg(argReg); + bool canStoreFullSlot = fieldIsSlot; + bool canLoadFullSlot = genIsValidIntReg(argReg); + if (argReg == REG_NA) + { + assert((genTypeSize(fieldNode) <= TARGET_POINTER_SIZE)); + assert(genTypeSize(genActualType(fieldNode)) == genTypeSize(genActualType(fieldType))); + + // We can widen local loads if the excess only affects padding bits. + canLoadFullSlot = (genTypeSize(fieldNode) == TARGET_POINTER_SIZE) || fieldNode->isUsedFromSpillTemp() || + (fieldNode->OperIsLocalRead() && (genTypeSize(fieldNode) >= genTypeSize(fieldType))); + } - if (canStoreWithPush && canLoadWithPush) + if (canStoreFullSlot && canLoadFullSlot) { assert(m_pushStkArg); - assert(genTypeSize(fieldNode) == TARGET_POINTER_SIZE); + assert(genTypeSize(fieldNode) <= TARGET_POINTER_SIZE); inst_TT(INS_push, emitActualTypeSize(fieldNode), fieldNode); currentOffset -= TARGET_POINTER_SIZE; @@ -7990,9 +7998,10 @@ void CodeGen::genPutArgStkFieldList(GenTreePutArgStk* putArgStk) } else { - // TODO-XArch-CQ: using "ins_Load" here is conservative, as it will always - // extend, which we can avoid if the field type is smaller than the node type. - inst_RV_TT(ins_Load(fieldNode->TypeGet()), emitTypeSize(fieldNode), intTmpReg, fieldNode); + // Use the smaller "mov" instruction in case we do not need a sign/zero-extending load. + instruction loadIns = canLoadFullSlot ? INS_mov : ins_Load(fieldNode->TypeGet()); + emitAttr loadSize = canLoadFullSlot ? EA_PTRSIZE : emitTypeSize(fieldNode); + inst_RV_TT(loadIns, loadSize, intTmpReg, fieldNode); } argReg = intTmpReg; @@ -8007,13 +8016,16 @@ void CodeGen::genPutArgStkFieldList(GenTreePutArgStk* putArgStk) else #endif // defined(FEATURE_SIMD) { - genStoreRegToStackArg(fieldType, argReg, fieldOffset - currentOffset); + // Using wide stores here avoids having to reserve a byteable register when we could not + // use "push" due to the field node being an indirection (i. e. for "!canLoadFullSlot"). + var_types storeType = canStoreFullSlot ? genActualType(fieldType) : fieldType; + genStoreRegToStackArg(storeType, argReg, fieldOffset - currentOffset); } if (m_pushStkArg) { - // We always push a slot-rounded size - currentOffset -= genTypeSize(fieldType); + // We always push a slot-rounded size. + currentOffset -= roundUp(genTypeSize(fieldType), TARGET_POINTER_SIZE); } } diff --git a/src/coreclr/jit/lowerxarch.cpp b/src/coreclr/jit/lowerxarch.cpp index 103bffe15cb21f..2b10804773af0d 100644 --- a/src/coreclr/jit/lowerxarch.cpp +++ b/src/coreclr/jit/lowerxarch.cpp @@ -507,18 +507,6 @@ void Lowering::LowerPutArgStk(GenTreePutArgStk* putArgStk) // registers to be consumed atomically by the call. if (varTypeIsIntegralOrI(fieldNode)) { - // If we are loading from an in-memory local, we would like to use "push", but this - // is only legal if we can safely load all 4 bytes. Retype the local node here to - // TYP_INT for such legal cases to make downstream (LSRA & codegen) logic simpler. - // Retyping is ok because we model this node as STORE(LOAD). - // If the field came from promotion, we allow the padding to remain undefined, if - // from decomposition, the field type will be INT (naturally blocking the retyping). - if (varTypeIsSmall(fieldNode) && (genTypeSize(fieldType) <= genTypeSize(fieldNode)) && - fieldNode->OperIsLocalRead()) - { - fieldNode->ChangeType(TYP_INT); - } - if (IsContainableImmed(putArgStk, fieldNode)) { MakeSrcContained(putArgStk, fieldNode); diff --git a/src/coreclr/jit/lsraxarch.cpp b/src/coreclr/jit/lsraxarch.cpp index 9fdfe585c68e8e..1c97652c5a4764 100644 --- a/src/coreclr/jit/lsraxarch.cpp +++ b/src/coreclr/jit/lsraxarch.cpp @@ -1512,17 +1512,18 @@ int LinearScan::BuildPutArgStk(GenTreePutArgStk* putArgStk) // We can treat as a slot any field that is stored at a slot boundary, where the previous // field is not in the same slot. (Note that we store the fields in reverse order.) - const bool fieldIsSlot = ((fieldOffset % 4) == 0) && ((prevOffset - fieldOffset) >= 4); - const bool canStoreWithPush = fieldIsSlot; - const bool canLoadWithPush = varTypeIsI(fieldNode); + const bool canStoreFullSlot = ((fieldOffset % 4) == 0) && ((prevOffset - fieldOffset) >= 4); + const bool canLoadFullSlot = + (genTypeSize(fieldNode) == TARGET_POINTER_SIZE) || + (fieldNode->OperIsLocalRead() && (genTypeSize(fieldNode) >= genTypeSize(fieldType))); - if ((!canStoreWithPush || !canLoadWithPush) && (intTemp == nullptr)) + if ((!canStoreFullSlot || !canLoadFullSlot) && (intTemp == nullptr)) { intTemp = buildInternalIntRegisterDefForNode(putArgStk); } // We can only store bytes using byteable registers. - if (!canStoreWithPush && varTypeIsByte(fieldType)) + if (!canStoreFullSlot && varTypeIsByte(fieldType)) { intTemp->registerAssignment &= allByteRegs(); } diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_73951/Runtime_73951.cs b/src/tests/JIT/Regression/JitBlue/Runtime_73951/Runtime_73951.cs new file mode 100644 index 00000000000000..1f4f5895fdc4c6 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_73951/Runtime_73951.cs @@ -0,0 +1,76 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +public class Runtime_73951 +{ + [ThreadStatic] + public static IRuntime s_rt; + [ThreadStatic] + public static S1 s_17; + + public static ushort s_result; + + public static int Main() + { + Problem(new Runtime()); + + return s_result == 0 ? 100 : 101; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public static void Problem(IRuntime rt) + { + s_rt = rt; + S0 vr21 = s_17.F1; + new S1(new object()).M105(vr21); + + var vr22 = new C0(vr21.F3); + s_rt.Capture(vr22.F1); + } + + public class C0 + { + public ushort F1; + public C0(ushort f1) + { + F1 = f1; + } + } + + public struct S0 + { + public uint F1; + public int F2; + public byte F3; + } + + public struct S1 + { + public object F0; + public S0 F1; + public S1(object f0) : this() + { + F0 = f0; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public S1 M105(S0 arg0) + { + return this; + } + } + + public interface IRuntime + { + void Capture(ushort value); + } + + public class Runtime : IRuntime + { + public void Capture(ushort value) => s_result = value; + } +} diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_73951/Runtime_73951.csproj b/src/tests/JIT/Regression/JitBlue/Runtime_73951/Runtime_73951.csproj new file mode 100644 index 00000000000000..f492aeac9d056b --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_73951/Runtime_73951.csproj @@ -0,0 +1,9 @@ + + + Exe + True + + + + + \ No newline at end of file From 8582c5cbcf03d6c0d1d3f0d11e622b8b0168f50f Mon Sep 17 00:00:00 2001 From: SingleAccretion <62474226+SingleAccretion@users.noreply.github.com> Date: Sat, 3 Sep 2022 03:10:33 +0300 Subject: [PATCH 100/107] Fix `fgNoStructParamPromotion` (#74807) * Fix "fgNoStructParamPromotion" The setting didn't actually disallow promotion of parameters, only made it dependent. This broke some assumptions in morph that if a dependently promoted struct is encountered, it must have already been marked DNER. * Add a test --- src/coreclr/jit/compiler.hpp | 7 ----- src/coreclr/jit/lclvars.cpp | 6 +++++ .../JitBlue/Runtime_74774/Runtime_74774.cs | 27 +++++++++++++++++++ .../Runtime_74774/Runtime_74774.csproj | 17 ++++++++++++ 4 files changed, 50 insertions(+), 7 deletions(-) create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_74774/Runtime_74774.cs create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_74774/Runtime_74774.csproj diff --git a/src/coreclr/jit/compiler.hpp b/src/coreclr/jit/compiler.hpp index 63b83aa8eb61d1..d8ba65821e7b1e 100644 --- a/src/coreclr/jit/compiler.hpp +++ b/src/coreclr/jit/compiler.hpp @@ -3886,13 +3886,6 @@ inline Compiler::lvaPromotionType Compiler::lvaGetPromotionType(const LclVarDsc* return PROMOTION_TYPE_INDEPENDENT; } - // Has struct promotion for arguments been disabled using COMPlus_JitNoStructPromotion=2 - if (fgNoStructParamPromotion) - { - // The struct parameter is not enregistered - return PROMOTION_TYPE_DEPENDENT; - } - // We have a parameter that could be enregistered #if defined(TARGET_ARM) // TODO-Cleanup: return INDEPENDENT for arm32. diff --git a/src/coreclr/jit/lclvars.cpp b/src/coreclr/jit/lclvars.cpp index d11743d9902b6c..1d70f4c42f6fbd 100644 --- a/src/coreclr/jit/lclvars.cpp +++ b/src/coreclr/jit/lclvars.cpp @@ -2039,6 +2039,12 @@ bool Compiler::StructPromotionHelper::CanPromoteStructVar(unsigned lclNum) return false; } + if (varDsc->lvIsParam && compiler->fgNoStructParamPromotion) + { + JITDUMP(" struct promotion of V%02u is disabled by fgNoStructParamPromotion\n", lclNum); + return false; + } + if (!compiler->lvaEnregMultiRegVars && varDsc->lvIsMultiRegArgOrRet()) { JITDUMP(" struct promotion of V%02u is disabled because lvIsMultiRegArgOrRet()\n", lclNum); diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_74774/Runtime_74774.cs b/src/tests/JIT/Regression/JitBlue/Runtime_74774/Runtime_74774.cs new file mode 100644 index 00000000000000..a7d044fd88bbc6 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_74774/Runtime_74774.cs @@ -0,0 +1,27 @@ +// 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; + +class Runtime_74774 +{ + private static int Main() + { + return Problem(new() { FirstLngValue = 1, SecondLngValue = 2 }) != 3 ? 101 : 100; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static long Problem(MultiRegStruct a) + { + [MethodImpl(MethodImplOptions.NoInlining)] + static long Call(MultiRegStruct a, MultiRegStruct b, MultiRegStruct c, MultiRegStruct d) => d.FirstLngValue + d.SecondLngValue; + + return Call(default, default, default, a); + } + + struct MultiRegStruct + { + public long FirstLngValue; + public long SecondLngValue; + } +} diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_74774/Runtime_74774.csproj b/src/tests/JIT/Regression/JitBlue/Runtime_74774/Runtime_74774.csproj new file mode 100644 index 00000000000000..54269a29060e60 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_74774/Runtime_74774.csproj @@ -0,0 +1,17 @@ + + + Exe + True + + + + + + + \ No newline at end of file From 8b73164bf51047edc078c5e67dffa085b1f3b89e Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Sat, 3 Sep 2022 04:44:47 -0700 Subject: [PATCH 101/107] Simplify NativeAOT warning message (#75043) --- .../Microsoft.DotNet.ILCompiler.SingleEntry.targets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.SingleEntry.targets b/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.SingleEntry.targets index 5e4110529b1c10..4ea64f9b83be41 100644 --- a/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.SingleEntry.targets +++ b/src/coreclr/nativeaot/BuildIntegration/Microsoft.DotNet.ILCompiler.SingleEntry.targets @@ -46,7 +46,7 @@ - + From 9e81ca53137c587bce0f30bf60f13bb10fbdd204 Mon Sep 17 00:00:00 2001 From: SingleAccretion <62474226+SingleAccretion@users.noreply.github.com> Date: Sat, 3 Sep 2022 21:04:34 +0300 Subject: [PATCH 102/107] Preference sources of copy-like casts to destinations (#74777) * Preference sources of copy-like casts to destinations * Remove invalid BITCAST usage Couple improvements because of CAST's better preferencing. --- src/coreclr/jit/lower.cpp | 9 ++----- src/coreclr/jit/lsra.h | 1 + src/coreclr/jit/lsraarmarch.cpp | 2 +- src/coreclr/jit/lsrabuild.cpp | 46 ++++++++++++++++++++++++++++++--- src/coreclr/jit/lsraxarch.cpp | 3 ++- 5 files changed, 48 insertions(+), 13 deletions(-) diff --git a/src/coreclr/jit/lower.cpp b/src/coreclr/jit/lower.cpp index 3532c4e996866e..21ec29cfaeb6c9 100644 --- a/src/coreclr/jit/lower.cpp +++ b/src/coreclr/jit/lower.cpp @@ -5764,15 +5764,10 @@ bool Lowering::LowerUnsignedDivOrMod(GenTreeOp* divMod) } else if (type != TYP_I_IMPL) { -#ifdef TARGET_ARMARCH divMod->SetOper(GT_CAST); - divMod->SetUnsigned(); divMod->AsCast()->gtCastType = TYP_INT; -#else - divMod->SetOper(GT_BITCAST); -#endif - divMod->gtOp1 = mulhi; - divMod->gtOp2 = nullptr; + divMod->gtOp1 = mulhi; + divMod->gtOp2 = nullptr; } } diff --git a/src/coreclr/jit/lsra.h b/src/coreclr/jit/lsra.h index e17f42d760be6d..5dbdd4afd85703 100644 --- a/src/coreclr/jit/lsra.h +++ b/src/coreclr/jit/lsra.h @@ -1815,6 +1815,7 @@ class LinearScan : public LinearScanInterface void setDelayFree(RefPosition* use); int BuildBinaryUses(GenTreeOp* node, regMaskTP candidates = RBM_NONE); + int BuildCastUses(GenTreeCast* cast, regMaskTP candidates); #ifdef TARGET_XARCH int BuildRMWUses(GenTree* node, GenTree* op1, GenTree* op2, regMaskTP candidates = RBM_NONE); #endif // !TARGET_XARCH diff --git a/src/coreclr/jit/lsraarmarch.cpp b/src/coreclr/jit/lsraarmarch.cpp index c5c03a99f58f52..2c42d385758bfd 100644 --- a/src/coreclr/jit/lsraarmarch.cpp +++ b/src/coreclr/jit/lsraarmarch.cpp @@ -806,7 +806,7 @@ int LinearScan::BuildCast(GenTreeCast* cast) } #endif - int srcCount = BuildOperandUses(src); + int srcCount = BuildCastUses(cast, RBM_NONE); buildInternalRegisterUses(); BuildDef(cast); return srcCount; diff --git a/src/coreclr/jit/lsrabuild.cpp b/src/coreclr/jit/lsrabuild.cpp index 8adb111ebc88b7..bd4ac88152fd22 100644 --- a/src/coreclr/jit/lsrabuild.cpp +++ b/src/coreclr/jit/lsrabuild.cpp @@ -2729,7 +2729,7 @@ void LinearScan::validateIntervals() } #endif // DEBUG -#if defined(TARGET_XARCH) || defined(FEATURE_HW_INTRINSICS) +#ifndef TARGET_ARM //------------------------------------------------------------------------ // setTgtPref: Set a preference relationship between the given Interval // and a Use RefPosition. @@ -2760,7 +2760,8 @@ void setTgtPref(Interval* interval, RefPosition* tgtPrefUse) } } } -#endif // TARGET_XARCH || FEATURE_HW_INTRINSICS +#endif // !TARGET_ARM + //------------------------------------------------------------------------ // BuildDef: Build a RefTypeDef RefPosition for the given node // @@ -2841,13 +2842,16 @@ RefPosition* LinearScan::BuildDef(GenTree* tree, regMaskTP dstCandidates, int mu RefInfoListNode* refInfo = listNodePool.GetNode(defRefPosition, tree); defList.Append(refInfo); } -#if defined(TARGET_XARCH) || defined(FEATURE_HW_INTRINSICS) + +#ifndef TARGET_ARM setTgtPref(interval, tgtPrefUse); setTgtPref(interval, tgtPrefUse2); -#endif // TARGET_XARCH +#endif // !TARGET_ARM + #if FEATURE_PARTIAL_SIMD_CALLEE_SAVE assert(!interval->isPartiallySpilled); #endif + return defRefPosition; } @@ -3310,6 +3314,40 @@ int LinearScan::BuildBinaryUses(GenTreeOp* node, regMaskTP candidates) return srcCount; } +//------------------------------------------------------------------------ +// BuildCastUses: Build uses for a cast's source, preferencing it as appropriate. +// +// Arguments: +// cast - The cast node to build uses for +// candidates - The candidate registers for the uses +// +// Return Value: +// The number of actual register operands. +// +int LinearScan::BuildCastUses(GenTreeCast* cast, regMaskTP candidates) +{ + GenTree* src = cast->CastOp(); + + // Casts can have contained memory operands. + if (src->isContained()) + { + return BuildOperandUses(src, candidates); + } + + RefPosition* srcUse = BuildUse(src, candidates); + +#ifdef TARGET_64BIT + // A long -> int cast is a copy - the code generator will elide + // it if the source and destination registers are the same. + if (src->TypeIs(TYP_LONG) && cast->TypeIs(TYP_INT)) + { + tgtPrefUse = srcUse; + } +#endif // TARGET_64BIT + + return 1; +} + //------------------------------------------------------------------------ // BuildStoreLocDef: Build a definition RefPosition for a local store // diff --git a/src/coreclr/jit/lsraxarch.cpp b/src/coreclr/jit/lsraxarch.cpp index 1c97652c5a4764..3c5220ba1d9140 100644 --- a/src/coreclr/jit/lsraxarch.cpp +++ b/src/coreclr/jit/lsraxarch.cpp @@ -2502,9 +2502,10 @@ int LinearScan::BuildCast(GenTreeCast* cast) } #endif - int srcCount = BuildOperandUses(src, candidates); + int srcCount = BuildCastUses(cast, candidates); buildInternalRegisterUses(); BuildDef(cast, candidates); + return srcCount; } From 2d1e29bdd3183b2e33026ad0606dded83583846e Mon Sep 17 00:00:00 2001 From: Jakob Botsch Nielsen Date: Sun, 4 Sep 2022 10:45:57 +0200 Subject: [PATCH 103/107] JIT: Mark an F# test as GC stress incompatible (#75001) Fix #73808 --- .../JIT/Regression/JitBlue/Runtime_72845/Runtime_72845.fsproj | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_72845/Runtime_72845.fsproj b/src/tests/JIT/Regression/JitBlue/Runtime_72845/Runtime_72845.fsproj index f8ba1e7f4a2575..a35f5a5711622f 100644 --- a/src/tests/JIT/Regression/JitBlue/Runtime_72845/Runtime_72845.fsproj +++ b/src/tests/JIT/Regression/JitBlue/Runtime_72845/Runtime_72845.fsproj @@ -1,12 +1,11 @@ Exe - - True True True $(NetCoreAppToolCurrent) + True From 243cf9f617a0bb99c1189de54c1bbd8d26cdba5a Mon Sep 17 00:00:00 2001 From: Jakob Botsch Nielsen Date: Sun, 4 Sep 2022 17:57:42 +0200 Subject: [PATCH 104/107] JIT: Simplify JitDisasm matching behavior (#74430) This changes how the JIT matches method names and signatures for method sets (e.g. JitDisasm). It also starts printing method instantiations for full method names and makes references to types consistent in generic instantiations and the signature. In addition it starts supporting generic instantiations in release too. To do this, most of the type printing is moved to the JIT, which also aligns the output between crossgen2 and the VM (there were subtle differences here, like spaces between generic type arguments). More importantly, we (for the most part) stop relying on JIT-EE methods that are documented to only be for debug purposes. The new behavior of the matching is the following: * The matching behavior is always string based. * The JitDisasm string is a space-separated list of patterns. Patterns can arbitrarily contain both '*' (match any characters) and '?' (match any 1 character). * The string matched against depends on characters in the pattern: + If the pattern contains a ':' character, the string matched against is prefixed by the class name and a colon + If the pattern contains a '(' character, the string matched against is suffixed by the signature + If the class name (part before colon) contains a '[', the class contains its generic instantiation + If the method name (part between colon and '(') contains a '[', the method contains its generic instantiation For example, consider ``` namespace MyNamespace { public class C { [MethodImpl(MethodImplOptions.NoInlining)] public void M(T1 arg1, T2 arg2, T3 arg3, T4 arg4) { } } } new C().M(default, default, default, default); // compilation 1 new C().M(default, default, default, default); // compilation 2 ``` The full strings are: Before the change: ``` MyNamespace.C`2[SByte,__Canon][System.SByte,System.__Canon]:M(byte,System.__Canon,int,System.__Canon) MyNamespace.C`2[Int32,Int32][System.Int32,System.Int32]:M(int,int,int,int) ``` Notice no method instantiation and the double class instantiation, which seems like an EE bug. Also two different names are used for sbyte: System.SByte and byte. After the change the strings are: ``` MyNamespace.C`2[byte,System.__Canon]:M[int,System.__Canon](byte,System.__Canon,int,System.__Canon) MyNamespace.C`2[int,int]:M[int,int](int,int,int,int) ``` The following strings will match both compilations: ``` M *C`2:M *C`2[*]:M[*](*) MyNamespace.C`2:M ``` The following will match only the first one: ``` M[int,*Canon] MyNamespace.C`2[byte,*]:M M(*Canon) ``` There is one significant change in behavior here, which is that I have removed the special case that allows matching class names without namespaces. In particular, today Console:WriteLine would match all overloads of System.Console.WriteLine, while after this change it will not match. However, with generalized wild cards the replacement is simple in *Console:WriteLine. --- docs/design/coreclr/jit/viewing-jit-dumps.md | 54 ++- src/coreclr/inc/corinfo.h | 12 +- src/coreclr/inc/jiteeversionguid.h | 10 +- src/coreclr/jit/compiler.cpp | 80 ++-- src/coreclr/jit/compiler.h | 71 ++- src/coreclr/jit/ee_il_dll.cpp | 29 +- src/coreclr/jit/eeinterface.cpp | 417 +++++++++------- src/coreclr/jit/fgdiagnostic.cpp | 2 +- src/coreclr/jit/fginline.cpp | 4 +- src/coreclr/jit/importer.cpp | 4 +- src/coreclr/jit/jitconfig.cpp | 444 ++++-------------- src/coreclr/jit/jitconfig.h | 18 +- src/coreclr/jit/jitconfigvalues.h | 9 +- .../tools/Common/JitInterface/CorInfoImpl.cs | 30 +- .../tools/superpmi/superpmi-shared/lwmlist.h | 2 +- .../superpmi-shared/methodcontext.cpp | 20 +- .../superpmi/superpmi-shared/methodcontext.h | 4 +- .../superpmi-shim-collector/icorjitinfo.cpp | 6 +- 18 files changed, 585 insertions(+), 631 deletions(-) diff --git a/docs/design/coreclr/jit/viewing-jit-dumps.md b/docs/design/coreclr/jit/viewing-jit-dumps.md index cef68fdac51871..6a13d9859fd798 100644 --- a/docs/design/coreclr/jit/viewing-jit-dumps.md +++ b/docs/design/coreclr/jit/viewing-jit-dumps.md @@ -120,29 +120,59 @@ These can be set in one of three ways: ## Specifying method names -The complete syntax for specifying a single method name (for a flag that takes a method name, such as `COMPlus_JitDump`) is: - +Some environment variables such as `COMPlus_JitDump` take a set of patterns specifying method names. The matching works in the following way: +* A method set string is a space-separated list of patterns. Patterns can arbitrarily contain both '*' (match any characters) and '?' (match any 1 character). +* The string matched against depends on characters in the pattern: + + If the pattern contains a ':' character, the string matched against is prefixed by the class name and a colon + + If the pattern contains a '(' character, the string matched against is suffixed by the signature + + If the class name (part before colon) contains a '[', the class contains its generic instantiation + + If the method name (part between colon and '(') contains a '[', the method contains its generic instantiation + +In particular, the matching is done against strings of the following format which coincides with how the JIT displays method signatures (so these can be copy pasted into the environment variable). ``` -[[.]::][([)] +[ClassName[Instantiation]:]MethodName[Instantiation][()] ``` -For example +For example, consider the following: +```csharp +namespace MyNamespace +{ + public class C + { + [MethodImpl(MethodImplOptions.NoInlining)] + public void M(T1 arg1, T2 arg2, T3 arg3, T4 arg4) + { + } + } +} -``` -System.Object::ToString(System.Object) +new C().M(default, default, default, default); // compilation 1 +new C().M(default, default, default, default); // compilation 2 ``` -The namespace, class name, and argument types are optional, and if they are not present, default to a wildcard. Thus stating: +The full names of these instantiations are the following, as printed by `COMPlus_JitDisasmSummary`: ``` -Main +MyNamespace.C`2[byte,System.__Canon]:M[int,System.__Canon](byte,System.__Canon,int,System.__Canon) +MyNamespace.C`2[int,int]:M[int,int](int,int,int,int) ``` +Note that ``C`2`` here is the name put into metadata by Roslyn; the suffix is not added by RyuJIT. +For Powershell users keep in mind that backtick is the escape character and itself has to be escaped via double backtick. -will match all methods named Main from any class and any number of arguments. - -`` is a comma separated list of type names. Note that presently only the number of arguments and not the types themselves are used to distinguish methods. Thus, `Main(Foo, Bar)` and `Main(int, int)` will both match any main method with two arguments. +The following strings will match both compilations: +``` +M +*C`2:M +*C`2[*]:M[*](*) +MyNamespace.C`2:M +``` -The wildcard character `*` can be used for `` and ``. In particular `*` by itself indicates every method. +The following match only the first compilation: +``` +M[int,*Canon] +MyNamespace.C`2[byte,*]:M +M(*Canon) +``` ## Useful COMPlus variables diff --git a/src/coreclr/inc/corinfo.h b/src/coreclr/inc/corinfo.h index 9a91fc92ae8a96..41154770a8cb22 100644 --- a/src/coreclr/inc/corinfo.h +++ b/src/coreclr/inc/corinfo.h @@ -2893,9 +2893,15 @@ class ICorStaticInfo CORINFO_METHOD_HANDLE hMethod ) = 0; - // this function is for debugging only. It returns the method name - // and if 'moduleName' is non-null, it sets it to something that will - // says which method (a class name, or a module name) + // This function returns the method name and if 'moduleName' is non-null, + // it sets it to something that contains the method (a class + // name, or a module name). Note that the moduleName parameter is for + // diagnostics only. + // + // The method name returned is the same as getMethodNameFromMetadata except + // in the case of functions without metadata (e.g. IL stubs), where this + // function still returns a reasonable name while getMethodNameFromMetadata + // returns null. virtual const char* getMethodName ( CORINFO_METHOD_HANDLE ftn, /* IN */ const char **moduleName /* OUT */ diff --git a/src/coreclr/inc/jiteeversionguid.h b/src/coreclr/inc/jiteeversionguid.h index c003b6be776b20..68d305e4f5d5d8 100644 --- a/src/coreclr/inc/jiteeversionguid.h +++ b/src/coreclr/inc/jiteeversionguid.h @@ -43,11 +43,11 @@ typedef const GUID *LPCGUID; #define GUID_DEFINED #endif // !GUID_DEFINED -constexpr GUID JITEEVersionIdentifier = { /* 1b9551b8-21f4-4233-9c90-f3eabd6a322b */ - 0x1b9551b8, - 0x21f4, - 0x4233, - {0x9c, 0x90, 0xf3, 0xea, 0xbd, 0x6a, 0x32, 0x2b} +constexpr GUID JITEEVersionIdentifier = { /* 0cd8b9d4-04f4-45a7-b16b-7f24b7c0a454 */ + 0x0cd8b9d4, + 0x04f4, + 0x45a7, + {0xb1, 0x6b, 0x7f, 0x24, 0xb7, 0xc0, 0xa4, 0x54} }; ////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/src/coreclr/jit/compiler.cpp b/src/coreclr/jit/compiler.cpp index 1042c1800324f1..f05c4d0bc92cee 100644 --- a/src/coreclr/jit/compiler.cpp +++ b/src/coreclr/jit/compiler.cpp @@ -1769,6 +1769,7 @@ void Compiler::compInit(ArenaAllocator* pAlloc, info.compCompHnd = compHnd; info.compMethodHnd = methodHnd; info.compMethodInfo = methodInfo; + info.compClassHnd = compHnd->getMethodClass(methodHnd); #ifdef DEBUG bRangeAllowStress = false; @@ -1788,17 +1789,10 @@ void Compiler::compInit(ArenaAllocator* pAlloc, info.compClassName = nullptr; info.compFullName = nullptr; - const char* classNamePtr; - const char* methodName; - - methodName = eeGetMethodName(methodHnd, &classNamePtr); - unsigned len = (unsigned)roundUp(strlen(classNamePtr) + 1); - info.compClassName = getAllocator(CMK_DebugOnly).allocate(len); - info.compMethodName = methodName; - strcpy_s((char*)info.compClassName, len, classNamePtr); - - info.compFullName = eeGetMethodFullName(methodHnd); - info.compPerfScore = 0.0; + info.compMethodName = eeGetMethodName(methodHnd, nullptr); + info.compClassName = eeGetClassName(info.compClassHnd); + info.compFullName = eeGetMethodFullName(methodHnd); + info.compPerfScore = 0.0; info.compMethodSuperPMIIndex = g_jitHost->getIntConfigValue(W("SuperPMIMethodContextNumber"), -1); #endif // defined(DEBUG) || defined(LATE_DISASM) || DUMP_FLOWGRAPHS @@ -2534,7 +2528,7 @@ void Compiler::compInitOptions(JitFlags* jitFlags) if (opts.jitFlags->IsSet(JitFlags::JIT_FLAG_ALT_JIT)) { - if (pfAltJit->contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (pfAltJit->contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { opts.altJit = true; } @@ -2615,7 +2609,7 @@ void Compiler::compInitOptions(JitFlags* jitFlags) // if (compIsForImportOnly() && (!altJitConfig || opts.altJit)) { - if (JitConfig.JitImportBreak().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (JitConfig.JitImportBreak().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { assert(!"JitImportBreak reached"); } @@ -2630,7 +2624,7 @@ void Compiler::compInitOptions(JitFlags* jitFlags) // if (!compIsForInlining()) { - if (JitConfig.JitDump().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (JitConfig.JitDump().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { verboseDump = true; } @@ -2865,32 +2859,32 @@ void Compiler::compInitOptions(JitFlags* jitFlags) opts.dspOrder = true; } - if (JitConfig.JitGCDump().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (JitConfig.JitGCDump().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { opts.dspGCtbls = true; } - if (JitConfig.JitDisasm().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (JitConfig.JitDisasm().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { opts.disAsm = true; } - if (JitConfig.JitDisasm().contains("SPILLED", nullptr, nullptr)) + if (JitConfig.JitDisasmSpilled()) { opts.disAsmSpilled = true; } - if (JitConfig.JitUnwindDump().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (JitConfig.JitUnwindDump().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { opts.dspUnwind = true; } - if (JitConfig.JitEHDump().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (JitConfig.JitEHDump().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { opts.dspEHTable = true; } - if (JitConfig.JitDebugDump().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (JitConfig.JitDebugDump().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { opts.dspDebugInfo = true; } @@ -2928,7 +2922,7 @@ void Compiler::compInitOptions(JitFlags* jitFlags) opts.compLongAddress = true; } - if (JitConfig.JitOptRepeat().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (JitConfig.JitOptRepeat().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { opts.optRepeat = true; } @@ -2938,7 +2932,7 @@ void Compiler::compInitOptions(JitFlags* jitFlags) // JitEarlyExpandMDArraysFilter. if (JitConfig.JitEarlyExpandMDArrays() == 0) { - if (JitConfig.JitEarlyExpandMDArraysFilter().contains(info.compMethodName, info.compClassName, + if (JitConfig.JitEarlyExpandMDArraysFilter().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { opts.compJitEarlyExpandMDArrays = true; @@ -2979,7 +2973,7 @@ void Compiler::compInitOptions(JitFlags* jitFlags) printf(""); // in our logic this causes a flush } - if (JitConfig.JitBreak().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (JitConfig.JitBreak().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { assert(!"JitBreak reached"); } @@ -2991,8 +2985,8 @@ void Compiler::compInitOptions(JitFlags* jitFlags) } if (verbose || - JitConfig.JitDebugBreak().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args) || - JitConfig.JitBreak().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + JitConfig.JitDebugBreak().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args) || + JitConfig.JitBreak().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { compDebugBreak = true; } @@ -3011,14 +3005,9 @@ void Compiler::compInitOptions(JitFlags* jitFlags) s_pJitFunctionFileInitialized = true; } #else // DEBUG - if (!JitConfig.JitDisasm().isEmpty()) + if (JitConfig.JitDisasm().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { - const char* methodName = info.compCompHnd->getMethodName(info.compMethodHnd, nullptr); - const char* className = info.compCompHnd->getClassName(info.compClassHnd); - if (JitConfig.JitDisasm().contains(methodName, className, &info.compMethodInfo->args)) - { - opts.disAsm = true; - } + opts.disAsm = true; } #endif // !DEBUG @@ -3186,21 +3175,21 @@ void Compiler::compInitOptions(JitFlags* jitFlags) // JitForceProcedureSplitting is used to force procedure splitting on checked assemblies. // This is useful for debugging on a checked build. Note that we still only do procedure // splitting in the zapper. - if (JitConfig.JitForceProcedureSplitting().contains(info.compMethodName, info.compClassName, + if (JitConfig.JitForceProcedureSplitting().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { opts.compProcedureSplitting = true; } // JitNoProcedureSplitting will always disable procedure splitting. - if (JitConfig.JitNoProcedureSplitting().contains(info.compMethodName, info.compClassName, + if (JitConfig.JitNoProcedureSplitting().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { opts.compProcedureSplitting = false; } // // JitNoProcedureSplittingEH will disable procedure splitting in functions with EH. - if (JitConfig.JitNoProcedureSplittingEH().contains(info.compMethodName, info.compClassName, + if (JitConfig.JitNoProcedureSplittingEH().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { opts.compProcedureSplittingEH = false; @@ -3316,7 +3305,7 @@ bool Compiler::compJitHaltMethod() /* This method returns true when we use an INS_BREAKPOINT to allow us to step into the generated native code */ /* Note that this these two "Jit" environment variables also work for ngen images */ - if (JitConfig.JitHalt().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (JitConfig.JitHalt().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { return true; } @@ -3420,7 +3409,7 @@ bool Compiler::compStressCompileHelper(compStressArea stressArea, unsigned weigh } if (!JitConfig.JitStressOnly().isEmpty() && - !JitConfig.JitStressOnly().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + !JitConfig.JitStressOnly().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { return false; } @@ -3703,7 +3692,7 @@ void Compiler::compSetOptimizationLevel() if (!theMinOptsValue) { - if (JitConfig.JitMinOptsName().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (JitConfig.JitMinOptsName().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { theMinOptsValue = true; } @@ -4207,8 +4196,7 @@ const char* Compiler::compGetStressMessage() const { // Or is it excluded via name? if (!JitConfig.JitStressOnly().isEmpty() || - !JitConfig.JitStressOnly().contains(info.compMethodName, info.compClassName, - &info.compMethodInfo->args)) + !JitConfig.JitStressOnly().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { // Not excluded -- stress can happen stressMessage = " JitStress"; @@ -5000,7 +4988,8 @@ void Compiler::compCompile(void** methodCodePtr, uint32_t* methodCodeSize, JitFl #ifdef DEBUG const char* fullName = info.compFullName; #else - const char* fullName = eeGetMethodFullName(info.compMethodHnd); + const char* fullName = + eeGetMethodFullName(info.compMethodHnd, /* includeReturnType */ false, /* includeThisSpecifier */ false); #endif char debugPart[128] = {0}; @@ -5375,13 +5364,13 @@ bool Compiler::skipMethod() return true; } - if (JitConfig.JitExclude().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + if (JitConfig.JitExclude().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { return true; } if (!JitConfig.JitInclude().isEmpty() && - !JitConfig.JitInclude().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args)) + !JitConfig.JitInclude().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args)) { return true; } @@ -5687,9 +5676,7 @@ int Compiler::compCompile(CORINFO_MODULE_HANDLE classPtr, { impTokenLookupContextHandle = impInlineInfo->tokenLookupContextHandle; - assert(impInlineInfo->inlineCandidateInfo->clsHandle == info.compCompHnd->getMethodClass(info.compMethodHnd)); - info.compClassHnd = impInlineInfo->inlineCandidateInfo->clsHandle; - + assert(impInlineInfo->inlineCandidateInfo->clsHandle == info.compClassHnd); assert(impInlineInfo->inlineCandidateInfo->clsAttr == info.compCompHnd->getClassAttribs(info.compClassHnd)); // printf("%x != %x\n", impInlineInfo->inlineCandidateInfo->clsAttr, // info.compCompHnd->getClassAttribs(info.compClassHnd)); @@ -5699,7 +5686,6 @@ int Compiler::compCompile(CORINFO_MODULE_HANDLE classPtr, { impTokenLookupContextHandle = METHOD_BEING_COMPILED_CONTEXT(); - info.compClassHnd = info.compCompHnd->getMethodClass(info.compMethodHnd); info.compClassAttr = info.compCompHnd->getClassAttribs(info.compClassHnd); } diff --git a/src/coreclr/jit/compiler.h b/src/coreclr/jit/compiler.h index 03910bbb60340e..1da2267e5974e3 100644 --- a/src/coreclr/jit/compiler.h +++ b/src/coreclr/jit/compiler.h @@ -7564,10 +7564,31 @@ class Compiler var_types eeGetFieldType(CORINFO_FIELD_HANDLE fldHnd, CORINFO_CLASS_HANDLE* pStructHnd = nullptr); -#if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) || defined(TRACK_LSRA_STATS) + void eePrintJitType(class StringPrinter* printer, var_types jitType); + void eePrintType(class StringPrinter* printer, + CORINFO_CLASS_HANDLE clsHnd, + bool includeNamespaces, + bool includeInstantiation); + void eePrintTypeOrJitAlias(class StringPrinter* printer, + CORINFO_CLASS_HANDLE clsHnd, + bool includeNamespaces, + bool includeInstantiation); + void eePrintMethod(class StringPrinter* printer, + CORINFO_CLASS_HANDLE clsHnd, + CORINFO_METHOD_HANDLE methodHnd, + CORINFO_SIG_INFO* sig, + bool includeNamespaces, + bool includeClassInstantiation, + bool includeMethodInstantiation, + bool includeSignature, + bool includeReturnType, + bool includeThisSpecifier); +#if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) || defined(TRACK_LSRA_STATS) const char* eeGetMethodName(CORINFO_METHOD_HANDLE hnd, const char** className); - const char* eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd); + const char* eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd, + bool includeReturnType = true, + bool includeThisSpecifier = true); unsigned compMethodHash(CORINFO_METHOD_HANDLE methodHandle); bool eeIsNativeMethod(CORINFO_METHOD_HANDLE method); @@ -7793,6 +7814,12 @@ class Compiler return eeRunWithSPMIErrorTrapImp(reinterpret_cast(function), reinterpret_cast(param)); } + template + bool eeRunFunctorWithSPMIErrorTrap(Functor f) + { + return eeRunWithSPMIErrorTrap([](Functor* pf) { (*pf)(); }, &f); + } + bool eeRunWithSPMIErrorTrapImp(void (*function)(void*), void* param); // Utility functions @@ -11316,6 +11343,46 @@ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ +class StringPrinter +{ + CompAllocator m_alloc; + char* m_buffer; + size_t m_bufferMax; + size_t m_bufferIndex = 0; + +public: + StringPrinter(CompAllocator alloc, char* buffer = nullptr, size_t bufferMax = 0) + : m_alloc(alloc), m_buffer(buffer), m_bufferMax(bufferMax) + { + if ((m_buffer == nullptr) || (m_bufferMax == 0)) + { + m_bufferMax = 128; + m_buffer = alloc.allocate(m_bufferMax); + } + + m_buffer[0] = '\0'; + } + + size_t GetLength() + { + return m_bufferIndex; + } + + char* GetBuffer() + { + assert(m_buffer[GetLength()] == '\0'); + return m_buffer; + } + void Truncate(size_t newLength) + { + assert(newLength <= m_bufferIndex); + m_bufferIndex = newLength; + m_buffer[m_bufferIndex] = '\0'; + } + + void Printf(const char* format, ...); +}; + /***************************************************************************** * * Variables to keep track of total code amounts. diff --git a/src/coreclr/jit/ee_il_dll.cpp b/src/coreclr/jit/ee_il_dll.cpp index 7b5b2961510907..11cfc55305e97c 100644 --- a/src/coreclr/jit/ee_il_dll.cpp +++ b/src/coreclr/jit/ee_il_dll.cpp @@ -1506,25 +1506,24 @@ const char* Compiler::eeGetFieldName(CORINFO_FIELD_HANDLE field, const char** cl return param.fieldOrMethodOrClassNamePtr; } +//------------------------------------------------------------------------ +// eeGetClassName: +// Get the name (including namespace and instantiation) of a type. +// If missing information (in SPMI), then return a placeholder string. +// +// Return value: +// The name string. +// const char* Compiler::eeGetClassName(CORINFO_CLASS_HANDLE clsHnd) { - FilterSuperPMIExceptionsParam_ee_il param; - - param.pThis = this; - param.pJitInfo = &info; - param.clazz = clsHnd; - - bool success = eeRunWithSPMIErrorTrap( - [](FilterSuperPMIExceptionsParam_ee_il* pParam) { - pParam->fieldOrMethodOrClassNamePtr = pParam->pJitInfo->compCompHnd->getClassName(pParam->clazz); - }, - ¶m); - - if (!success) + StringPrinter printer(getAllocator(CMK_DebugOnly)); + if (!eeRunFunctorWithSPMIErrorTrap([&]() { eePrintType(&printer, clsHnd, true, true); })) { - param.fieldOrMethodOrClassNamePtr = "hackishClassName"; + printer.Truncate(0); + printer.Printf("hackishClassName"); } - return param.fieldOrMethodOrClassNamePtr; + + return printer.GetBuffer(); } #endif // DEBUG || FEATURE_JIT_METHOD_PERF diff --git a/src/coreclr/jit/eeinterface.cpp b/src/coreclr/jit/eeinterface.cpp index 60c685e142b35a..df3a65af43be6d 100644 --- a/src/coreclr/jit/eeinterface.cpp +++ b/src/coreclr/jit/eeinterface.cpp @@ -19,228 +19,327 @@ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX #pragma hdrstop #endif -#if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) +//------------------------------------------------------------------------ +// StringPrinter::Printf: +// Print a formatted string. +// +// Arguments: +// format - the format +// +void StringPrinter::Printf(const char* format, ...) +{ + va_list args; + va_start(args, format); -/*****************************************************************************/ + while (true) + { + size_t bufferLeft = m_bufferMax - m_bufferIndex; + assert(bufferLeft >= 1); // always fit null terminator + + va_list argsCopy; + va_copy(argsCopy, args); + int printed = _vsnprintf_s(m_buffer + m_bufferIndex, bufferLeft, _TRUNCATE, format, argsCopy); + va_end(argsCopy); + + if (printed < 0) + { + // buffer too small + size_t newSize = m_bufferMax * 2; + char* newBuffer = m_alloc.allocate(newSize); + memcpy(newBuffer, m_buffer, m_bufferIndex + 1); // copy null terminator too -/***************************************************************************** - * - * Filter wrapper to handle exception filtering. - * On Unix compilers don't support SEH. - */ + m_buffer = newBuffer; + m_bufferMax = newSize; + } + else + { + m_bufferIndex = m_bufferIndex + static_cast(printed); + break; + } + } + + va_end(args); +} -struct FilterSuperPMIExceptionsParam_eeinterface +#if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) + +//------------------------------------------------------------------------ +// eePrintJitType: +// Print a JIT type. +// +// Arguments: +// printer - the printer +// jitType - the JIT type +// +void Compiler::eePrintJitType(StringPrinter* printer, var_types jitType) { - Compiler* pThis; - Compiler::Info* pJitInfo; - bool hasThis; - size_t siglength; - CORINFO_SIG_INFO sig; - CORINFO_ARG_LIST_HANDLE argLst; - CORINFO_METHOD_HANDLE hnd; - const char* returnType; - const char** pArgNames; - EXCEPTION_POINTERS exceptionPointers; -}; - -const char* Compiler::eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd) + printer->Printf("%s", varTypeName(jitType)); +} + +//------------------------------------------------------------------------ +// eePrintType: +// Print a type given by a class handle. +// +// Arguments: +// printer - the printer +// clsHnd - Handle for the class +// includeNamespace - Whether to print namespaces before type names +// includeInstantiation - Whether to print the instantiation of the class +// +void Compiler::eePrintType(StringPrinter* printer, + CORINFO_CLASS_HANDLE clsHnd, + bool includeNamespace, + bool includeInstantiation) { - const char* className; - const char* methodName = eeGetMethodName(hnd, &className); - if ((eeGetHelperNum(hnd) != CORINFO_HELP_UNDEF) || eeIsNativeMethod(hnd)) + const char* namespaceName; + const char* className = info.compCompHnd->getClassNameFromMetadata(clsHnd, &namespaceName); + if (className == nullptr) { - return methodName; + namespaceName = nullptr; + className = ""; + } + + if (includeNamespace && (namespaceName != nullptr) && (namespaceName[0] != '\0')) + { + printer->Printf("%s.", namespaceName); } - FilterSuperPMIExceptionsParam_eeinterface param; - param.returnType = nullptr; - param.pThis = this; - param.hasThis = false; - param.siglength = 0; - param.hnd = hnd; - param.pJitInfo = &info; + printer->Printf("%s", className); + + if (!includeInstantiation) + { + return; + } - size_t length = 0; - unsigned i; + char pref = '['; + for (unsigned typeArgIndex = 0;; typeArgIndex++) + { + CORINFO_CLASS_HANDLE typeArg = info.compCompHnd->getTypeInstantiationArgument(clsHnd, typeArgIndex); - /* Generating the full signature is a two-pass process. First we have to walk - the components in order to assess the total size, then we allocate the buffer - and copy the elements into it. - */ + if (typeArg == NO_CLASS_HANDLE) + { + break; + } - /* Right now there is a race-condition in the EE, className can be nullptr */ + printer->Printf("%c", pref); + pref = ','; + eePrintTypeOrJitAlias(printer, typeArg, includeNamespace, true); + } - /* initialize length with length of className and '.' */ + if (pref != '[') + { + printer->Printf("]"); + } +} - if (className) +//------------------------------------------------------------------------ +// eePrintTypeOrJitAlias: +// Print a type given by a class handle. If the type is a primitive type, +// prints its JIT alias. +// +// Arguments: +// printer - the printer +// clsHnd - Handle for the class +// includeNamespace - Whether to print namespaces before type names +// includeInstantiation - Whether to print the instantiation of the class +// +void Compiler::eePrintTypeOrJitAlias(StringPrinter* printer, + CORINFO_CLASS_HANDLE clsHnd, + bool includeNamespace, + bool includeInstantiation) +{ + CorInfoType typ = info.compCompHnd->asCorInfoType(clsHnd); + if ((typ == CORINFO_TYPE_CLASS) || (typ == CORINFO_TYPE_VALUECLASS)) { - length = strlen(className) + 1; + eePrintType(printer, clsHnd, includeNamespace, includeInstantiation); } else { - assert(strlen(".") == 7); - length = 7; + eePrintJitType(printer, JitType2PreciseVarType(typ)); } +} - /* add length of methodName and opening bracket */ - length += strlen(methodName) + 1; - - bool success = eeRunWithSPMIErrorTrap( - [](FilterSuperPMIExceptionsParam_eeinterface* pParam) { - - /* figure out the signature */ - - pParam->pThis->eeGetMethodSig(pParam->hnd, &pParam->sig); +//------------------------------------------------------------------------ +// eePrintMethod: +// Print a method given by a method handle, its owning class handle and its +// signature. +// +// Arguments: +// printer - the printer +// clsHnd - Handle for the owning class, or NO_CLASS_HANDLE to not print the class. +// sig - The signature of the method. +// includeNamespaces - Whether to print namespaces before type names. +// includeClassInstantiation - Whether to print the class instantiation. Only valid when clsHnd is passed. +// includeMethodInstantiation - Whether to print the method instantiation. Requires the signature to be passed. +// includeSignature - Whether to print the signature. +// includeReturnType - Whether to include the return type at the end. +// includeThisSpecifier - Whether to include a specifier at the end for whether the method is an instance +// method. +// +void Compiler::eePrintMethod(StringPrinter* printer, + CORINFO_CLASS_HANDLE clsHnd, + CORINFO_METHOD_HANDLE methHnd, + CORINFO_SIG_INFO* sig, + bool includeNamespaces, + bool includeClassInstantiation, + bool includeMethodInstantiation, + bool includeSignature, + bool includeReturnType, + bool includeThisSpecifier) +{ + if (clsHnd != NO_CLASS_HANDLE) + { + eePrintType(printer, clsHnd, includeNamespaces, includeClassInstantiation); + printer->Printf(":"); + } - // allocate space to hold the class names for each of the parameters + const char* methName = info.compCompHnd->getMethodName(methHnd, nullptr); + printer->Printf("%s", methName); - if (pParam->sig.numArgs > 0) - { - pParam->pArgNames = - pParam->pThis->getAllocator(CMK_DebugOnly).allocate(pParam->sig.numArgs); - } - else + if (includeMethodInstantiation && (sig->sigInst.methInstCount > 0)) + { + printer->Printf("["); + for (unsigned i = 0; i < sig->sigInst.methInstCount; i++) + { + if (i > 0) { - pParam->pArgNames = nullptr; + printer->Printf(","); } - unsigned i; - pParam->argLst = pParam->sig.args; + eePrintTypeOrJitAlias(printer, sig->sigInst.methInst[i], includeNamespaces, true); + } + printer->Printf("]"); + } + + if (includeSignature) + { + printer->Printf("("); - for (i = 0; i < pParam->sig.numArgs; i++) + CORINFO_ARG_LIST_HANDLE argLst = sig->args; + for (unsigned i = 0; i < sig->numArgs; i++) + { + if (i > 0) + printer->Printf(","); + + CORINFO_CLASS_HANDLE vcClsHnd; + var_types type = JitType2PreciseVarType(strip(info.compCompHnd->getArgType(sig, argLst, &vcClsHnd))); + switch (type) { - var_types type = pParam->pThis->eeGetArgType(pParam->argLst, &pParam->sig); - switch (type) + case TYP_REF: + case TYP_STRUCT: { - case TYP_REF: - case TYP_STRUCT: + CORINFO_CLASS_HANDLE clsHnd = eeGetArgClass(sig, argLst); + // For some SIMD struct types we can get a nullptr back from eeGetArgClass on Linux/X64 + if (clsHnd != NO_CLASS_HANDLE) { - CORINFO_CLASS_HANDLE clsHnd = pParam->pThis->eeGetArgClass(&pParam->sig, pParam->argLst); - // For some SIMD struct types we can get a nullptr back from eeGetArgClass on Linux/X64 - if (clsHnd != NO_CLASS_HANDLE) - { - const char* clsName = pParam->pThis->eeGetClassName(clsHnd); - if (clsName != nullptr) - { - pParam->pArgNames[i] = clsName; - break; - } - } - } - FALLTHROUGH; - default: - pParam->pArgNames[i] = varTypeName(type); + eePrintType(printer, clsHnd, includeNamespaces, true); break; + } } - pParam->siglength += strlen(pParam->pArgNames[i]); - pParam->argLst = pParam->pJitInfo->compCompHnd->getArgNext(pParam->argLst); + + FALLTHROUGH; + default: + eePrintJitType(printer, type); + break; } - /* add ',' if there is more than one argument */ + argLst = info.compCompHnd->getArgNext(argLst); + } - if (pParam->sig.numArgs > 1) - { - pParam->siglength += (pParam->sig.numArgs - 1); - } + printer->Printf(")"); - var_types retType = JITtype2varType(pParam->sig.retType); + if (includeReturnType) + { + var_types retType = JitType2PreciseVarType(sig->retType); if (retType != TYP_VOID) { + printer->Printf(":"); switch (retType) { case TYP_REF: case TYP_STRUCT: { - CORINFO_CLASS_HANDLE clsHnd = pParam->sig.retTypeClass; + CORINFO_CLASS_HANDLE clsHnd = sig->retTypeClass; if (clsHnd != NO_CLASS_HANDLE) { - const char* clsName = pParam->pThis->eeGetClassName(clsHnd); - if (clsName != nullptr) - { - pParam->returnType = clsName; - break; - } + eePrintType(printer, clsHnd, includeNamespaces, true); + break; } } FALLTHROUGH; default: - pParam->returnType = varTypeName(retType); + eePrintJitType(printer, retType); break; } - pParam->siglength += strlen(pParam->returnType) + 1; // don't forget the delimiter ':' - } - - // Does it have a 'this' pointer? Don't count explicit this, which has the this pointer type as the first - // element of the arg type list - if (pParam->sig.hasThis() && !pParam->sig.hasExplicitThis()) - { - assert(strlen(":this") == 5); - pParam->siglength += 5; - pParam->hasThis = true; } - }, - ¶m); + } - if (!success) - { - param.siglength = 0; + // Does it have a 'this' pointer? Don't count explicit this, which has + // the this pointer type as the first element of the arg type list + if (includeThisSpecifier && sig->hasThis() && !sig->hasExplicitThis()) + { + printer->Printf(":this"); + } } +} - /* add closing bracket and null terminator */ - - length += param.siglength + 2; - - char* retName = getAllocator(CMK_DebugOnly).allocate(length); - - /* Now generate the full signature string in the allocated buffer */ - - if (className) - { - strcpy_s(retName, length, className); - strcat_s(retName, length, ":"); - } - else +//------------------------------------------------------------------------ +// eeGetMethodFullName: +// Get a string describing a method. +// +// Arguments: +// hnd - the method handle +// includeReturnType - Whether to include the return type in the string +// includeThisSpecifier - Whether to include a specifier for whether this is an instance method. +// +// Returns: +// The string. +// +const char* Compiler::eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd, bool includeReturnType, bool includeThisSpecifier) +{ + const char* className; + const char* methodName = eeGetMethodName(hnd, &className); + if ((eeGetHelperNum(hnd) != CORINFO_HELP_UNDEF) || eeIsNativeMethod(hnd)) { - strcpy_s(retName, length, "."); + return methodName; } - strcat_s(retName, length, methodName); + StringPrinter p(getAllocator(CMK_DebugOnly)); + CORINFO_CLASS_HANDLE clsHnd = NO_CLASS_HANDLE; + bool success = eeRunFunctorWithSPMIErrorTrap([&]() { + clsHnd = info.compCompHnd->getMethodClass(hnd); + CORINFO_SIG_INFO sig; + eeGetMethodSig(hnd, &sig); + eePrintMethod(&p, clsHnd, hnd, &sig, + /* includeNamespaces */ true, + /* includeClassInstantiation */ true, + /* includeMethodInstantiation */ true, + /* includeSignature */ true, includeReturnType, includeThisSpecifier); - // append the signature - strcat_s(retName, length, "("); + }); - if (param.siglength > 0) + if (!success) { - param.argLst = param.sig.args; - - for (i = 0; i < param.sig.numArgs; i++) + // Try with bare minimum + p.Truncate(0); + + success = eeRunFunctorWithSPMIErrorTrap([&]() { + eePrintMethod(&p, clsHnd, hnd, + /* sig */ nullptr, + /* includeNamespaces */ true, + /* includeClassInstantiation */ false, + /* includeMethodInstantiation */ false, + /* includeSignature */ false, includeReturnType, includeThisSpecifier); + }); + + if (!success) { - var_types type = eeGetArgType(param.argLst, ¶m.sig); - strcat_s(retName, length, param.pArgNames[i]); - param.argLst = info.compCompHnd->getArgNext(param.argLst); - if (i + 1 < param.sig.numArgs) - { - strcat_s(retName, length, ","); - } + p.Truncate(0); + p.Printf("hackishClassName:hackishMethodName(?)"); } } - strcat_s(retName, length, ")"); - - if (param.returnType != nullptr) - { - strcat_s(retName, length, ":"); - strcat_s(retName, length, param.returnType); - } - - if (param.hasThis) - { - strcat_s(retName, length, ":this"); - } - - assert(strlen(retName) == (length - 1)); - - return (retName); + return p.GetBuffer(); } #endif // defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) diff --git a/src/coreclr/jit/fgdiagnostic.cpp b/src/coreclr/jit/fgdiagnostic.cpp index b083f7869d2633..73445b88d223da 100644 --- a/src/coreclr/jit/fgdiagnostic.cpp +++ b/src/coreclr/jit/fgdiagnostic.cpp @@ -467,7 +467,7 @@ FILE* Compiler::fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, PhasePositi } #ifdef DEBUG - dumpFunction = JitConfig.JitDumpFg().contains(info.compMethodName, info.compClassName, &info.compMethodInfo->args); + dumpFunction = JitConfig.JitDumpFg().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args); filename = JitConfig.JitDumpFgFile(); pathname = JitConfig.JitDumpFgDir(); diff --git a/src/coreclr/jit/fginline.cpp b/src/coreclr/jit/fginline.cpp index d0b29da3ca0795..1deb759ac46c88 100644 --- a/src/coreclr/jit/fginline.cpp +++ b/src/coreclr/jit/fginline.cpp @@ -663,8 +663,8 @@ PhaseStatus Compiler::fgInline() } #ifdef DEBUG - fgPrintInlinedMethods = JitConfig.JitPrintInlinedMethods().contains(info.compMethodName, info.compClassName, - &info.compMethodInfo->args); + fgPrintInlinedMethods = + JitConfig.JitPrintInlinedMethods().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args); #endif // DEBUG noway_assert(fgFirstBB != nullptr); diff --git a/src/coreclr/jit/importer.cpp b/src/coreclr/jit/importer.cpp index 5e85743da45b4b..a4be1332525f0e 100644 --- a/src/coreclr/jit/importer.cpp +++ b/src/coreclr/jit/importer.cpp @@ -21611,8 +21611,8 @@ void Compiler::impDevirtualizeCall(GenTreeCall* call, // Optionally, print info on devirtualization Compiler* const rootCompiler = impInlineRoot(); - const bool doPrint = JitConfig.JitPrintDevirtualizedMethods().contains(rootCompiler->info.compMethodName, - rootCompiler->info.compClassName, + const bool doPrint = JitConfig.JitPrintDevirtualizedMethods().contains(rootCompiler->info.compMethodHnd, + rootCompiler->info.compClassHnd, &rootCompiler->info.compMethodInfo->args); #endif // DEBUG diff --git a/src/coreclr/jit/jitconfig.cpp b/src/coreclr/jit/jitconfig.cpp index cd65af36f106e9..7e055f0726bb93 100644 --- a/src/coreclr/jit/jitconfig.cpp +++ b/src/coreclr/jit/jitconfig.cpp @@ -36,272 +36,51 @@ void JitConfigValues::MethodSet::initialize(const WCHAR* list, ICorJitHost* host } } - const char SEP_CHAR = ' '; // character used to separate each entry - const char WILD_CHAR = '*'; // character used as the wildcard match everything - char currChar = '?'; // The current character - int nameStart = -1; // Index of the start of the current class or method name - MethodName** lastName = &m_names; // Last entry inserted into the list - bool isQuoted = false; // true while parsing inside a quote "this-is-a-quoted-region" - MethodName currentName; // Buffer used while parsing the current entry - - currentName.m_next = nullptr; - currentName.m_methodNameStart = -1; - currentName.m_methodNameLen = -1; - currentName.m_methodNameWildcardAtStart = false; - currentName.m_methodNameWildcardAtEnd = false; - currentName.m_classNameStart = -1; - currentName.m_classNameLen = -1; - currentName.m_classNameWildcardAtEnd = false; - currentName.m_numArgs = -1; - - enum State - { - NO_NAME, - CLS_NAME, - FUNC_NAME, - ARG_LIST - }; // parsing state machine - - State state = NO_NAME; - for (int i = 0; (currChar != '\0'); i++) - { - currChar = m_list[i]; + auto commitPattern = [this, host](const char* start, const char* end) { + if (end <= start) + { + return; + } + + MethodName* name = static_cast(host->allocateMemory(sizeof(MethodName))); + name->m_next = m_names; + name->m_patternStart = start; + name->m_patternEnd = end; + const char* colon = static_cast(memchr(start, ':', end - start)); + const char* startOfMethodName = colon != nullptr ? colon + 1 : start; + + const char* parens = static_cast(memchr(startOfMethodName, '(', end - startOfMethodName)); + const char* endOfMethodName = parens != nullptr ? parens : end; + name->m_methodNameContainsInstantiation = + memchr(startOfMethodName, '[', endOfMethodName - startOfMethodName) != nullptr; - switch (state) + if (colon != nullptr) { - case NO_NAME: - // skip over zero or more blanks, then expect CLS_NAME - if (currChar != SEP_CHAR) - { - nameStart = i; - state = CLS_NAME; // we have found the start of the next entry - } - break; - - case CLS_NAME: - // Check for a quoted Class Name: (i.e. "MyClass") - if (m_list[nameStart] == '"') - { - // Advance until we see the second " - // - for (; (currChar != '\0'); i++) - { - currChar = m_list[i]; - // Advance until we see the second " - if (currChar == '"') - { - break; - } - // or until we see the end of string - if (currChar == '\0') - { - break; - } - } - - // skip the initial " - nameStart++; - isQuoted = true; - } - - // A colon denotes the end of the Class name and the start of the Method name - if (currChar == ':') - { - // Record the class name - currentName.m_classNameStart = nameStart; - currentName.m_classNameLen = i - nameStart; - - // Also accept the double colon syntax as well (i.e class::method) - // - if (m_list[i + 1] == ':') - { - i++; - } - - if (isQuoted) - { - // Remove the trailing " - currentName.m_classNameLen--; - isQuoted = false; - } - - // Is the first character a wildcard? - if (m_list[currentName.m_classNameStart] == WILD_CHAR) - { - // The class name is a full wildcard; mark it as such. - currentName.m_classNameStart = -1; - currentName.m_classNameLen = -1; - } - // Is there a wildcard at the end of the class name? - // - else if (m_list[currentName.m_classNameStart + currentName.m_classNameLen - 1] == WILD_CHAR) - { - // i.e. bar*:method, will match any class that starts with "bar" - - // Remove the trailing WILD_CHAR from class name - currentName.m_classNameWildcardAtEnd = true; - currentName.m_classNameLen--; // backup for WILD_CHAR - } - - // The method name will start at the next character - nameStart = i + 1; - - // Now expect FUNC_NAME - state = FUNC_NAME; - } - else if ((currChar == '\0') || (currChar == SEP_CHAR) || (currChar == '(')) - { - // Treat this as a method name without a class name. - currentName.m_classNameStart = -1; - currentName.m_classNameLen = -1; - goto DONE_FUNC_NAME; - } - break; - - case FUNC_NAME: - // Check for a quoted method name: i.e. className:"MyFunc" - // - // Note that we may have already parsed a quoted string above in CLS_NAME, i.e. "Func": - if (!isQuoted && (m_list[nameStart] == '"')) - { - // Advance until we see the second " - // - for (; (currChar != '\0'); i++) - { - currChar = m_list[i]; - // Advance until we see the second " - if (currChar == '"') - { - break; - } - // or until we see the end of string - if (currChar == '\0') - { - break; - } - } - - // skip the initial " - nameStart++; - isQuoted = true; - } - - if ((currChar == '\0') || (currChar == SEP_CHAR) || (currChar == '(')) - { - DONE_FUNC_NAME: - assert((currChar == '\0') || (currChar == SEP_CHAR) || (currChar == '(')); - - // Record the method name - currentName.m_methodNameStart = nameStart; - currentName.m_methodNameLen = i - nameStart; - - if (isQuoted) - { - // Remove the trailing " - currentName.m_methodNameLen--; - isQuoted = false; - } - - // Is the first character a wildcard? - if (m_list[currentName.m_methodNameStart] == WILD_CHAR && currentName.m_methodNameLen == 1) - { - // The method name is a full wildcard; mark it as such. - currentName.m_methodNameStart = -1; - currentName.m_methodNameLen = -1; - } - else - { - // Is there a wildcard at the start of the method name? - if (m_list[currentName.m_methodNameStart] == WILD_CHAR) - { - // i.e. class:*foo, will match any method that ends with "foo" - // Remove the leading WILD_CHAR from method name - currentName.m_methodNameStart++; - currentName.m_methodNameLen--; - currentName.m_methodNameWildcardAtStart = true; - } - // Is there a wildcard at the end of the method name? - if (m_list[currentName.m_methodNameStart + currentName.m_methodNameLen - 1] == WILD_CHAR) - { - // i.e. class:foo*, will match any method that starts with "foo" - // Remove the trailing WILD_CHAR from method name - currentName.m_methodNameLen--; // backup for WILD_CHAR - currentName.m_methodNameWildcardAtEnd = true; - } - } - - // should we expect an ARG_LIST? - // - if (currChar == '(') - { - currentName.m_numArgs = -1; - // Expect an ARG_LIST - state = ARG_LIST; - } - else // reached the end of string or a SEP_CHAR - { - assert((currChar == '\0') || (currChar == SEP_CHAR)); - - currentName.m_numArgs = -1; - - // There isn't an ARG_LIST - goto DONE_ARG_LIST; - } - } - break; - - case ARG_LIST: - if ((currChar == '\0') || (currChar == ')')) - { - if (currentName.m_numArgs == -1) - { - currentName.m_numArgs = 0; - } - - DONE_ARG_LIST: - assert((currChar == '\0') || (currChar == SEP_CHAR) || (currChar == ')')); - - // We have parsed an entire method name; create a new entry in the list for it. - MethodName* name = static_cast(host->allocateMemory(sizeof(MethodName))); - *name = currentName; - - assert(name->m_next == nullptr); - *lastName = name; - lastName = &name->m_next; - - state = NO_NAME; - - // Skip anything after the argument list until we find the next - // separator character. Otherwise if we see "func(a,b):foo" we - // would create entries for "func(a,b)" as well as ":foo". - if (currChar == ')') - { - do - { - currChar = m_list[++i]; - } while ((currChar != '\0') && (currChar != SEP_CHAR)); - } - } - else // We are looking at the ARG_LIST - { - if ((currChar != SEP_CHAR) && (currentName.m_numArgs == -1)) - { - currentName.m_numArgs = 1; - } - - // A comma means that there is an additional arg - if (currChar == ',') - { - currentName.m_numArgs++; - } - } - break; - - default: - assert(!"Bad state"); - break; + name->m_containsClassName = true; + name->m_classNameContainsInstantiation = memchr(start, '[', colon - start) != nullptr; + } + else + { + name->m_containsClassName = false; + name->m_classNameContainsInstantiation = false; + } + + name->m_containsSignature = parens != nullptr; + m_names = name; + }; + + const char* curPatternStart = m_list; + const char* curChar; + for (curChar = curPatternStart; *curChar != '\0'; curChar++) + { + if (*curChar == ' ') + { + commitPattern(curPatternStart, curChar); + curPatternStart = curChar + 1; } } + + commitPattern(curPatternStart, curChar); } void JitConfigValues::MethodSet::destroy(ICorJitHost* host) @@ -320,108 +99,91 @@ void JitConfigValues::MethodSet::destroy(ICorJitHost* host) m_names = nullptr; } -// strstr that is length-limited, this implementation is not intended to be used on hot paths -static size_t strnstr(const char* pSrc, size_t srcSize, const char* needle, size_t needleSize) +// Quadratic string matching algorithm that supports * and ? wildcards +static bool matchGlob(const char* pattern, const char* patternEnd, const char* str) { - if (srcSize < needleSize) - { - return -1; - } + // Invariant: [patternStart..backtrackPattern) matches [stringStart..backtrackStr) + const char* backtrackPattern = nullptr; + const char* backtrackStr = nullptr; - for (size_t srcPos = 0; srcPos <= srcSize - needleSize; srcPos++) + while (true) { - if (strncmp(pSrc + srcPos, needle, needleSize) == 0) + if (pattern == patternEnd) { - return srcPos; + if (*str == '\0') + return true; + } + else if (*pattern == '*') + { + backtrackPattern = ++pattern; + backtrackStr = str; + continue; + } + else if (*str == '\0') + { + // No match since pattern needs at least one char in remaining cases. + } + else if ((*pattern == '?') || (*pattern == *str)) + { + pattern++; + str++; + continue; } - } - return -1; -} -static bool matchesName( - const char* const name, int nameLen, bool wildcardAtStart, bool wildcardAtEnd, const char* const s2) -{ - if (wildcardAtStart && (int)strnstr(s2, strlen(s2), name, nameLen) == -1) - { - return false; - } + // In this case there was no match, see if we can backtrack to a wild + // card and consume one more character from the string. + if ((backtrackPattern == nullptr) || (*backtrackStr == '\0')) + return false; - if (!wildcardAtStart && strncmp(name, s2, nameLen) != 0) - { - // 's2' must start with 'nameLen' characters of 'name' - return false; + // Consume one more character for the wildcard. + pattern = backtrackPattern; + str = ++backtrackStr; } +} - // if we don't have a wildcardAtEnd then s2 also need to be zero terminated - if (!wildcardAtEnd && (s2[nameLen] != '\0')) +bool JitConfigValues::MethodSet::contains(CORINFO_METHOD_HANDLE methodHnd, + CORINFO_CLASS_HANDLE classHnd, + CORINFO_SIG_INFO* sigInfo) const +{ + if (isEmpty()) { return false; } - // we have a successful match - return true; -} - -bool JitConfigValues::MethodSet::contains(const char* methodName, - const char* className, - CORINFO_SIG_INFO* sigInfo) const -{ - int numArgs = sigInfo != nullptr ? sigInfo->numArgs : -1; + Compiler* comp = JitTls::GetCompiler(); + char buffer[1024]; + StringPrinter printer(comp->getAllocator(CMK_DebugOnly), buffer, ArrLen(buffer)); + MethodName* prevPattern = nullptr; - // Try to match any the entries in the list. for (MethodName* name = m_names; name != nullptr; name = name->m_next) { - // If m_numArgs is valid, check for a mismatch - if (name->m_numArgs != -1 && name->m_numArgs != numArgs) - { - continue; - } - - // If m_methodNameStart is valid, check for a mismatch - if (name->m_methodNameStart != -1) + if ((prevPattern == nullptr) || (name->m_containsClassName != prevPattern->m_containsClassName) || + (name->m_classNameContainsInstantiation != prevPattern->m_classNameContainsInstantiation) || + (name->m_methodNameContainsInstantiation != prevPattern->m_methodNameContainsInstantiation) || + (name->m_containsSignature != prevPattern->m_containsSignature)) { - const char* expectedMethodName = &m_list[name->m_methodNameStart]; - if (!matchesName(expectedMethodName, name->m_methodNameLen, name->m_methodNameWildcardAtStart, - name->m_methodNameWildcardAtEnd, methodName)) - { - // C++ embeds the class name into the method name; deal with that here. - const char* colon = strchr(methodName, ':'); - if (colon != nullptr && colon[1] == ':' && - matchesName(expectedMethodName, name->m_methodNameLen, name->m_methodNameWildcardAtStart, - name->m_methodNameWildcardAtEnd, methodName)) - { - int classLen = (int)(colon - methodName); - if (name->m_classNameStart == -1 || - (classLen == name->m_classNameLen && - strncmp(&m_list[name->m_classNameStart], methodName, classLen) == 0)) - { - return true; - } - } + printer.Truncate(0); + bool success = comp->eeRunFunctorWithSPMIErrorTrap([&]() { + comp->eePrintMethod(&printer, name->m_containsClassName ? classHnd : NO_CLASS_HANDLE, methodHnd, + sigInfo, + /* includeNamespaces */ true, + /* includeClassInstantiation */ name->m_classNameContainsInstantiation, + /* includeMethodInstantiation */ name->m_methodNameContainsInstantiation, + /* includeSignature */ name->m_containsSignature, + /* includeReturnType */ false, + /* includeThis */ false); + }); + + if (!success) continue; - } - } - // If m_classNameStart is valid, check for a mismatch - if (className == nullptr || name->m_classNameStart == -1 || - matchesName(&m_list[name->m_classNameStart], name->m_classNameLen, false, false, className)) - { - return true; + prevPattern = name; } -#ifdef _DEBUG - // Maybe className doesn't include the namespace. Try to match that - const char* nsSep = strrchr(className, '.'); - if (nsSep != nullptr && nsSep != className) + if (matchGlob(name->m_patternStart, name->m_patternEnd, printer.GetBuffer())) { - const char* onlyClass = nsSep[-1] == '.' ? nsSep : &nsSep[1]; - if (matchesName(&m_list[name->m_classNameStart], name->m_classNameLen, false, - name->m_classNameWildcardAtEnd, onlyClass)) - { - return true; - } + return true; } -#endif } return false; diff --git a/src/coreclr/jit/jitconfig.h b/src/coreclr/jit/jitconfig.h index 90f3daf9f63174..e19021cd52f22b 100644 --- a/src/coreclr/jit/jitconfig.h +++ b/src/coreclr/jit/jitconfig.h @@ -7,6 +7,8 @@ #include "switches.h" struct CORINFO_SIG_INFO; +typedef struct CORINFO_CLASS_STRUCT_* CORINFO_CLASS_HANDLE; +typedef struct CORINFO_METHOD_STRUCT_* CORINFO_METHOD_HANDLE; class ICorJitHost; class JitConfigValues @@ -18,14 +20,12 @@ class JitConfigValues struct MethodName { MethodName* m_next; - int m_methodNameStart; - int m_methodNameLen; - bool m_methodNameWildcardAtStart; - bool m_methodNameWildcardAtEnd; - int m_classNameStart; - int m_classNameLen; - bool m_classNameWildcardAtEnd; - int m_numArgs; + const char* m_patternStart; + const char* m_patternEnd; + bool m_containsClassName; + bool m_classNameContainsInstantiation; + bool m_methodNameContainsInstantiation; + bool m_containsSignature; }; char* m_list; @@ -51,7 +51,7 @@ class JitConfigValues { return m_names == nullptr; } - bool contains(const char* methodName, const char* className, CORINFO_SIG_INFO* sigInfo) const; + bool contains(CORINFO_METHOD_HANDLE methodHnd, CORINFO_CLASS_HANDLE classHnd, CORINFO_SIG_INFO* sigInfo) const; }; private: diff --git a/src/coreclr/jit/jitconfigvalues.h b/src/coreclr/jit/jitconfigvalues.h index fd32276e8b5cff..5690f7a4cdc7ac 100644 --- a/src/coreclr/jit/jitconfigvalues.h +++ b/src/coreclr/jit/jitconfigvalues.h @@ -190,10 +190,11 @@ CONFIG_STRING(JitDisasmAssemblies, W("JitDisasmAssemblies")) // Only show JitDis CONFIG_INTEGER(JitDisasmWithGC, W("JitDisasmWithGC"), 0) // Dump interleaved GC Info for any method disassembled. CONFIG_INTEGER(JitDisasmWithDebugInfo, W("JitDisasmWithDebugInfo"), 0) // Dump interleaved debug info for any method // disassembled. -CONFIG_METHODSET(JitDump, W("JitDump")) // Dumps trees for specified method -CONFIG_INTEGER(JitDumpTier0, W("JitDumpTier0"), 1) // Dump tier0 requests -CONFIG_INTEGER(JitDumpAtOSROffset, W("JitDumpAtOSROffset"), -1) // Only dump OSR requests for this offset -CONFIG_INTEGER(JitDumpInlinePhases, W("JitDumpInlinePhases"), 1) // Dump inline compiler phases +CONFIG_INTEGER(JitDisasmSpilled, W("JitDisasmSpilled"), 0) // Display native code when any register spilling occurs +CONFIG_METHODSET(JitDump, W("JitDump")) // Dumps trees for specified method +CONFIG_INTEGER(JitDumpTier0, W("JitDumpTier0"), 1) // Dump tier0 requests +CONFIG_INTEGER(JitDumpAtOSROffset, W("JitDumpAtOSROffset"), -1) // Only dump OSR requests for this offset +CONFIG_INTEGER(JitDumpInlinePhases, W("JitDumpInlinePhases"), 1) // Dump inline compiler phases CONFIG_METHODSET(JitEHDump, W("JitEHDump")) // Dump the EH table for the method, as reported to the VM CONFIG_METHODSET(JitExclude, W("JitExclude")) CONFIG_INTEGER(JitFakeProcedureSplitting, W("JitFakeProcedureSplitting"), 0) // Do code splitting independent of VM. diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs index c5f6ba41139354..14846a61a087b7 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs @@ -770,27 +770,25 @@ private void Get_CORINFO_SIG_INFO(MethodDesc method, CORINFO_SIG_INFO* sig, Meth if (method.IsArrayAddressMethod()) hasHiddenParameter = true; - - // We only populate sigInst for intrinsic methods because most of the time, - // JIT doesn't care what the instantiation is and this is expensive. - Instantiation owningTypeInst = method.OwningType.Instantiation; - sig->sigInst.classInstCount = (uint)owningTypeInst.Length; - if (owningTypeInst.Length != 0) - { - sig->sigInst.classInst = GetJitInstantiation(owningTypeInst); - } - - sig->sigInst.methInstCount = (uint)method.Instantiation.Length; - if (method.Instantiation.Length != 0) - { - sig->sigInst.methInst = GetJitInstantiation(method.Instantiation); - } } if (hasHiddenParameter) { sig->callConv |= CorInfoCallConv.CORINFO_CALLCONV_PARAMTYPE; } + + Instantiation owningTypeInst = method.OwningType.Instantiation; + sig->sigInst.classInstCount = (uint)owningTypeInst.Length; + if (owningTypeInst.Length != 0) + { + sig->sigInst.classInst = GetJitInstantiation(owningTypeInst); + } + + sig->sigInst.methInstCount = (uint)method.Instantiation.Length; + if (method.Instantiation.Length != 0) + { + sig->sigInst.methInst = GetJitInstantiation(method.Instantiation); + } } private void Get_CORINFO_SIG_INFO(MethodSignature signature, CORINFO_SIG_INFO* sig, MethodILScope scope) @@ -817,7 +815,7 @@ private void Get_CORINFO_SIG_INFO(MethodSignature signature, CORINFO_SIG_INFO* s sig->sigInst.classInst = null; // Not used by the JIT sig->sigInst.classInstCount = 0; // Not used by the JIT - sig->sigInst.methInst = null; // Not used by the JIT + sig->sigInst.methInst = null; sig->sigInst.methInstCount = (uint)signature.GenericParameterCount; sig->pSig = null; diff --git a/src/coreclr/tools/superpmi/superpmi-shared/lwmlist.h b/src/coreclr/tools/superpmi/superpmi-shared/lwmlist.h index 503e2c42bcf1f1..ce147abc89be60 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/lwmlist.h +++ b/src/coreclr/tools/superpmi/superpmi-shared/lwmlist.h @@ -68,7 +68,7 @@ LWM(GetClassGClayout, DWORDLONG, Agnostic_GetClassGClayout) LWM(GetClassModuleIdForStatics, DWORDLONG, Agnostic_GetClassModuleIdForStatics) LWM(GetClassName, DWORDLONG, DWORD) LWM(GetClassNameFromMetadata, DLD, DD) -LWM(GetTypeInstantiationArgument, DWORDLONG, DWORDLONG) +LWM(GetTypeInstantiationArgument, DLD, DWORDLONG) LWM(GetClassNumInstanceFields, DWORDLONG, DWORD) LWM(GetClassSize, DWORDLONG, DWORD) LWM(GetHeapClassSize, DWORDLONG, DWORD) diff --git a/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.cpp b/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.cpp index 3d7b40ff375f09..6536e5b8cb0a82 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.cpp @@ -6461,27 +6461,33 @@ const char* MethodContext::repGetClassNameFromMetadata(CORINFO_CLASS_HANDLE cls, } void MethodContext::recGetTypeInstantiationArgument(CORINFO_CLASS_HANDLE cls, - CORINFO_CLASS_HANDLE result, - unsigned index) + unsigned index, + CORINFO_CLASS_HANDLE result) { if (GetTypeInstantiationArgument == nullptr) - GetTypeInstantiationArgument = new LightWeightMap(); + GetTypeInstantiationArgument = new LightWeightMap(); - DWORDLONG key = CastHandle(cls); + DLD key; + ZeroMemory(&key, sizeof(key)); + key.A = CastHandle(cls); + key.B = index; DWORDLONG value = CastHandle(result); GetTypeInstantiationArgument->Add(key, value); DEBUG_REC(dmpGetTypeInstantiationArgument(key, value)); } -void MethodContext::dmpGetTypeInstantiationArgument(DWORDLONG key, DWORDLONG value) +void MethodContext::dmpGetTypeInstantiationArgument(DLD key, DWORDLONG value) { - printf("GetTypeInstantiationArgument key - classNonNull-%llu, value NonNull-%llu", key, value); + printf("GetTypeInstantiationArgument key - classNonNull-%llu, index-%u, value NonNull-%llu", key.A, key.B, value); GetTypeInstantiationArgument->Unlock(); } CORINFO_CLASS_HANDLE MethodContext::repGetTypeInstantiationArgument(CORINFO_CLASS_HANDLE cls, unsigned index) { CORINFO_CLASS_HANDLE result = nullptr; - DWORDLONG key = CastHandle(cls); + DLD key; + ZeroMemory(&key, sizeof(key)); + key.A = CastHandle(cls); + key.B = index; int itemIndex = -1; if (GetTypeInstantiationArgument != nullptr) diff --git a/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.h b/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.h index 3fc5247ef66c20..66a3b90e49a601 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.h +++ b/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.h @@ -796,8 +796,8 @@ class MethodContext void dmpGetClassNameFromMetadata(DLD key, DD value); const char* repGetClassNameFromMetadata(CORINFO_CLASS_HANDLE cls, const char** namespaceName); - void recGetTypeInstantiationArgument(CORINFO_CLASS_HANDLE cls, CORINFO_CLASS_HANDLE result, unsigned index); - void dmpGetTypeInstantiationArgument(DWORDLONG key, DWORDLONG value); + void recGetTypeInstantiationArgument(CORINFO_CLASS_HANDLE cls, unsigned index, CORINFO_CLASS_HANDLE result); + void dmpGetTypeInstantiationArgument(DLD key, DWORDLONG value); CORINFO_CLASS_HANDLE repGetTypeInstantiationArgument(CORINFO_CLASS_HANDLE cls, unsigned index); void recAppendClassName(int nBufLenIn, diff --git a/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitinfo.cpp b/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitinfo.cpp index 5d146d2de2cd77..2943db7a5376f4 100644 --- a/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitinfo.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitinfo.cpp @@ -489,9 +489,9 @@ const char* interceptor_ICJI::getClassNameFromMetadata(CORINFO_CLASS_HANDLE cls, CORINFO_CLASS_HANDLE interceptor_ICJI::getTypeInstantiationArgument(CORINFO_CLASS_HANDLE cls, unsigned index) { mc->cr->AddCall("getTypeInstantiationArgument"); - CORINFO_CLASS_HANDLE temp = original_ICorJitInfo->getTypeInstantiationArgument(cls, index); - mc->recGetTypeInstantiationArgument(cls, temp, index); - return temp; + CORINFO_CLASS_HANDLE result = original_ICorJitInfo->getTypeInstantiationArgument(cls, index); + mc->recGetTypeInstantiationArgument(cls, index, result); + return result; } // Append a (possibly truncated) textual representation of the type `cls` to a preallocated buffer. From cb10fa986e171a5651c37a263d7f7a173e227fd1 Mon Sep 17 00:00:00 2001 From: Jan Vorlicek Date: Sun, 4 Sep 2022 19:16:11 +0200 Subject: [PATCH 105/107] Remove unnecessary LoaderHeap asserts (#74995) There were two asserts in the LoaderHeap code that were checking successful reservation / committing of memory. However, these can fail in oom situation and the caller is prepared to handle such case. This assert was adding noise in CI testing. I have already removed one such assert at another place recently and I haven't noticed that we have other ones. The code at the two places was identical, so I have also refactored the committing code into a separate function. --- src/coreclr/inc/loaderheap.h | 3 ++ src/coreclr/utilcode/loaderheap.cpp | 67 +++++++++++++---------------- 2 files changed, 33 insertions(+), 37 deletions(-) diff --git a/src/coreclr/inc/loaderheap.h b/src/coreclr/inc/loaderheap.h index d310d17fb687c9..bc3cf5cf38e4bb 100644 --- a/src/coreclr/inc/loaderheap.h +++ b/src/coreclr/inc/loaderheap.h @@ -327,6 +327,9 @@ class UnlockedLoaderHeap // has run out, reserve another set of pages BOOL GetMoreCommittedPages(size_t dwMinSize); + // Commit memory pages starting at the specified adress + BOOL CommitPages(void* pData, size_t dwSizeToCommitPart); + protected: // Reserve some pages at any address BOOL UnlockedReservePages(size_t dwCommitBlockSize); diff --git a/src/coreclr/utilcode/loaderheap.cpp b/src/coreclr/utilcode/loaderheap.cpp index db6489026b2921..c2514efe39b6ee 100644 --- a/src/coreclr/utilcode/loaderheap.cpp +++ b/src/coreclr/utilcode/loaderheap.cpp @@ -1087,6 +1087,33 @@ void ReleaseReservedMemory(BYTE* value) using ReservedMemoryHolder = SpecializedWrapper; +BOOL UnlockedLoaderHeap::CommitPages(void* pData, size_t dwSizeToCommitPart) +{ + // Commit first set of pages, since it will contain the LoaderHeapBlock + void *pTemp = ExecutableAllocator::Instance()->Commit(pData, dwSizeToCommitPart, IsExecutable()); + if (pTemp == NULL) + { + return FALSE; + } + + if (IsInterleaved()) + { + _ASSERTE(dwSizeToCommitPart == GetOsPageSize()); + + void *pTemp = ExecutableAllocator::Instance()->Commit((BYTE*)pData + dwSizeToCommitPart, dwSizeToCommitPart, FALSE); + if (pTemp == NULL) + { + return FALSE; + } + + ExecutableWriterHolder codePageWriterHolder((BYTE*)pData, GetOsPageSize()); + m_codePageGenerator(codePageWriterHolder.GetRW(), (BYTE*)pData); + FlushInstructionCache(GetCurrentProcess(), pData, GetOsPageSize()); + } + + return TRUE; +} + BOOL UnlockedLoaderHeap::UnlockedReservePages(size_t dwSizeToCommit) { CONTRACTL @@ -1166,32 +1193,11 @@ BOOL UnlockedLoaderHeap::UnlockedReservePages(size_t dwSizeToCommit) dwSizeToCommitPart /= 2; } - // Commit first set of pages, since it will contain the LoaderHeapBlock - void *pTemp = ExecutableAllocator::Instance()->Commit(pData, dwSizeToCommitPart, IsExecutable()); - if (pTemp == NULL) + if (!CommitPages(pData, dwSizeToCommitPart)) { - _ASSERTE(!"Unable to commit a loaderheap code page"); - return FALSE; } - if (IsInterleaved()) - { - _ASSERTE(dwSizeToCommitPart == GetOsPageSize()); - - void *pTemp = ExecutableAllocator::Instance()->Commit((BYTE*)pData + dwSizeToCommitPart, dwSizeToCommitPart, FALSE); - if (pTemp == NULL) - { - _ASSERTE(!"Unable to commit a loaderheap data page"); - - return FALSE; - } - - ExecutableWriterHolder codePageWriterHolder(pData, GetOsPageSize()); - m_codePageGenerator(codePageWriterHolder.GetRW(), pData); - FlushInstructionCache(GetCurrentProcess(), pData, GetOsPageSize()); - } - // Record reserved range in range list, if one is specified // Do this AFTER the commit - otherwise we'll have bogus ranges included. if (m_pRangeList != NULL) @@ -1301,26 +1307,13 @@ BOOL UnlockedLoaderHeap::GetMoreCommittedPages(size_t dwMinSize) dwSizeToCommitPart /= 2; } - // Yes, so commit the desired number of reserved pages - void *pData = ExecutableAllocator::Instance()->Commit(m_pPtrToEndOfCommittedRegion, dwSizeToCommitPart, IsExecutable()); - if (pData == NULL) + if (!CommitPages(m_pPtrToEndOfCommittedRegion, dwSizeToCommitPart)) { return FALSE; } if (IsInterleaved()) { - // Commit a data page after the code page - void* pDataRW = ExecutableAllocator::Instance()->Commit(m_pPtrToEndOfCommittedRegion + dwSizeToCommitPart, dwSizeToCommitPart, FALSE); - if (pDataRW == NULL) - { - return FALSE; - } - - ExecutableWriterHolder codePageWriterHolder((BYTE*)pData, GetOsPageSize()); - m_codePageGenerator(codePageWriterHolder.GetRW(), (BYTE*)pData); - FlushInstructionCache(GetCurrentProcess(), pData, GetOsPageSize()); - // If the remaining bytes are large enough to allocate data of the allocation granularity, add them to the free // block list. // Otherwise the remaining bytes that are available will be wasted. @@ -1335,7 +1328,7 @@ BOOL UnlockedLoaderHeap::GetMoreCommittedPages(size_t dwMinSize) // For interleaved heaps, further allocations will start from the newly committed page as they cannot // cross page boundary. - m_pAllocPtr = (BYTE*)pData; + m_pAllocPtr = (BYTE*)m_pPtrToEndOfCommittedRegion; } m_pPtrToEndOfCommittedRegion += dwSizeToCommitPart; From 46875f5847b04bfcf8bcbed16f078514cb29d86a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20K=C3=B6plinger?= Date: Sun, 4 Sep 2022 19:25:08 +0200 Subject: [PATCH 106/107] System.Net.Requests: Pick correct RemoteExecutor overload in test (#74994) The test was using `RemoteExecutor.Invoke(Action method, ...)` since there is no overload that takes `Func` (only one with three strings) and that means it's becoming an async void. The delegate that gets invoked will return the moment the method awaits something not yet completed, so now there's a race condition, where `RemoteExecutor.Invoke` thinks all work is done, but there's still likely work running and it'll start doing all its cleanup stuff like killing child processes. Fix by removing one string parameter so it picks the correct overload. I'll also open an arcade PR to add an overload with four string arguments. Fixes https://github.com/dotnet/runtime/issues/74667 --- .../System.Net.Requests/tests/AssemblyInfo.cs | 1 - .../tests/HttpWebRequestTest.cs | 14 +++++++------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/libraries/System.Net.Requests/tests/AssemblyInfo.cs b/src/libraries/System.Net.Requests/tests/AssemblyInfo.cs index 3e5956a3d6fb35..eb0dcc687b65ba 100644 --- a/src/libraries/System.Net.Requests/tests/AssemblyInfo.cs +++ b/src/libraries/System.Net.Requests/tests/AssemblyInfo.cs @@ -5,5 +5,4 @@ using Xunit; [assembly: ActiveIssue("https://github.com/dotnet/runtime/issues/34690", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] -[assembly: ActiveIssue("https://github.com/dotnet/runtime/issues/74667", typeof(PlatformDetection), nameof(PlatformDetection.IsMonoLinuxArm64))] [assembly: SkipOnPlatform(TestPlatforms.Browser, "System.Net.Requests is not supported on Browser.")] diff --git a/src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs b/src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs index a6939061bdca26..3ea52f672990fd 100644 --- a/src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs +++ b/src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs @@ -1978,12 +1978,12 @@ await server.AcceptConnectionAsync(async connection => } [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] - [InlineData(RequestCacheLevel.NoCacheNoStore, new string[] { "Pragma: no-cache", "Cache-Control: no-store, no-cache" })] - [InlineData(RequestCacheLevel.Reload, new string[] { "Pragma: no-cache", "Cache-Control: no-cache" })] + [InlineData(RequestCacheLevel.NoCacheNoStore, "Cache-Control: no-store, no-cache")] + [InlineData(RequestCacheLevel.Reload, "Cache-Control: no-cache")] public void SendHttpGetRequest_WithGlobalCachePolicy_AddCacheHeaders( - RequestCacheLevel requestCacheLevel, string[] expectedHeaders) + RequestCacheLevel requestCacheLevel, string expectedHeader) { - RemoteExecutor.Invoke(async (async, reqCacheLevel, eh0, eh1) => + RemoteExecutor.Invoke(async (async, reqCacheLevel, eh) => { await LoopbackServer.CreateServerAsync(async (server, uri) => { @@ -1994,8 +1994,8 @@ await LoopbackServer.CreateServerAsync(async (server, uri) => await server.AcceptConnectionAsync(async connection => { List headers = await connection.ReadRequestHeaderAndSendResponseAsync(); - Assert.Contains(eh0, headers); - Assert.Contains(eh1, headers); + Assert.Contains("Pragma: no-cache", headers); + Assert.Contains(eh, headers); }); using (var response = (HttpWebResponse)await getResponse) @@ -2003,7 +2003,7 @@ await server.AcceptConnectionAsync(async connection => Assert.Equal(HttpStatusCode.OK, response.StatusCode); } }); - }, (this is HttpWebRequestTest_Async).ToString(), requestCacheLevel.ToString(), expectedHeaders[0], expectedHeaders[1]).Dispose(); + }, (this is HttpWebRequestTest_Async).ToString(), requestCacheLevel.ToString(), expectedHeader).Dispose(); } [Theory] From 75e65e99af5b3c8a2fd0abd5e887f8b14bd45362 Mon Sep 17 00:00:00 2001 From: Adeel Mujahid <3840695+am11@users.noreply.github.com> Date: Sun, 4 Sep 2022 20:47:12 +0300 Subject: [PATCH 107/107] Add a few more riscv64 stubs in PAL (#74793) * Add a few more riscv64 stubs in PAL * Simplify more conditional directives Co-authored-by: Jan Kotas --- src/coreclr/debug/ee/debugger.cpp | 4 +- src/coreclr/inc/crosscomp.h | 2 + src/coreclr/inc/llvm/ELF.h | 1 + src/coreclr/inc/volatile.h | 6 +- src/coreclr/pal/inc/pal.h | 285 +++++++----- src/coreclr/pal/inc/rt/palrt.h | 39 +- src/coreclr/pal/inc/unixasmmacros.inc | 2 + src/coreclr/pal/inc/unixasmmacrosppc64le.inc | 1 - src/coreclr/pal/inc/unixasmmacrosriscv64.inc | 42 ++ src/coreclr/pal/inc/unixasmmacross390x.inc | 1 - .../pal/src/arch/loongarch64/context.S | 16 - .../pal/src/arch/riscv64/asmconstants.h | 4 +- src/coreclr/pal/src/arch/riscv64/context.S | 6 - src/coreclr/pal/src/exception/seh-unwind.cpp | 96 +++- src/coreclr/pal/src/include/pal/context.h | 67 ++- src/coreclr/pal/src/misc/perfjitdump.cpp | 2 + src/coreclr/pal/src/thread/context.cpp | 439 ++++++++++-------- 17 files changed, 607 insertions(+), 406 deletions(-) create mode 100644 src/coreclr/pal/inc/unixasmmacrosriscv64.inc delete mode 100644 src/coreclr/pal/src/arch/loongarch64/context.S delete mode 100644 src/coreclr/pal/src/arch/riscv64/context.S diff --git a/src/coreclr/debug/ee/debugger.cpp b/src/coreclr/debug/ee/debugger.cpp index f8a3adc971a460..7b1f76f78a9f87 100644 --- a/src/coreclr/debug/ee/debugger.cpp +++ b/src/coreclr/debug/ee/debugger.cpp @@ -6638,6 +6638,7 @@ void Debugger::InitDebuggerLaunchJitInfo(Thread * pThread, EXCEPTION_POINTERS * reinterpret_cast(s_DebuggerLaunchJitInfoExceptionRecord.ExceptionAddress) : reinterpret_cast(reinterpret_cast(GetIP(pExceptionInfo->ContextRecord))); +#if defined(HOST_WINDOWS) #if defined(TARGET_X86) s_DebuggerLaunchJitInfo.dwProcessorArchitecture = PROCESSOR_ARCHITECTURE_INTEL; #elif defined(TARGET_AMD64) @@ -6646,11 +6647,10 @@ void Debugger::InitDebuggerLaunchJitInfo(Thread * pThread, EXCEPTION_POINTERS * s_DebuggerLaunchJitInfo.dwProcessorArchitecture = PROCESSOR_ARCHITECTURE_ARM; #elif defined(TARGET_ARM64) s_DebuggerLaunchJitInfo.dwProcessorArchitecture = PROCESSOR_ARCHITECTURE_ARM64; -#elif defined(TARGET_LOONGARCH64) - s_DebuggerLaunchJitInfo.dwProcessorArchitecture = PROCESSOR_ARCHITECTURE_LOONGARCH64; #else #error Unknown processor. #endif +#endif } diff --git a/src/coreclr/inc/crosscomp.h b/src/coreclr/inc/crosscomp.h index 79c246a29e8a59..4be28673efd38a 100644 --- a/src/coreclr/inc/crosscomp.h +++ b/src/coreclr/inc/crosscomp.h @@ -565,6 +565,8 @@ typedef struct _T_KNONVOLATILE_CONTEXT_POINTERS { #define DAC_CS_NATIVE_DATA_SIZE 96 #elif defined(TARGET_LINUX) && defined(TARGET_LOONGARCH64) #define DAC_CS_NATIVE_DATA_SIZE 96 +#elif defined(TARGET_LINUX) && defined(TARGET_RISCV64) +#define DAC_CS_NATIVE_DATA_SIZE 96 #elif defined(TARGET_LINUX) && defined(TARGET_POWERPC64) #define DAC_CS_NATIVE_DATA_SIZE 96 #elif defined(TARGET_NETBSD) && defined(TARGET_AMD64) diff --git a/src/coreclr/inc/llvm/ELF.h b/src/coreclr/inc/llvm/ELF.h index b38ecf9eba73a7..4cc44d1d26304c 100644 --- a/src/coreclr/inc/llvm/ELF.h +++ b/src/coreclr/inc/llvm/ELF.h @@ -343,6 +343,7 @@ enum { EM_NORC = 218, // Nanoradio Optimized RISC EM_CSR_KALIMBA = 219, // CSR Kalimba architecture family EM_AMDGPU = 224, // AMD GPU architecture + EM_RISCV = 243, EM_LOONGARCH = 258, // LoongArch processor // A request has been made to the maintainer of the official registry for diff --git a/src/coreclr/inc/volatile.h b/src/coreclr/inc/volatile.h index 4ab4cdbdc08789..d0b2df959809aa 100644 --- a/src/coreclr/inc/volatile.h +++ b/src/coreclr/inc/volatile.h @@ -68,8 +68,8 @@ #error The Volatile type is currently only defined for Visual C++ and GNU C++ #endif -#if defined(__GNUC__) && !defined(HOST_X86) && !defined(HOST_AMD64) && !defined(HOST_ARM) && !defined(HOST_ARM64) && !defined(HOST_LOONGARCH64) && !defined(HOST_S390X) && !defined(HOST_POWERPC64) -#error The Volatile type is currently only defined for GCC when targeting x86, AMD64, ARM, ARM64, LOONGARCH64, PPC64LE, or S390X CPUs +#if defined(__GNUC__) && !defined(HOST_X86) && !defined(HOST_AMD64) && !defined(HOST_ARM) && !defined(HOST_ARM64) && !defined(HOST_LOONGARCH64) && !defined(HOST_RISCV64) && !defined(HOST_S390X) && !defined(HOST_POWERPC64) +#error The Volatile type is currently only defined for GCC when targeting x86, AMD64, ARM, ARM64, LOONGARCH64, RISCV64, PPC64LE, or S390X CPUs #endif #if defined(__GNUC__) @@ -81,6 +81,8 @@ #define VOLATILE_MEMORY_BARRIER() asm volatile ("dmb ish" : : : "memory") #elif defined(HOST_LOONGARCH64) #define VOLATILE_MEMORY_BARRIER() asm volatile ("dbar 0 " : : : "memory") +#elif defined(HOST_RISCV64) +#define VOLATILE_MEMORY_BARRIER() asm volatile ("fence rw,rw" : : : "memory") #else // // For GCC, we prevent reordering by the compiler by inserting the following after a volatile diff --git a/src/coreclr/pal/inc/pal.h b/src/coreclr/pal/inc/pal.h index f58c854487128a..d16eac5cc3ec2e 100644 --- a/src/coreclr/pal/inc/pal.h +++ b/src/coreclr/pal/inc/pal.h @@ -1494,6 +1494,25 @@ typedef struct _KNONVOLATILE_CONTEXT_POINTERS { } KNONVOLATILE_CONTEXT_POINTERS, *PKNONVOLATILE_CONTEXT_POINTERS; + +// +// Context Frame +// +// +// The flags field within this record controls the contents of a CONTEXT +// record. +// +// If the context record is used as an input parameter, then for each +// portion of the context record controlled by a flag whose value is +// set, it is assumed that such portion of the context record contains +// valid context. If the context record is being used to modify a threads +// context, then only that portion of the threads context is modified. +// +// If the context record is used as an output parameter to capture the +// context of a thread, then only those portions of the thread's context +// corresponding to set flags will be returned. +// + #elif defined(HOST_AMD64) // copied from winnt.h @@ -1540,39 +1559,6 @@ typedef struct _XMM_SAVE_AREA32 { BYTE Reserved4[96]; } XMM_SAVE_AREA32, *PXMM_SAVE_AREA32; -// -// Context Frame -// -// This frame has a several purposes: 1) it is used as an argument to -// NtContinue, 2) it is used to construct a call frame for APC delivery, -// and 3) it is used in the user level thread creation routines. -// -// -// The flags field within this record controls the contents of a CONTEXT -// record. -// -// If the context record is used as an input parameter, then for each -// portion of the context record controlled by a flag whose value is -// set, it is assumed that such portion of the context record contains -// valid context. If the context record is being used to modify a threads -// context, then only that portion of the threads context is modified. -// -// If the context record is used as an output parameter to capture the -// context of a thread, then only those portions of the thread's context -// corresponding to set flags will be returned. -// -// CONTEXT_CONTROL specifies SegSs, Rsp, SegCs, Rip, and EFlags. -// -// CONTEXT_INTEGER specifies Rax, Rcx, Rdx, Rbx, Rbp, Rsi, Rdi, and R8-R15. -// -// CONTEXT_SEGMENTS specifies SegDs, SegEs, SegFs, and SegGs. -// -// CONTEXT_DEBUG_REGISTERS specifies Dr0-Dr3 and Dr6-Dr7. -// -// CONTEXT_MMX_REGISTERS specifies the floating point and extended registers -// Mm0/St0-Mm7/St7 and Xmm0-Xmm15). -// - typedef struct DECLSPEC_ALIGN(16) _CONTEXT { // @@ -1786,37 +1772,6 @@ typedef struct _NEON128 { LONGLONG High; } NEON128, *PNEON128; -// -// Context Frame -// -// This frame has a several purposes: 1) it is used as an argument to -// NtContinue, 2) it is used to construct a call frame for APC delivery, -// and 3) it is used in the user level thread creation routines. -// -// -// The flags field within this record controls the contents of a CONTEXT -// record. -// -// If the context record is used as an input parameter, then for each -// portion of the context record controlled by a flag whose value is -// set, it is assumed that such portion of the context record contains -// valid context. If the context record is being used to modify a threads -// context, then only that portion of the threads context is modified. -// -// If the context record is used as an output parameter to capture the -// context of a thread, then only those portions of the thread's context -// corresponding to set flags will be returned. -// -// CONTEXT_CONTROL specifies Sp, Lr, Pc, and Cpsr -// -// CONTEXT_INTEGER specifies R0-R12 -// -// CONTEXT_FLOATING_POINT specifies Q0-Q15 / D0-D31 / S0-S31 -// -// CONTEXT_DEBUG_REGISTERS specifies up to 16 of DBGBVR, DBGBCR, DBGWVR, -// DBGWCR. -// - typedef struct DECLSPEC_ALIGN(8) _CONTEXT { // @@ -1968,37 +1923,6 @@ typedef struct _IMAGE_ARM_RUNTIME_FUNCTION_ENTRY { #define ARM64_MAX_BREAKPOINTS 8 #define ARM64_MAX_WATCHPOINTS 2 -// -// Context Frame -// -// This frame has a several purposes: 1) it is used as an argument to -// NtContinue, 2) it is used to construct a call frame for APC delivery, -// and 3) it is used in the user level thread creation routines. -// -// -// The flags field within this record controls the contents of a CONTEXT -// record. -// -// If the context record is used as an input parameter, then for each -// portion of the context record controlled by a flag whose value is -// set, it is assumed that such portion of the context record contains -// valid context. If the context record is being used to modify a threads -// context, then only that portion of the threads context is modified. -// -// If the context record is used as an output parameter to capture the -// context of a thread, then only those portions of the thread's context -// corresponding to set flags will be returned. -// -// CONTEXT_CONTROL specifies Sp, Lr, Pc, and Cpsr -// -// CONTEXT_INTEGER specifies R0-R12 -// -// CONTEXT_FLOATING_POINT specifies Q0-Q15 / D0-D31 / S0-S31 -// -// CONTEXT_DEBUG_REGISTERS specifies up to 16 of DBGBVR, DBGBCR, DBGWVR, -// DBGWCR. -// - typedef struct _NEON128 { ULONGLONG Low; LONGLONG High; @@ -2145,28 +2069,6 @@ typedef struct _KNONVOLATILE_CONTEXT_POINTERS { #define LOONGARCH64_MAX_BREAKPOINTS 8 #define LOONGARCH64_MAX_WATCHPOINTS 2 -// -// Context Frame -// -// This frame has a several purposes: 1) it is used as an argument to -// NtContinue, 2) it is used to construct a call frame for APC delivery, -// and 3) it is used in the user level thread creation routines. -// -// -// The flags field within this record controls the contents of a CONTEXT -// record. -// -// If the context record is used as an input parameter, then for each -// portion of the context record controlled by a flag whose value is -// set, it is assumed that such portion of the context record contains -// valid context. If the context record is being used to modify a threads -// context, then only that portion of the threads context is modified. -// -// If the context record is used as an output parameter to capture the -// context of a thread, then only those portions of the thread's context -// corresponding to set flags will be returned. -// - typedef struct DECLSPEC_ALIGN(16) _CONTEXT { // @@ -2249,6 +2151,155 @@ typedef struct _KNONVOLATILE_CONTEXT_POINTERS { PDWORD64 F31; } KNONVOLATILE_CONTEXT_POINTERS, *PKNONVOLATILE_CONTEXT_POINTERS; +#elif defined(HOST_RISCV64) + +#error "TODO-RISCV64: review this when src/coreclr/pal/src/arch/riscv64/asmconstants.h is ported" + +// Please refer to src/coreclr/pal/src/arch/riscv64/asmconstants.h +#define CONTEXT_RISCV64 0x04000000L + +#define CONTEXT_CONTROL (CONTEXT_RISCV64 | 0x1) +#define CONTEXT_INTEGER (CONTEXT_RISCV64 | 0x2) +#define CONTEXT_FLOATING_POINT (CONTEXT_RISCV64 | 0x4) +#define CONTEXT_DEBUG_REGISTERS (CONTEXT_RISCV64 | 0x8) + +#define CONTEXT_FULL (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_FLOATING_POINT) + +#define CONTEXT_ALL (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS) + +#define CONTEXT_EXCEPTION_ACTIVE 0x8000000 +#define CONTEXT_SERVICE_ACTIVE 0x10000000 +#define CONTEXT_EXCEPTION_REQUEST 0x40000000 +#define CONTEXT_EXCEPTION_REPORTING 0x80000000 + +// +// This flag is set by the unwinder if it has unwound to a call +// site, and cleared whenever it unwinds through a trap frame. +// It is used by language-specific exception handlers to help +// differentiate exception scopes during dispatching. +// + +#define CONTEXT_UNWOUND_TO_CALL 0x20000000 + +// begin_ntoshvp + +// +// Specify the number of breakpoints and watchpoints that the OS +// will track. Architecturally, RISCV64 supports up to 16. In practice, +// however, almost no one implements more than 4 of each. +// + +#define RISCV64_MAX_BREAKPOINTS 8 +#define RISCV64_MAX_WATCHPOINTS 2 + +typedef struct DECLSPEC_ALIGN(16) _CONTEXT { + + // + // Control flags. + // + + /* +0x000 */ DWORD ContextFlags; + + // + // Integer registers. + // + DWORD64 Ra; + DWORD64 Sp; + DWORD64 Gp; + DWORD64 Tp; + DWORD64 T0; + DWORD64 T1; + DWORD64 T2; + DWORD64 S0; + DWORD64 S1; + DWORD64 A0; + DWORD64 A1; + DWORD64 A2; + DWORD64 A3; + DWORD64 A4; + DWORD64 A5; + DWORD64 A6; + DWORD64 A7; + DWORD64 S2; + DWORD64 S3; + DWORD64 S4; + DWORD64 S5; + DWORD64 S6; + DWORD64 S7; + DWORD64 S8; + DWORD64 S9; + DWORD64 S10; + DWORD64 S11; + DWORD64 T3; + DWORD64 T4; + DWORD64 T5; + DWORD64 T6; + DWORD64 Pc; + + // + // Floating Point Registers + // + // TODO-RISCV64: support the SIMD. + ULONGLONG F[32]; + DWORD Fcsr; +} CONTEXT, *PCONTEXT, *LPCONTEXT; + +// +// Nonvolatile context pointer record. +// + +typedef struct _KNONVOLATILE_CONTEXT_POINTERS { + + PDWORD64 Ra; + PDWORD64 Tp; + PDWORD64 T0; + PDWORD64 T1; + PDWORD64 S0; + PDWORD64 S1; + PDWORD64 A0; + PDWORD64 A1; + PDWORD64 A2; + PDWORD64 A3; + PDWORD64 A4; + PDWORD64 A5; + PDWORD64 A6; + PDWORD64 A7; + PDWORD64 S2; + PDWORD64 S3; + PDWORD64 S4; + PDWORD64 S5; + PDWORD64 S6; + PDWORD64 S7; + PDWORD64 S8; + PDWORD64 S9; + PDWORD64 S10; + PDWORD64 S11; + PDWORD64 T3; + PDWORD64 T4; + PDWORD64 T5; + PDWORD64 T6; + + PDWORD64 FS0; + PDWORD64 FS1; + PDWORD64 FA0; + PDWORD64 FA1; + PDWORD64 FA2; + PDWORD64 FA3; + PDWORD64 FA4; + PDWORD64 FA5; + PDWORD64 FA6; + PDWORD64 FA7; + PDWORD64 FS2; + PDWORD64 FS3; + PDWORD64 FS4; + PDWORD64 FS5; + PDWORD64 FS6; + PDWORD64 FS7; + PDWORD64 FS8; + PDWORD64 FS9; + PDWORD64 FS10; + PDWORD64 FS11; +} KNONVOLATILE_CONTEXT_POINTERS, *PKNONVOLATILE_CONTEXT_POINTERS; #elif defined(HOST_S390X) diff --git a/src/coreclr/pal/inc/rt/palrt.h b/src/coreclr/pal/inc/rt/palrt.h index 954bcc7ca8c727..0713a59da8444e 100644 --- a/src/coreclr/pal/inc/rt/palrt.h +++ b/src/coreclr/pal/inc/rt/palrt.h @@ -867,24 +867,6 @@ typedef VOID (NTAPI *WAITORTIMERCALLBACK)(PVOID, BOOLEAN); #define IMAGE_COR20_HEADER_FIELD(obj, f) ((obj).f) #endif -// copied from winnt.h -#define PROCESSOR_ARCHITECTURE_INTEL 0 -#define PROCESSOR_ARCHITECTURE_MIPS 1 -#define PROCESSOR_ARCHITECTURE_ALPHA 2 -#define PROCESSOR_ARCHITECTURE_PPC 3 -#define PROCESSOR_ARCHITECTURE_SHX 4 -#define PROCESSOR_ARCHITECTURE_ARM 5 -#define PROCESSOR_ARCHITECTURE_IA64 6 -#define PROCESSOR_ARCHITECTURE_ALPHA64 7 -#define PROCESSOR_ARCHITECTURE_MSIL 8 -#define PROCESSOR_ARCHITECTURE_AMD64 9 -#define PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 10 -#define PROCESSOR_ARCHITECTURE_NEUTRAL 11 -#define PROCESSOR_ARCHITECTURE_ARM64 12 -#define PROCESSOR_ARCHITECTURE_LOONGARCH64 13 - -#define PROCESSOR_ARCHITECTURE_UNKNOWN 0xFFFF - // // JIT Debugging Info. This structure is defined to have constant size in // both the emulated and native environment. @@ -892,7 +874,6 @@ typedef VOID (NTAPI *WAITORTIMERCALLBACK)(PVOID, BOOLEAN); typedef struct _JIT_DEBUG_INFO { DWORD dwSize; - DWORD dwProcessorArchitecture; DWORD dwThreadID; DWORD dwReserved0; ULONG64 lpExceptionAddress; @@ -1061,7 +1042,7 @@ typedef struct _DISPATCHER_CONTEXT { DWORD Reserved; } DISPATCHER_CONTEXT, *PDISPATCHER_CONTEXT; -#elif defined(HOST_ARM64) +#elif defined(HOST_ARM64) || defined(HOST_LOONGARCH64) || defined(HOST_RISCV64) typedef struct _DISPATCHER_CONTEXT { ULONG64 ControlPc; @@ -1109,24 +1090,6 @@ typedef struct _DISPATCHER_CONTEXT { BOOLEAN ControlPcIsUnwound; } DISPATCHER_CONTEXT, *PDISPATCHER_CONTEXT; -#elif defined(HOST_LOONGARCH64) - -typedef struct _DISPATCHER_CONTEXT { - ULONG64 ControlPc; - ULONG64 ImageBase; - PRUNTIME_FUNCTION FunctionEntry; - ULONG64 EstablisherFrame; - ULONG64 TargetPc; - PCONTEXT ContextRecord; - PEXCEPTION_ROUTINE LanguageHandler; - PVOID HandlerData; - PVOID HistoryTable; - ULONG64 ScopeIndex; - BOOLEAN ControlPcIsUnwound; - PBYTE NonVolatileRegisters; - ULONG64 Reserved; -} DISPATCHER_CONTEXT, *PDISPATCHER_CONTEXT; - #elif defined(HOST_S390X) typedef struct _DISPATCHER_CONTEXT { diff --git a/src/coreclr/pal/inc/unixasmmacros.inc b/src/coreclr/pal/inc/unixasmmacros.inc index cf05fbe3199348..658a65bb4b35aa 100644 --- a/src/coreclr/pal/inc/unixasmmacros.inc +++ b/src/coreclr/pal/inc/unixasmmacros.inc @@ -47,6 +47,8 @@ #include "unixasmmacross390x.inc" #elif defined(HOST_LOONGARCH64) #include "unixasmmacrosloongarch64.inc" +#elif defined(HOST_RISCV64) +#include "unixasmmacrosriscv64.inc" #elif defined(HOST_POWERPC64) #include "unixasmmacrosppc64le.inc" #endif diff --git a/src/coreclr/pal/inc/unixasmmacrosppc64le.inc b/src/coreclr/pal/inc/unixasmmacrosppc64le.inc index 2c1c4d6f3e1dee..6fdc3ee3ee44fd 100644 --- a/src/coreclr/pal/inc/unixasmmacrosppc64le.inc +++ b/src/coreclr/pal/inc/unixasmmacrosppc64le.inc @@ -34,4 +34,3 @@ C_FUNC(\Name\()_End): .global C_FUNC(\Name\()_End) LEAF_END \Name, \Section .endm - diff --git a/src/coreclr/pal/inc/unixasmmacrosriscv64.inc b/src/coreclr/pal/inc/unixasmmacrosriscv64.inc new file mode 100644 index 00000000000000..683ae88415a907 --- /dev/null +++ b/src/coreclr/pal/inc/unixasmmacrosriscv64.inc @@ -0,0 +1,42 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#error "TODO-RISCV64: review this; missing many macros for VM" + +.macro NESTED_ENTRY Name, Section, Handler + LEAF_ENTRY \Name, \Section + .ifnc \Handler, NoHandler + .personality C_FUNC(\Handler) + .endif +.endm + +.macro NESTED_END Name, Section + LEAF_END \Name, \Section +.endm + +.macro PATCH_LABEL Name + .global C_FUNC(\Name) +C_FUNC(\Name): +.endm + +.macro LEAF_ENTRY Name, Section + .global C_FUNC(\Name) + .type \Name, %function +C_FUNC(\Name): + .cfi_startproc +.endm + +.macro LEAF_END Name, Section + .size \Name, .-\Name + .cfi_endproc +.endm + +.macro LEAF_END_MARKED Name, Section +C_FUNC(\Name\()_End): + .global C_FUNC(\Name\()_End) + LEAF_END \Name, \Section +.endm + +.macro EMIT_BREAKPOINT + ebreak +.endm diff --git a/src/coreclr/pal/inc/unixasmmacross390x.inc b/src/coreclr/pal/inc/unixasmmacross390x.inc index ae6a894ad7cd5b..e4d792870886cb 100644 --- a/src/coreclr/pal/inc/unixasmmacross390x.inc +++ b/src/coreclr/pal/inc/unixasmmacross390x.inc @@ -34,4 +34,3 @@ C_FUNC(\Name\()_End): .global C_FUNC(\Name\()_End) LEAF_END \Name, \Section .endm - diff --git a/src/coreclr/pal/src/arch/loongarch64/context.S b/src/coreclr/pal/src/arch/loongarch64/context.S deleted file mode 100644 index 64e8464308ca65..00000000000000 --- a/src/coreclr/pal/src/arch/loongarch64/context.S +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -#include "unixasmmacros.inc" - -#if defined(_DEBUG) -NESTED_ENTRY DBG_CheckStackAlignment, _TEXT, NoHandler - // $fp,$ra - PROLOG_SAVE_REG_PAIR_INDEXED 22, 1, -16 - // Reading from an unaligned stack pointer will trigger a stack alignment fault - ld.d $a0, $sp - // $fp,$ra - EPILOG_RESTORE_REG_PAIR_INDEXED 22, 1, 16 - jirl $r0, $ra, 0 -NESTED_END _DBG_CheckStackAlignment, _TEXT -#endif diff --git a/src/coreclr/pal/src/arch/riscv64/asmconstants.h b/src/coreclr/pal/src/arch/riscv64/asmconstants.h index a278e12f95ecc6..015ac39c13fc9f 100644 --- a/src/coreclr/pal/src/arch/riscv64/asmconstants.h +++ b/src/coreclr/pal/src/arch/riscv64/asmconstants.h @@ -4,8 +4,8 @@ #ifndef __PAL_RISCV64_ASMCONSTANTS_H__ #define __PAL_RISCV64_ASMCONSTANTS_H__ -// https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/3f81fae0412bb9ad4002a4ade508be7aa5e1599b/riscv-dwarf.adoc -// https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/442ae19a2846bca37c6416f2d347fe74bb0b0dba/riscv-cc.adoc +// https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/2d865a2964fe06bfc569ab00c74e152b582ed764/riscv-dwarf.adoc +// https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/2d865a2964fe06bfc569ab00c74e152b582ed764/riscv-cc.adoc #error "TODO-RISCV64: review this when other files are ported in this directory" diff --git a/src/coreclr/pal/src/arch/riscv64/context.S b/src/coreclr/pal/src/arch/riscv64/context.S deleted file mode 100644 index f6c1fb2c96ce46..00000000000000 --- a/src/coreclr/pal/src/arch/riscv64/context.S +++ /dev/null @@ -1,6 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -#include "unixasmmacros.inc" - -#error "TODO-RISCV64: missing implementation" diff --git a/src/coreclr/pal/src/exception/seh-unwind.cpp b/src/coreclr/pal/src/exception/seh-unwind.cpp index f718be6af54c27..a5f9f3345e93f4 100644 --- a/src/coreclr/pal/src/exception/seh-unwind.cpp +++ b/src/coreclr/pal/src/exception/seh-unwind.cpp @@ -152,6 +152,31 @@ enum ASSIGN_REG(S6) \ ASSIGN_REG(S7) \ ASSIGN_REG(S8) +#elif (defined(HOST_UNIX) && defined(HOST_RISCV64)) + +#error "TODO-RISCV64: review this" + +// https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/2d865a2964fe06bfc569ab00c74e152b582ed764/riscv-cc.adoc + +#define ASSIGN_UNWIND_REGS \ + ASSIGN_REG(Ra) \ + ASSIGN_REG(Sp) \ + ASSIGN_REG(Sp) \ + ASSIGN_REG(Gp) \ + ASSIGN_REG(Tp) \ + ASSIGN_REG(Pc) \ + ASSIGN_REG(S0) \ + ASSIGN_REG(S1) \ + ASSIGN_REG(S2) \ + ASSIGN_REG(S3) \ + ASSIGN_REG(S4) \ + ASSIGN_REG(S5) \ + ASSIGN_REG(S6) \ + ASSIGN_REG(S7) \ + ASSIGN_REG(S8) \ + ASSIGN_REG(S9) \ + ASSIGN_REG(S10) \ + ASSIGN_REG(S11) #elif (defined(HOST_UNIX) && defined(HOST_POWERPC64)) #define ASSIGN_UNWIND_REGS \ ASSIGN_REG(Nip) \ @@ -172,7 +197,7 @@ enum ASSIGN_REG(R28) \ ASSIGN_REG(R29) \ ASSIGN_REG(R30) \ - ASSIGN_REG(R31) + ASSIGN_REG(R31) #else #error unsupported architecture #endif @@ -411,6 +436,42 @@ void UnwindContextToWinContext(unw_cursor_t *cursor, CONTEXT *winContext) unw_get_reg(cursor, UNW_LOONGARCH64_R29, (unw_word_t *) &winContext->S6); unw_get_reg(cursor, UNW_LOONGARCH64_R30, (unw_word_t *) &winContext->S7); unw_get_reg(cursor, UNW_LOONGARCH64_R31, (unw_word_t *) &winContext->S8); +#elif (defined(HOST_UNIX) && defined(HOST_RISCV64)) +#error "TODO-RISCV64: review this" + + // https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/2d865a2964fe06bfc569ab00c74e152b582ed764/riscv-cc.adoc + + unw_get_reg(cursor, UNW_REG_IP, (unw_word_t *) &winContext->Pc); + unw_get_reg(cursor, UNW_RISCV_X1, (unw_word_t *) &winContext->Ra); + unw_get_reg(cursor, UNW_REG_SP, (unw_word_t *) &winContext->Sp); + unw_get_reg(cursor, UNW_RISCV_X4, (unw_word_t *) &winContext->Tp); + unw_get_reg(cursor, UNW_RISCV_X5, (unw_word_t *) &winContext->T0); + unw_get_reg(cursor, UNW_RISCV_X6, (unw_word_t *) &winContext->T1); + unw_get_reg(cursor, UNW_RISCV_X7, (unw_word_t *) &winContext->T2); + unw_get_reg(cursor, UNW_RISCV_X8, (unw_word_t *) &winContext->S0); + unw_get_reg(cursor, UNW_RISCV_X9, (unw_word_t *) &winContext->S1); + unw_get_reg(cursor, UNW_RISCV_X10, (unw_word_t *) &winContext->A0); + unw_get_reg(cursor, UNW_RISCV_X11, (unw_word_t *) &winContext->A1); + unw_get_reg(cursor, UNW_RISCV_X12, (unw_word_t *) &winContext->A2); + unw_get_reg(cursor, UNW_RISCV_X13, (unw_word_t *) &winContext->A3); + unw_get_reg(cursor, UNW_RISCV_X14, (unw_word_t *) &winContext->A4); + unw_get_reg(cursor, UNW_RISCV_X15, (unw_word_t *) &winContext->A5); + unw_get_reg(cursor, UNW_RISCV_X16, (unw_word_t *) &winContext->A6); + unw_get_reg(cursor, UNW_RISCV_X17, (unw_word_t *) &winContext->A7); + unw_get_reg(cursor, UNW_RISCV_X18, (unw_word_t *) &winContext->S2); + unw_get_reg(cursor, UNW_RISCV_X19, (unw_word_t *) &winContext->S3); + unw_get_reg(cursor, UNW_RISCV_X20, (unw_word_t *) &winContext->S4); + unw_get_reg(cursor, UNW_RISCV_X21, (unw_word_t *) &winContext->S5); + unw_get_reg(cursor, UNW_RISCV_X22, (unw_word_t *) &winContext->S6); + unw_get_reg(cursor, UNW_RISCV_X23, (unw_word_t *) &winContext->S7); + unw_get_reg(cursor, UNW_RISCV_X24, (unw_word_t *) &winContext->S8); + unw_get_reg(cursor, UNW_RISCV_X25, (unw_word_t *) &winContext->S9); + unw_get_reg(cursor, UNW_RISCV_X26, (unw_word_t *) &winContext->S10); + unw_get_reg(cursor, UNW_RISCV_X27, (unw_word_t *) &winContext->S11); + unw_get_reg(cursor, UNW_RISCV_X28, (unw_word_t *) &winContext->T3); + unw_get_reg(cursor, UNW_RISCV_X29, (unw_word_t *) &winContext->T4); + unw_get_reg(cursor, UNW_RISCV_X30, (unw_word_t *) &winContext->T5); + unw_get_reg(cursor, UNW_RISCV_X31, (unw_word_t *) &winContext->T6); #elif (defined(HOST_UNIX) && defined(HOST_POWERPC64)) unw_get_reg(cursor, UNW_REG_SP, (unw_word_t *) &winContext->R31); unw_get_reg(cursor, UNW_REG_IP, (unw_word_t *) &winContext->Nip); @@ -529,6 +590,39 @@ void GetContextPointers(unw_cursor_t *cursor, unw_context_t *unwContext, KNONVOL GetContextPointer(cursor, unwContext, UNW_LOONGARCH64_R29, &contextPointers->S6); GetContextPointer(cursor, unwContext, UNW_LOONGARCH64_R30, &contextPointers->S7); GetContextPointer(cursor, unwContext, UNW_LOONGARCH64_R31, &contextPointers->S8); +#elif (defined(HOST_UNIX) && defined(HOST_RISCV64)) +#error "TODO-RISCV64: review this" + + // https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/2d865a2964fe06bfc569ab00c74e152b582ed764/riscv-cc.adoc + + GetContextPointer(cursor, unwContext, UNW_RISCV_X1, &contextPointers->Ra); + GetContextPointer(cursor, unwContext, UNW_RISCV_X4, &contextPointers->Tp); + GetContextPointer(cursor, unwContext, UNW_RISCV_X5, &contextPointers->T0); + GetContextPointer(cursor, unwContext, UNW_RISCV_X7, &contextPointers->T1); + GetContextPointer(cursor, unwContext, UNW_RISCV_X8, &contextPointers->S0); + GetContextPointer(cursor, unwContext, UNW_RISCV_X9, &contextPointers->S1); + GetContextPointer(cursor, unwContext, UNW_RISCV_X10, &contextPointers->A0); + GetContextPointer(cursor, unwContext, UNW_RISCV_X11, &contextPointers->A1); + GetContextPointer(cursor, unwContext, UNW_RISCV_X12, &contextPointers->A2); + GetContextPointer(cursor, unwContext, UNW_RISCV_X13, &contextPointers->A3); + GetContextPointer(cursor, unwContext, UNW_RISCV_X14, &contextPointers->A4); + GetContextPointer(cursor, unwContext, UNW_RISCV_X15, &contextPointers->A5); + GetContextPointer(cursor, unwContext, UNW_RISCV_X16, &contextPointers->A6); + GetContextPointer(cursor, unwContext, UNW_RISCV_X17, &contextPointers->A7); + GetContextPointer(cursor, unwContext, UNW_RISCV_X18, &contextPointers->S2); + GetContextPointer(cursor, unwContext, UNW_RISCV_X19, &contextPointers->S3); + GetContextPointer(cursor, unwContext, UNW_RISCV_X20, &contextPointers->S4); + GetContextPointer(cursor, unwContext, UNW_RISCV_X21, &contextPointers->S5); + GetContextPointer(cursor, unwContext, UNW_RISCV_X22, &contextPointers->S6); + GetContextPointer(cursor, unwContext, UNW_RISCV_X23, &contextPointers->S7); + GetContextPointer(cursor, unwContext, UNW_RISCV_X24, &contextPointers->S8); + GetContextPointer(cursor, unwContext, UNW_RISCV_X25, &contextPointers->S9); + GetContextPointer(cursor, unwContext, UNW_RISCV_X26, &contextPointers->S10); + GetContextPointer(cursor, unwContext, UNW_RISCV_X27, &contextPointers->S11); + GetContextPointer(cursor, unwContext, UNW_RISCV_X28, &contextPointers->T3); + GetContextPointer(cursor, unwContext, UNW_RISCV_X29, &contextPointers->T4); + GetContextPointer(cursor, unwContext, UNW_RISCV_X30, &contextPointers->T5); + GetContextPointer(cursor, unwContext, UNW_RISCV_X31, &contextPointers->T6); #elif (defined(HOST_UNIX) && defined(HOST_POWERPC64)) GetContextPointer(cursor, unwContext, UNW_PPC64_R14, &contextPointers->R14); GetContextPointer(cursor, unwContext, UNW_PPC64_R15, &contextPointers->R15); diff --git a/src/coreclr/pal/src/include/pal/context.h b/src/coreclr/pal/src/include/pal/context.h index fec5139fd5e405..8f9f99ea2cffb7 100644 --- a/src/coreclr/pal/src/include/pal/context.h +++ b/src/coreclr/pal/src/include/pal/context.h @@ -121,6 +121,7 @@ using asm_sigcontext::_xstate; #ifdef HOST_64BIT #if defined(HOST_LOONGARCH64) + #define MCREG_R0(mc) ((mc).__gregs[0]) #define MCREG_Ra(mc) ((mc).__gregs[1]) #define MCREG_Tp(mc) ((mc).__gregs[2]) @@ -155,7 +156,44 @@ using asm_sigcontext::_xstate; #define MCREG_S8(mc) ((mc).__gregs[31]) #define MCREG_Pc(mc) ((mc).__pc) +#elif defined(HOST_RISCV64) +#error "TODO-RISCV64: review this" + +#define MCREG_Ra(mc) ((mc).__gregs[1]) +#define MCREG_Sp(mc) ((mc).__gregs[2]) +#define MCREG_Gp(mc) ((mc).__gregs[3]) +#define MCREG_Tp(mc) ((mc).__gregs[4]) +#define MCREG_T0(mc) ((mc).__gregs[5]) +#define MCREG_T1(mc) ((mc).__gregs[6]) +#define MCREG_T2(mc) ((mc).__gregs[7]) +#define MCREG_S0(mc) ((mc).__gregs[8]) +#define MCREG_S1(mc) ((mc).__gregs[9]) +#define MCREG_A0(mc) ((mc).__gregs[10]) +#define MCREG_A1(mc) ((mc).__gregs[11]) +#define MCREG_A2(mc) ((mc).__gregs[12]) +#define MCREG_A3(mc) ((mc).__gregs[13]) +#define MCREG_A4(mc) ((mc).__gregs[14]) +#define MCREG_A5(mc) ((mc).__gregs[15]) +#define MCREG_A6(mc) ((mc).__gregs[16]) +#define MCREG_A7(mc) ((mc).__gregs[17]) +#define MCREG_S2(mc) ((mc).__gregs[18]) +#define MCREG_S3(mc) ((mc).__gregs[19]) +#define MCREG_S4(mc) ((mc).__gregs[20]) +#define MCREG_S5(mc) ((mc).__gregs[21]) +#define MCREG_S6(mc) ((mc).__gregs[22]) +#define MCREG_S7(mc) ((mc).__gregs[23]) +#define MCREG_S8(mc) ((mc).__gregs[24]) +#define MCREG_S9(mc) ((mc).__gregs[25]) +#define MCREG_S10(mc) ((mc).__gregs[26]) +#define MCREG_S11(mc) ((mc).__gregs[27]) +#define MCREG_T3(mc) ((mc).__gregs[28]) +#define MCREG_T4(mc) ((mc).__gregs[29]) +#define MCREG_T5(mc) ((mc).__gregs[30]) +#define MCREG_T6(mc) ((mc).__gregs[31]) +#define MCREG_Pc(mc) ((mc).__gregs[0]) + #else // HOST_LOONGARCH64 + #define MCREG_Rbx(mc) ((mc).__gregs[_REG_RBX]) #define MCREG_Rcx(mc) ((mc).__gregs[_REG_RCX]) #define MCREG_Rdx(mc) ((mc).__gregs[_REG_RDX]) @@ -190,7 +228,8 @@ using asm_sigcontext::_xstate; #define FPREG_DataSelector(uc) *((WORD*) &(((struct fxsave*)(&(uc)->uc_mcontext.__fpregs))->fx_dp) + 2) #define FPREG_MxCsr(uc) (((struct fxsave*)(&(uc)->uc_mcontext.__fpregs))->fx_mxcsr) #define FPREG_MxCsr_Mask(uc) (((struct fxsave*)(&(uc)->uc_mcontext.__fpregs))->fx_mxcsr_mask) -#endif + +#endif // HOST_LOONGARCH64 #else // HOST_64BIT @@ -214,6 +253,7 @@ using asm_sigcontext::_xstate; #ifdef HOST_64BIT #if defined(HOST_LOONGARCH64) + #define MCREG_R0(mc) ((mc).gregs[0]) #define MCREG_Ra(mc) ((mc).gregs[1]) #define MCREG_Tp(mc) ((mc).gregs[2]) @@ -247,6 +287,7 @@ using asm_sigcontext::_xstate; #define MCREG_S7(mc) ((mc).gregs[30]) #define MCREG_S8(mc) ((mc).gregs[31]) #define MCREG_Pc(mc) ((mc).pc) + #endif // HOST_LOONGARCH64 #define MCREG_Rbx(mc) ((mc).gregs[REG_RBX]) @@ -535,6 +576,7 @@ const _STRUCT_ARM_NEON_STATE64* GetConstNativeSigSimdContext(const native_contex #endif // TARGET_OSX #elif defined(HOST_LOONGARCH64) + #define MCREG_R0(mc) ((mc).regs[0]) #define MCREG_Ra(mc) ((mc).regs[1]) #define MCREG_Tp(mc) ((mc).regs[2]) @@ -568,6 +610,7 @@ const _STRUCT_ARM_NEON_STATE64* GetConstNativeSigSimdContext(const native_contex #define MCREG_S7(mc) ((mc).regs[30]) #define MCREG_S8(mc) ((mc).regs[31]) #define MCREG_Pc(mc) ((mc).pc) + #else // HOST_ARM64 #ifdef TARGET_OSX @@ -762,6 +805,7 @@ const VfpSigFrame* GetConstNativeSigSimdContext(const native_context_t *mc) #ifdef HOST_64BIT #if defined(HOST_LOONGARCH64) + #define PTREG_R0(ptreg) ((ptreg).regs[0]) #define PTREG_Ra(ptreg) ((ptreg).regs[1]) #define PTREG_Tp(ptreg) ((ptreg).regs[2]) @@ -795,6 +839,7 @@ const VfpSigFrame* GetConstNativeSigSimdContext(const native_context_t *mc) #define PTREG_S7(ptreg) ((ptreg).regs[30]) #define PTREG_S8(ptreg) ((ptreg).regs[31]) #define PTREG_Pc(ptreg) ((ptreg).csr_epc) + #endif // HOST_LOONGARCH64 #if defined(HOST_POWERPC64) @@ -958,16 +1003,12 @@ inline static DWORD64 CONTEXTGetPC(LPCONTEXT pContext) return pContext->Rip; #elif defined(HOST_X86) return pContext->Eip; -#elif defined(HOST_ARM64) || defined(HOST_ARM) - return pContext->Pc; -#elif defined(HOST_LOONGARCH64) - return pContext->Pc; #elif defined(HOST_S390X) return pContext->PSWAddr; #elif defined(HOST_POWERPC64) return pContext->Nip; #else -#error "don't know how to get the program counter for this architecture" + return pContext->Pc; #endif } @@ -977,16 +1018,12 @@ inline static void CONTEXTSetPC(LPCONTEXT pContext, DWORD64 pc) pContext->Rip = pc; #elif defined(HOST_X86) pContext->Eip = pc; -#elif defined(HOST_ARM64) || defined(HOST_ARM) - pContext->Pc = pc; -#elif defined(HOST_LOONGARCH64) - pContext->Pc = pc; #elif defined(HOST_S390X) pContext->PSWAddr = pc; #elif defined(HOST_POWERPC64) pContext->Nip = pc; #else -#error "don't know how to set the program counter for this architecture" + pContext->Pc = pc; #endif } @@ -998,16 +1035,14 @@ inline static DWORD64 CONTEXTGetFP(LPCONTEXT pContext) return pContext->Ebp; #elif defined(HOST_ARM) return pContext->R7; -#elif defined(HOST_ARM64) - return pContext->Fp; -#elif defined(HOST_LOONGARCH64) - return pContext->Fp; #elif defined(HOST_S390X) return pContext->R11; #elif defined(HOST_POWERPC64) return pContext->R31; +#elif defined(HOST_RISCV64) + return pContext->S0; #else -#error "don't know how to get the frame pointer for this architecture" + return pContext->Fp; #endif } diff --git a/src/coreclr/pal/src/misc/perfjitdump.cpp b/src/coreclr/pal/src/misc/perfjitdump.cpp index cc8d46ef1caa49..8d7f79ed3f08bf 100644 --- a/src/coreclr/pal/src/misc/perfjitdump.cpp +++ b/src/coreclr/pal/src/misc/perfjitdump.cpp @@ -48,6 +48,8 @@ namespace ELF_MACHINE = EM_AARCH64, #elif defined(HOST_LOONGARCH64) ELF_MACHINE = EM_LOONGARCH, +#elif defined(HOST_RISCV64) + ELF_MACHINE = EM_RISCV, #elif defined(HOST_S390X) ELF_MACHINE = EM_S390, #elif defined(HOST_POWERPC64) diff --git a/src/coreclr/pal/src/thread/context.cpp b/src/coreclr/pal/src/thread/context.cpp index 184116239ca736..8f49257068cfb6 100644 --- a/src/coreclr/pal/src/thread/context.cpp +++ b/src/coreclr/pal/src/thread/context.cpp @@ -35,20 +35,8 @@ extern PGET_GCMARKER_EXCEPTION_CODE g_getGcMarkerExceptionCode; #define CONTEXT_AREA_MASK 0xffff #ifdef HOST_X86 #define CONTEXT_ALL_FLOATING (CONTEXT_FLOATING_POINT | CONTEXT_EXTENDED_REGISTERS) -#elif defined(HOST_AMD64) -#define CONTEXT_ALL_FLOATING CONTEXT_FLOATING_POINT -#elif defined(HOST_ARM) -#define CONTEXT_ALL_FLOATING CONTEXT_FLOATING_POINT -#elif defined(HOST_ARM64) -#define CONTEXT_ALL_FLOATING CONTEXT_FLOATING_POINT -#elif defined(HOST_LOONGARCH64) -#define CONTEXT_ALL_FLOATING CONTEXT_FLOATING_POINT -#elif defined(HOST_S390X) -#define CONTEXT_ALL_FLOATING CONTEXT_FLOATING_POINT -#elif defined(HOST_POWERPC64) -#define CONTEXT_ALL_FLOATING CONTEXT_FLOATING_POINT #else -#error Unexpected architecture. +#define CONTEXT_ALL_FLOATING CONTEXT_FLOATING_POINT #endif #if !HAVE_MACH_EXCEPTIONS @@ -72,211 +60,253 @@ typedef int __ptrace_request; #ifdef HOST_AMD64 #define ASSIGN_CONTROL_REGS \ - ASSIGN_REG(Rbp) \ - ASSIGN_REG(Rip) \ - ASSIGN_REG(SegCs) \ - ASSIGN_REG(EFlags) \ - ASSIGN_REG(Rsp) \ + ASSIGN_REG(Rbp) \ + ASSIGN_REG(Rip) \ + ASSIGN_REG(SegCs) \ + ASSIGN_REG(EFlags) \ + ASSIGN_REG(Rsp) \ #define ASSIGN_INTEGER_REGS \ - ASSIGN_REG(Rdi) \ - ASSIGN_REG(Rsi) \ - ASSIGN_REG(Rbx) \ - ASSIGN_REG(Rdx) \ - ASSIGN_REG(Rcx) \ - ASSIGN_REG(Rax) \ - ASSIGN_REG(R8) \ - ASSIGN_REG(R9) \ - ASSIGN_REG(R10) \ - ASSIGN_REG(R11) \ - ASSIGN_REG(R12) \ - ASSIGN_REG(R13) \ - ASSIGN_REG(R14) \ - ASSIGN_REG(R15) \ + ASSIGN_REG(Rdi) \ + ASSIGN_REG(Rsi) \ + ASSIGN_REG(Rbx) \ + ASSIGN_REG(Rdx) \ + ASSIGN_REG(Rcx) \ + ASSIGN_REG(Rax) \ + ASSIGN_REG(R8) \ + ASSIGN_REG(R9) \ + ASSIGN_REG(R10) \ + ASSIGN_REG(R11) \ + ASSIGN_REG(R12) \ + ASSIGN_REG(R13) \ + ASSIGN_REG(R14) \ + ASSIGN_REG(R15) \ #elif defined(HOST_X86) #define ASSIGN_CONTROL_REGS \ - ASSIGN_REG(Ebp) \ - ASSIGN_REG(Eip) \ - ASSIGN_REG(SegCs) \ - ASSIGN_REG(EFlags) \ - ASSIGN_REG(Esp) \ - ASSIGN_REG(SegSs) \ + ASSIGN_REG(Ebp) \ + ASSIGN_REG(Eip) \ + ASSIGN_REG(SegCs) \ + ASSIGN_REG(EFlags) \ + ASSIGN_REG(Esp) \ + ASSIGN_REG(SegSs) \ #define ASSIGN_INTEGER_REGS \ - ASSIGN_REG(Edi) \ - ASSIGN_REG(Esi) \ - ASSIGN_REG(Ebx) \ - ASSIGN_REG(Edx) \ - ASSIGN_REG(Ecx) \ - ASSIGN_REG(Eax) \ + ASSIGN_REG(Edi) \ + ASSIGN_REG(Esi) \ + ASSIGN_REG(Ebx) \ + ASSIGN_REG(Edx) \ + ASSIGN_REG(Ecx) \ + ASSIGN_REG(Eax) \ #elif defined(HOST_ARM) #define ASSIGN_CONTROL_REGS \ - ASSIGN_REG(Sp) \ - ASSIGN_REG(Lr) \ - ASSIGN_REG(Pc) \ - ASSIGN_REG(Cpsr) \ + ASSIGN_REG(Sp) \ + ASSIGN_REG(Lr) \ + ASSIGN_REG(Pc) \ + ASSIGN_REG(Cpsr) \ #define ASSIGN_INTEGER_REGS \ - ASSIGN_REG(R0) \ - ASSIGN_REG(R1) \ - ASSIGN_REG(R2) \ - ASSIGN_REG(R3) \ - ASSIGN_REG(R4) \ - ASSIGN_REG(R5) \ - ASSIGN_REG(R6) \ - ASSIGN_REG(R7) \ - ASSIGN_REG(R8) \ - ASSIGN_REG(R9) \ - ASSIGN_REG(R10) \ - ASSIGN_REG(R11) \ - ASSIGN_REG(R12) + ASSIGN_REG(R0) \ + ASSIGN_REG(R1) \ + ASSIGN_REG(R2) \ + ASSIGN_REG(R3) \ + ASSIGN_REG(R4) \ + ASSIGN_REG(R5) \ + ASSIGN_REG(R6) \ + ASSIGN_REG(R7) \ + ASSIGN_REG(R8) \ + ASSIGN_REG(R9) \ + ASSIGN_REG(R10) \ + ASSIGN_REG(R11) \ + ASSIGN_REG(R12) #elif defined(HOST_ARM64) #define ASSIGN_CONTROL_REGS \ - ASSIGN_REG(Cpsr) \ - ASSIGN_REG(Fp) \ - ASSIGN_REG(Sp) \ - ASSIGN_REG(Lr) \ - ASSIGN_REG(Pc) + ASSIGN_REG(Cpsr) \ + ASSIGN_REG(Fp) \ + ASSIGN_REG(Sp) \ + ASSIGN_REG(Lr) \ + ASSIGN_REG(Pc) #define ASSIGN_INTEGER_REGS \ - ASSIGN_REG(X0) \ - ASSIGN_REG(X1) \ - ASSIGN_REG(X2) \ - ASSIGN_REG(X3) \ - ASSIGN_REG(X4) \ - ASSIGN_REG(X5) \ - ASSIGN_REG(X6) \ - ASSIGN_REG(X7) \ - ASSIGN_REG(X8) \ - ASSIGN_REG(X9) \ - ASSIGN_REG(X10) \ - ASSIGN_REG(X11) \ - ASSIGN_REG(X12) \ - ASSIGN_REG(X13) \ - ASSIGN_REG(X14) \ - ASSIGN_REG(X15) \ - ASSIGN_REG(X16) \ - ASSIGN_REG(X17) \ - ASSIGN_REG(X18) \ - ASSIGN_REG(X19) \ - ASSIGN_REG(X20) \ - ASSIGN_REG(X21) \ - ASSIGN_REG(X22) \ - ASSIGN_REG(X23) \ - ASSIGN_REG(X24) \ - ASSIGN_REG(X25) \ - ASSIGN_REG(X26) \ - ASSIGN_REG(X27) \ - ASSIGN_REG(X28) + ASSIGN_REG(X0) \ + ASSIGN_REG(X1) \ + ASSIGN_REG(X2) \ + ASSIGN_REG(X3) \ + ASSIGN_REG(X4) \ + ASSIGN_REG(X5) \ + ASSIGN_REG(X6) \ + ASSIGN_REG(X7) \ + ASSIGN_REG(X8) \ + ASSIGN_REG(X9) \ + ASSIGN_REG(X10) \ + ASSIGN_REG(X11) \ + ASSIGN_REG(X12) \ + ASSIGN_REG(X13) \ + ASSIGN_REG(X14) \ + ASSIGN_REG(X15) \ + ASSIGN_REG(X16) \ + ASSIGN_REG(X17) \ + ASSIGN_REG(X18) \ + ASSIGN_REG(X19) \ + ASSIGN_REG(X20) \ + ASSIGN_REG(X21) \ + ASSIGN_REG(X22) \ + ASSIGN_REG(X23) \ + ASSIGN_REG(X24) \ + ASSIGN_REG(X25) \ + ASSIGN_REG(X26) \ + ASSIGN_REG(X27) \ + ASSIGN_REG(X28) #elif defined(HOST_LOONGARCH64) #define ASSIGN_CONTROL_REGS \ - ASSIGN_REG(Fp) \ - ASSIGN_REG(Sp) \ - ASSIGN_REG(Ra) \ - ASSIGN_REG(Pc) + ASSIGN_REG(Fp) \ + ASSIGN_REG(Sp) \ + ASSIGN_REG(Ra) \ + ASSIGN_REG(Pc) +#define ASSIGN_INTEGER_REGS \ + ASSIGN_REG(R0) \ + ASSIGN_REG(Tp) \ + ASSIGN_REG(A0) \ + ASSIGN_REG(A1) \ + ASSIGN_REG(A2) \ + ASSIGN_REG(A3) \ + ASSIGN_REG(A4) \ + ASSIGN_REG(A5) \ + ASSIGN_REG(A6) \ + ASSIGN_REG(A7) \ + ASSIGN_REG(T0) \ + ASSIGN_REG(T1) \ + ASSIGN_REG(T2) \ + ASSIGN_REG(T3) \ + ASSIGN_REG(T4) \ + ASSIGN_REG(T5) \ + ASSIGN_REG(T6) \ + ASSIGN_REG(T7) \ + ASSIGN_REG(T8) \ + ASSIGN_REG(S0) \ + ASSIGN_REG(S1) \ + ASSIGN_REG(S2) \ + ASSIGN_REG(S3) \ + ASSIGN_REG(S4) \ + ASSIGN_REG(S5) \ + ASSIGN_REG(S6) \ + ASSIGN_REG(S7) \ + ASSIGN_REG(S8) \ + ASSIGN_REG(X0) + +#elif defined(HOST_RISCV64) + +#error "TODO-RISCV64: review this" + +// https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/2d865a2964fe06bfc569ab00c74e152b582ed764/riscv-cc.adoc + +#define ASSIGN_CONTROL_REGS \ + ASSIGN_REG(Ra) \ + ASSIGN_REG(Sp) \ + ASSIGN_REG(Sp) \ + ASSIGN_REG(Gp) \ + ASSIGN_REG(Tp) \ + ASSIGN_REG(Pc) #define ASSIGN_INTEGER_REGS \ - ASSIGN_REG(R0) \ - ASSIGN_REG(Tp) \ - ASSIGN_REG(A0) \ - ASSIGN_REG(A1) \ - ASSIGN_REG(A2) \ - ASSIGN_REG(A3) \ - ASSIGN_REG(A4) \ - ASSIGN_REG(A5) \ - ASSIGN_REG(A6) \ - ASSIGN_REG(A7) \ - ASSIGN_REG(T0) \ - ASSIGN_REG(T1) \ - ASSIGN_REG(T2) \ - ASSIGN_REG(T3) \ - ASSIGN_REG(T4) \ - ASSIGN_REG(T5) \ - ASSIGN_REG(T6) \ - ASSIGN_REG(T7) \ - ASSIGN_REG(T8) \ - ASSIGN_REG(S0) \ - ASSIGN_REG(S1) \ - ASSIGN_REG(S2) \ - ASSIGN_REG(S3) \ - ASSIGN_REG(S4) \ - ASSIGN_REG(S5) \ - ASSIGN_REG(S6) \ - ASSIGN_REG(S7) \ - ASSIGN_REG(S8) \ - ASSIGN_REG(X0) + ASSIGN_REG(T0) \ + ASSIGN_REG(T1) \ + ASSIGN_REG(T2) \ + ASSIGN_REG(S0) \ + ASSIGN_REG(S1) \ + ASSIGN_REG(A0) \ + ASSIGN_REG(A1) \ + ASSIGN_REG(A2) \ + ASSIGN_REG(A3) \ + ASSIGN_REG(A4) \ + ASSIGN_REG(A5) \ + ASSIGN_REG(A6) \ + ASSIGN_REG(A7) \ + ASSIGN_REG(S2) \ + ASSIGN_REG(S3) \ + ASSIGN_REG(S4) \ + ASSIGN_REG(S5) \ + ASSIGN_REG(S6) \ + ASSIGN_REG(S7) \ + ASSIGN_REG(S8) \ + ASSIGN_REG(S9) \ + ASSIGN_REG(S10) \ + ASSIGN_REG(S11) \ + ASSIGN_REG(T3) \ + ASSIGN_REG(T4) \ + ASSIGN_REG(T5) \ + ASSIGN_REG(T6) #elif defined(HOST_S390X) #define ASSIGN_CONTROL_REGS \ - ASSIGN_REG(PSWMask) \ - ASSIGN_REG(PSWAddr) \ - ASSIGN_REG(R15) \ + ASSIGN_REG(PSWMask) \ + ASSIGN_REG(PSWAddr) \ + ASSIGN_REG(R15) \ #define ASSIGN_INTEGER_REGS \ - ASSIGN_REG(R0) \ - ASSIGN_REG(R1) \ - ASSIGN_REG(R2) \ - ASSIGN_REG(R3) \ - ASSIGN_REG(R4) \ - ASSIGN_REG(R5) \ - ASSIGN_REG(R5) \ - ASSIGN_REG(R6) \ - ASSIGN_REG(R7) \ - ASSIGN_REG(R8) \ - ASSIGN_REG(R9) \ - ASSIGN_REG(R10) \ - ASSIGN_REG(R11) \ - ASSIGN_REG(R12) \ - ASSIGN_REG(R13) \ - ASSIGN_REG(R14) + ASSIGN_REG(R0) \ + ASSIGN_REG(R1) \ + ASSIGN_REG(R2) \ + ASSIGN_REG(R3) \ + ASSIGN_REG(R4) \ + ASSIGN_REG(R5) \ + ASSIGN_REG(R5) \ + ASSIGN_REG(R6) \ + ASSIGN_REG(R7) \ + ASSIGN_REG(R8) \ + ASSIGN_REG(R9) \ + ASSIGN_REG(R10) \ + ASSIGN_REG(R11) \ + ASSIGN_REG(R12) \ + ASSIGN_REG(R13) \ + ASSIGN_REG(R14) #elif defined(HOST_POWERPC64) #define ASSIGN_CONTROL_REGS \ - ASSIGN_REG(Nip) \ - ASSIGN_REG(Msr) \ - ASSIGN_REG(Ctr) \ - ASSIGN_REG(Link) \ - ASSIGN_REG(Xer) \ - ASSIGN_REG(Ccr) \ - ASSIGN_REG(R31) \ + ASSIGN_REG(Nip) \ + ASSIGN_REG(Msr) \ + ASSIGN_REG(Ctr) \ + ASSIGN_REG(Link) \ + ASSIGN_REG(Xer) \ + ASSIGN_REG(Ccr) \ + ASSIGN_REG(R31) \ #define ASSIGN_INTEGER_REGS \ - ASSIGN_REG(R0) \ - ASSIGN_REG(R1) \ - ASSIGN_REG(R2) \ - ASSIGN_REG(R3) \ - ASSIGN_REG(R4) \ - ASSIGN_REG(R5) \ - ASSIGN_REG(R5) \ - ASSIGN_REG(R6) \ - ASSIGN_REG(R7) \ - ASSIGN_REG(R8) \ - ASSIGN_REG(R9) \ - ASSIGN_REG(R10) \ - ASSIGN_REG(R11) \ - ASSIGN_REG(R12) \ - ASSIGN_REG(R13) \ - ASSIGN_REG(R14) \ - ASSIGN_REG(R15) \ - ASSIGN_REG(R16) \ - ASSIGN_REG(R17) \ - ASSIGN_REG(R18) \ - ASSIGN_REG(R19) \ - ASSIGN_REG(R20) \ - ASSIGN_REG(R21) \ - ASSIGN_REG(R22) \ - ASSIGN_REG(R23) \ - ASSIGN_REG(R24) \ - ASSIGN_REG(R25) \ - ASSIGN_REG(R26) \ - ASSIGN_REG(R27) \ - ASSIGN_REG(R28) \ - ASSIGN_REG(R29) \ - ASSIGN_REG(R30) + ASSIGN_REG(R0) \ + ASSIGN_REG(R1) \ + ASSIGN_REG(R2) \ + ASSIGN_REG(R3) \ + ASSIGN_REG(R4) \ + ASSIGN_REG(R5) \ + ASSIGN_REG(R5) \ + ASSIGN_REG(R6) \ + ASSIGN_REG(R7) \ + ASSIGN_REG(R8) \ + ASSIGN_REG(R9) \ + ASSIGN_REG(R10) \ + ASSIGN_REG(R11) \ + ASSIGN_REG(R12) \ + ASSIGN_REG(R13) \ + ASSIGN_REG(R14) \ + ASSIGN_REG(R15) \ + ASSIGN_REG(R16) \ + ASSIGN_REG(R17) \ + ASSIGN_REG(R18) \ + ASSIGN_REG(R19) \ + ASSIGN_REG(R20) \ + ASSIGN_REG(R21) \ + ASSIGN_REG(R22) \ + ASSIGN_REG(R23) \ + ASSIGN_REG(R24) \ + ASSIGN_REG(R25) \ + ASSIGN_REG(R26) \ + ASSIGN_REG(R27) \ + ASSIGN_REG(R28) \ + ASSIGN_REG(R29) \ + ASSIGN_REG(R30) #else #error "Don't know how to assign registers on this architecture" @@ -545,7 +575,7 @@ void CONTEXTToNativeContext(CONST CONTEXT *lpContext, native_context_t *native) #undef ASSIGN_REG #if !HAVE_FPREGS_WITH_CW -#if (HAVE_GREGSET_T || HAVE___GREGSET_T) && !defined(HOST_S390X) && !defined(HOST_LOONGARCH64) && !defined(HOST_POWERPC64) +#if (HAVE_GREGSET_T || HAVE___GREGSET_T) && !defined(HOST_S390X) && !defined(HOST_LOONGARCH64) && !defined(HOST_RISCV64) && !defined(HOST_POWERPC64) #if HAVE_GREGSET_T if (native->uc_mcontext.fpregs == nullptr) #elif HAVE___GREGSET_T @@ -557,7 +587,7 @@ void CONTEXTToNativeContext(CONST CONTEXT *lpContext, native_context_t *native) // whether CONTEXT_FLOATING_POINT is set in the CONTEXT's flags. return; } -#endif // (HAVE_GREGSET_T || HAVE___GREGSET_T) && !HOST_S390X && !HOST_LOONGARCH64 && !HOST_POWERPC64 +#endif // (HAVE_GREGSET_T || HAVE___GREGSET_T) && !HOST_S390X && !HOST_LOONGARCH64 && !HOST_RISCV64 && !HOST_POWERPC64 #endif // !HAVE_FPREGS_WITH_CW if ((lpContext->ContextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT) @@ -623,10 +653,17 @@ void CONTEXTToNativeContext(CONST CONTEXT *lpContext, native_context_t *native) static_assert_no_msg(sizeof(fp->fprs) == sizeof(lpContext->Fpr)); memcpy(fp->fprs, lpContext->Fpr, sizeof(lpContext->Fpr)); #elif defined(HOST_LOONGARCH64) + native->uc_mcontext.__fcsr = lpContext->Fcsr; for (int i = 0; i < 32; i++) { native->uc_mcontext.__fpregs[i].__val64[0] = lpContext->F[i]; } +#elif defined(HOST_RISCV64) + native->uc_mcontext.__fpregs.__d.__fcsr = lpContext->Fcsr; + for (int i = 0; i < 64; i++) + { + native->uc_mcontext.__fpregs.__d.__f[i] = lpContext->F[i]; + } #endif } @@ -680,7 +717,7 @@ void CONTEXTFromNativeContext(const native_context_t *native, LPCONTEXT lpContex #undef ASSIGN_REG #if !HAVE_FPREGS_WITH_CW -#if (HAVE_GREGSET_T || HAVE___GREGSET_T) && !defined(HOST_S390X) && !defined(HOST_LOONGARCH64) && !defined(HOST_POWERPC64) +#if (HAVE_GREGSET_T || HAVE___GREGSET_T) && !defined(HOST_S390X) && !defined(HOST_LOONGARCH64) && !defined(HOST_RISCV64) && !defined(HOST_POWERPC64) #if HAVE_GREGSET_T if (native->uc_mcontext.fpregs == nullptr) #elif HAVE___GREGSET_T @@ -702,7 +739,7 @@ void CONTEXTFromNativeContext(const native_context_t *native, LPCONTEXT lpContex // Bail out regardless of whether the caller wanted CONTEXT_FLOATING_POINT or CONTEXT_XSTATE return; } -#endif // (HAVE_GREGSET_T || HAVE___GREGSET_T) && !HOST_S390X && !HOST_POWERPC64 +#endif // (HAVE_GREGSET_T || HAVE___GREGSET_T) && !HOST_S390X && !HOST_LOONGARCH64 && !HOST_RISCV64 && !HOST_POWERPC64 && !HOST_POWERPC64 #endif // !HAVE_FPREGS_WITH_CW if ((contextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT) @@ -778,6 +815,12 @@ void CONTEXTFromNativeContext(const native_context_t *native, LPCONTEXT lpContex { lpContext->F[i] = native->uc_mcontext.__fpregs[i].__val64[0]; } +#elif defined(HOST_RISCV64) + lpContext->Fcsr = native->uc_mcontext.__fpregs.__d.__fcsr; + for (int i = 0; i < 64; i++) + { + lpContext->F[i] = native->uc_mcontext.__fpregs.__d.__f[i]; + } #endif } @@ -823,18 +866,12 @@ LPVOID GetNativeContextPC(const native_context_t *context) return (LPVOID)MCREG_Rip(context->uc_mcontext); #elif defined(HOST_X86) return (LPVOID) MCREG_Eip(context->uc_mcontext); -#elif defined(HOST_ARM) - return (LPVOID) MCREG_Pc(context->uc_mcontext); -#elif defined(HOST_ARM64) - return (LPVOID) MCREG_Pc(context->uc_mcontext); -#elif defined(HOST_LOONGARCH64) - return (LPVOID) MCREG_Pc(context->uc_mcontext); #elif defined(HOST_S390X) return (LPVOID) MCREG_PSWAddr(context->uc_mcontext); #elif defined(HOST_POWERPC64) return (LPVOID) MCREG_Nip(context->uc_mcontext); #else -# error implement me for this architecture + return (LPVOID) MCREG_Pc(context->uc_mcontext); #endif } @@ -857,18 +894,12 @@ LPVOID GetNativeContextSP(const native_context_t *context) return (LPVOID)MCREG_Rsp(context->uc_mcontext); #elif defined(HOST_X86) return (LPVOID) MCREG_Esp(context->uc_mcontext); -#elif defined(HOST_ARM) - return (LPVOID) MCREG_Sp(context->uc_mcontext); -#elif defined(HOST_ARM64) - return (LPVOID) MCREG_Sp(context->uc_mcontext); -#elif defined(HOST_LOONGARCH64) - return (LPVOID) MCREG_Sp(context->uc_mcontext); #elif defined(HOST_S390X) return (LPVOID) MCREG_R15(context->uc_mcontext); #elif defined(HOST_POWERPC64) return (LPVOID) MCREG_R31(context->uc_mcontext); #else -# error implement me for this architecture + return (LPVOID) MCREG_Sp(context->uc_mcontext); #endif }