From 53780c95133fd316834af820e88da366239dae0d Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
 <41898282+github-actions[bot]@users.noreply.github.com>
Date: Tue, 13 Aug 2024 10:37:57 -0700
Subject: [PATCH 01/21] [release/8.0-staging] Disable W^X in Rosetta emulated
 x64 containers on macOS (#105117)

* Disable W^X on x64 in rosetta based container

The docker on macOS Arm64 uses Rosetta to run x64 containers. That
has an effect on the double mapping. The Rosetta is unable to detect
when an already executed code page is modified. So we cannot use double
mapping on those containers. To detect that case, this change adds check
that verifies that the double mapping works even when the code is
modified.

Close #102226

* Rework based on PR feedback

* Check only for Rosetta

* Enable the rosetta check for x86 too

This will help WINE running 32 bit code under rosetta emulation on
macOS.

---------

Co-authored-by: Jan Vorlicek <janvorli@microsoft.com>
---
 src/coreclr/minipal/CMakeLists.txt            |  1 +
 src/coreclr/minipal/Unix/doublemapping.cpp    | 33 ++++++-----------
 src/coreclr/minipal/Windows/doublemapping.cpp |  7 ++++
 src/native/minipal/cpufeatures.c              | 35 +++++++++++++++++++
 src/native/minipal/cpufeatures.h              |  1 +
 5 files changed, 54 insertions(+), 23 deletions(-)

diff --git a/src/coreclr/minipal/CMakeLists.txt b/src/coreclr/minipal/CMakeLists.txt
index 3096237d2a2fe3..78a1726af3e815 100644
--- a/src/coreclr/minipal/CMakeLists.txt
+++ b/src/coreclr/minipal/CMakeLists.txt
@@ -1,4 +1,5 @@
 include_directories(.)
+include_directories(${CLR_SRC_NATIVE_DIR})
 if (CLR_CMAKE_HOST_UNIX)
     add_subdirectory(Unix)
 else (CLR_CMAKE_HOST_UNIX)
diff --git a/src/coreclr/minipal/Unix/doublemapping.cpp b/src/coreclr/minipal/Unix/doublemapping.cpp
index cb65e5e284e2b3..67d516fb322a56 100644
--- a/src/coreclr/minipal/Unix/doublemapping.cpp
+++ b/src/coreclr/minipal/Unix/doublemapping.cpp
@@ -20,24 +20,13 @@
 #define memfd_create(...) syscall(__NR_memfd_create, __VA_ARGS__)
 #endif // TARGET_LINUX && !MFD_CLOEXEC
 #include "minipal.h"
+#include "minipal/cpufeatures.h"
 
-#if defined(TARGET_OSX) && defined(TARGET_AMD64)
-#include <mach/mach.h>
-#include <sys/sysctl.h>
+#ifdef TARGET_OSX
 
-bool IsProcessTranslated()
-{
-   int ret = 0;
-   size_t size = sizeof(ret);
-   if (sysctlbyname("sysctl.proc_translated", &ret, &size, NULL, 0) == -1)
-   {
-      return false;
-   }
-   return ret == 1;
-}
-#endif // TARGET_OSX && TARGET_AMD64
+#include <mach/mach.h>
 
-#ifndef TARGET_OSX
+#else // TARGET_OSX
 
 #ifdef TARGET_64BIT
 static const off_t MaxDoubleMappedSize = 2048ULL*1024*1024*1024;
@@ -49,6 +38,12 @@ static const off_t MaxDoubleMappedSize = UINT_MAX;
 
 bool VMToOSInterface::CreateDoubleMemoryMapper(void** pHandle, size_t *pMaxExecutableCodeSize)
 {
+    if (minipal_detect_rosetta())
+    {
+        // Rosetta doesn't support double mapping correctly
+        return false;
+    }
+
 #ifndef TARGET_OSX
 
 #ifdef TARGET_FREEBSD
@@ -78,14 +73,6 @@ bool VMToOSInterface::CreateDoubleMemoryMapper(void** pHandle, size_t *pMaxExecu
     *pHandle = (void*)(size_t)fd;
 #else // !TARGET_OSX
 
-#ifdef TARGET_AMD64
-    if (IsProcessTranslated())
-    {
-        // Rosetta doesn't support double mapping correctly
-        return false;
-    }
-#endif // TARGET_AMD64
-
     *pMaxExecutableCodeSize = SIZE_MAX;
     *pHandle = NULL;
 #endif // !TARGET_OSX
diff --git a/src/coreclr/minipal/Windows/doublemapping.cpp b/src/coreclr/minipal/Windows/doublemapping.cpp
index 0d7033b567056c..9e8ddfed8e964d 100644
--- a/src/coreclr/minipal/Windows/doublemapping.cpp
+++ b/src/coreclr/minipal/Windows/doublemapping.cpp
@@ -6,6 +6,7 @@
 #include <inttypes.h>
 #include <assert.h>
 #include "minipal.h"
+#include "minipal/cpufeatures.h"
 
 #define HIDWORD(_qw)    ((ULONG)((_qw) >> 32))
 #define LODWORD(_qw)    ((ULONG)(_qw))
@@ -60,6 +61,12 @@ inline void *GetBotMemoryAddress(void)
 
 bool VMToOSInterface::CreateDoubleMemoryMapper(void **pHandle, size_t *pMaxExecutableCodeSize)
 {
+    if (minipal_detect_rosetta())
+    {
+        // Rosetta doesn't support double mapping correctly. WINE on macOS ARM64 can be running under Rosetta.
+        return false;
+    }
+
     *pMaxExecutableCodeSize = (size_t)MaxDoubleMappedSize;
     *pHandle = CreateFileMapping(
                  INVALID_HANDLE_VALUE,    // use paging file
diff --git a/src/native/minipal/cpufeatures.c b/src/native/minipal/cpufeatures.c
index be0aabe081c9fc..56ec81993c8521 100644
--- a/src/native/minipal/cpufeatures.c
+++ b/src/native/minipal/cpufeatures.c
@@ -4,6 +4,8 @@
 #include <stdint.h>
 #include <stdbool.h>
 #include <stddef.h>
+#include <stdio.h>
+#include <string.h>
 
 #include "cpufeatures.h"
 #include "cpuid.h"
@@ -427,3 +429,36 @@ int minipal_getcpufeatures(void)
 
     return result;
 }
+
+// Detect if the current process is running under the Apple Rosetta x64 emulator
+bool minipal_detect_rosetta(void)
+{
+#if defined(HOST_AMD64) || defined(HOST_X86)
+    // Check for CPU brand indicating emulation
+    int regs[4];
+    char brand[49];
+
+    // Get the maximum value for extended function CPUID info
+    __cpuid(regs, (int)0x80000000);
+    if ((unsigned int)regs[0] < 0x80000004)
+    {
+        return false; // Extended CPUID not supported
+    }
+
+    // Retrieve the CPU brand string
+    for (unsigned int i = 0x80000002; i <= 0x80000004; ++i)
+    {
+        __cpuid(regs, (int)i);
+        memcpy(brand + (i - 0x80000002) * sizeof(regs), regs, sizeof(regs));
+    }
+    brand[sizeof(brand) - 1] = '\0';
+
+    // Check if CPU brand indicates emulation
+    if (strstr(brand, "VirtualApple") != NULL)
+    {
+        return true;
+    }
+#endif // HOST_AMD64 || HOST_X86
+
+    return false;
+}
diff --git a/src/native/minipal/cpufeatures.h b/src/native/minipal/cpufeatures.h
index 73d151f1e2d80f..a985cf0fc92379 100644
--- a/src/native/minipal/cpufeatures.h
+++ b/src/native/minipal/cpufeatures.h
@@ -72,6 +72,7 @@ extern "C"
 #endif // __cplusplus
 
 int minipal_getcpufeatures(void);
+bool minipal_detect_rosetta(void);
 
 #ifdef __cplusplus
 }

From 42ababd320b7784fd2e05f7a8c1d8b3d698bca89 Mon Sep 17 00:00:00 2001
From: Tanner Gooding <tagoo@outlook.com>
Date: Tue, 13 Aug 2024 19:07:45 -0700
Subject: [PATCH 02/21] Ensure we consistently broadcast the result of simd dot
 product (#106031)

---
 src/coreclr/jit/lowerxarch.cpp                |  9 ++--
 src/coreclr/jit/morph.cpp                     | 10 ----
 .../JitBlue/Runtime_99391/Runtime_99391.cs    | 50 +++++++++++++++++++
 .../Runtime_99391/Runtime_99391.csproj        | 11 ++++
 4 files changed, 65 insertions(+), 15 deletions(-)
 create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_99391/Runtime_99391.cs
 create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_99391/Runtime_99391.csproj

diff --git a/src/coreclr/jit/lowerxarch.cpp b/src/coreclr/jit/lowerxarch.cpp
index 8f3150e7e7b18e..7c309288de1eb6 100644
--- a/src/coreclr/jit/lowerxarch.cpp
+++ b/src/coreclr/jit/lowerxarch.cpp
@@ -4865,8 +4865,9 @@ GenTree* Lowering::LowerHWIntrinsicDot(GenTreeHWIntrinsic* node)
 
                 horizontalAdd = NI_SSE3_HorizontalAdd;
 
-                if (!comp->compOpportunisticallyDependsOn(InstructionSet_SSE3))
+                if ((simdSize == 8) || !comp->compOpportunisticallyDependsOn(InstructionSet_SSE3))
                 {
+                    // We also do this for simdSize == 8 to ensure we broadcast the result as expected
                     shuffle = NI_SSE_Shuffle;
                 }
                 break;
@@ -4917,10 +4918,8 @@ GenTree* Lowering::LowerHWIntrinsicDot(GenTreeHWIntrinsic* node)
 
                 horizontalAdd = NI_SSE3_HorizontalAdd;
 
-                if (!comp->compOpportunisticallyDependsOn(InstructionSet_SSE3))
-                {
-                    shuffle = NI_SSE2_Shuffle;
-                }
+                // We need to ensure we broadcast the result as expected
+                shuffle = NI_SSE2_Shuffle;
                 break;
             }
 
diff --git a/src/coreclr/jit/morph.cpp b/src/coreclr/jit/morph.cpp
index b20cd585882b87..3deada8eec085b 100644
--- a/src/coreclr/jit/morph.cpp
+++ b/src/coreclr/jit/morph.cpp
@@ -10724,16 +10724,6 @@ GenTree* Compiler::fgOptimizeHWIntrinsic(GenTreeHWIntrinsic* node)
                 break;
             }
 
-#if defined(TARGET_XARCH)
-            if ((node->GetSimdSize() == 8) && !compOpportunisticallyDependsOn(InstructionSet_SSE41))
-            {
-                // When SSE4.1 isn't supported then Vector2 only needs a single horizontal add
-                // which means the result isn't broadcast across the entire vector and we can't
-                // optimize
-                break;
-            }
-#endif // TARGET_XARCH
-
             GenTree* op1      = node->Op(1);
             GenTree* sqrt     = nullptr;
             GenTree* toScalar = nullptr;
diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_99391/Runtime_99391.cs b/src/tests/JIT/Regression/JitBlue/Runtime_99391/Runtime_99391.cs
new file mode 100644
index 00000000000000..6033a74cdd6645
--- /dev/null
+++ b/src/tests/JIT/Regression/JitBlue/Runtime_99391/Runtime_99391.cs
@@ -0,0 +1,50 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System;
+using System.Runtime.CompilerServices;
+using System.Numerics;
+using Xunit;
+
+public class Runtime_99391
+{
+    [Fact]
+    public static void TestEntryPoint()
+    {
+        Vector2 result2a = Vector2.Normalize(Value2);
+        Assert.Equal(new Vector2(0, 1), result2a);
+
+        Vector2 result2b = Vector2.Normalize(new Vector2(0, 2));
+        Assert.Equal(new Vector2(0, 1), result2b);
+
+        Vector3 result3a = Vector3.Normalize(Value3);
+        Assert.Equal(new Vector3(0, 0, 1), result3a);
+
+        Vector3 result3b = Vector3.Normalize(new Vector3(0, 0, 2));
+        Assert.Equal(new Vector3(0, 0, 1), result3b);
+
+        Vector4 result4a = Vector4.Normalize(Value4);
+        Assert.Equal(new Vector4(0, 0, 0, 1), result4a);
+
+        Vector4 result4b = Vector4.Normalize(new Vector4(0, 0, 0, 2));
+        Assert.Equal(new Vector4(0, 0, 0, 1), result4b);
+    }
+
+    private static Vector2 Value2
+    {
+        [MethodImpl(MethodImplOptions.NoInlining)]
+        get => new Vector2(0, 2);
+    }
+
+    private static Vector3 Value3
+    {
+        [MethodImpl(MethodImplOptions.NoInlining)]
+        get => new Vector3(0, 0, 2);
+    }
+
+    private static Vector4 Value4
+    {
+        [MethodImpl(MethodImplOptions.NoInlining)]
+        get => new Vector4(0, 0, 0, 2);
+    }
+}
diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_99391/Runtime_99391.csproj b/src/tests/JIT/Regression/JitBlue/Runtime_99391/Runtime_99391.csproj
new file mode 100644
index 00000000000000..efa9e9b022442a
--- /dev/null
+++ b/src/tests/JIT/Regression/JitBlue/Runtime_99391/Runtime_99391.csproj
@@ -0,0 +1,11 @@
+<Project Sdk="Microsoft.NET.Sdk">
+  <PropertyGroup>
+    <Optimize>True</Optimize>
+  </PropertyGroup>
+  <ItemGroup>
+    <Compile Include="$(MSBuildProjectName).cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <CLRTestEnvironmentVariable Include="DOTNET_TieredCompilation" Value="0" />
+  </ItemGroup>
+</Project>

From 5ce9f8447ec01a3aae0b7b471cf7c170e477bc99 Mon Sep 17 00:00:00 2001
From: "dotnet-maestro[bot]"
 <42748379+dotnet-maestro[bot]@users.noreply.github.com>
Date: Mon, 19 Aug 2024 14:35:18 -0700
Subject: [PATCH 03/21] Update dependencies from
 https://github.com/dotnet/source-build-reference-packages build 20240815.1
 (#106626)

Microsoft.SourceBuild.Intermediate.source-build-reference-packages
 From Version 8.0.0-alpha.1.24372.3 -> To Version 8.0.0-alpha.1.24415.1

Co-authored-by: dotnet-maestro[bot] <dotnet-maestro[bot]@users.noreply.github.com>
---
 NuGet.config            | 10 ----------
 eng/Version.Details.xml |  4 ++--
 2 files changed, 2 insertions(+), 12 deletions(-)

diff --git a/NuGet.config b/NuGet.config
index 961d774f91d772..0dff023e179ae1 100644
--- a/NuGet.config
+++ b/NuGet.config
@@ -10,16 +10,6 @@
     <!--Begin: Package sources managed by Dependency Flow automation. Do not edit the sources below.-->
     <!--  Begin: Package sources from dotnet-emsdk -->
     <add key="darc-pub-dotnet-emsdk-2674f58" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-2674f580/nuget/v3/index.json" />
-    <add key="darc-pub-dotnet-emsdk-e92f92e" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-e92f92ef/nuget/v3/index.json" />
-    <add key="darc-pub-dotnet-emsdk-e92f92e-9" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-e92f92ef-9/nuget/v3/index.json" />
-    <add key="darc-pub-dotnet-emsdk-e92f92e-8" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-e92f92ef-8/nuget/v3/index.json" />
-    <add key="darc-pub-dotnet-emsdk-e92f92e-7" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-e92f92ef-7/nuget/v3/index.json" />
-    <add key="darc-pub-dotnet-emsdk-e92f92e-6" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-e92f92ef-6/nuget/v3/index.json" />
-    <add key="darc-pub-dotnet-emsdk-e92f92e-5" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-e92f92ef-5/nuget/v3/index.json" />
-    <add key="darc-pub-dotnet-emsdk-e92f92e-4" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-e92f92ef-4/nuget/v3/index.json" />
-    <add key="darc-pub-dotnet-emsdk-e92f92e-3" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-e92f92ef-3/nuget/v3/index.json" />
-    <add key="darc-pub-dotnet-emsdk-e92f92e-2" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-e92f92ef-2/nuget/v3/index.json" />
-    <add key="darc-pub-dotnet-emsdk-e92f92e-1" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-e92f92ef-1/nuget/v3/index.json" />
     <!--  End: Package sources from dotnet-emsdk -->
     <!--  Begin: Package sources from dotnet-sdk -->
     <!--  End: Package sources from dotnet-sdk -->
diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml
index 8c6dbdb2bf4f9a..fce32fe924a830 100644
--- a/eng/Version.Details.xml
+++ b/eng/Version.Details.xml
@@ -99,9 +99,9 @@
       <Sha>2674f580a4b1d27322914df8488498065e71a3f2</Sha>
       <SourceBuild RepoName="emsdk" ManagedOnly="true" />
     </Dependency>
-    <Dependency Name="Microsoft.SourceBuild.Intermediate.source-build-reference-packages" Version="8.0.0-alpha.1.24372.3">
+    <Dependency Name="Microsoft.SourceBuild.Intermediate.source-build-reference-packages" Version="8.0.0-alpha.1.24415.1">
       <Uri>https://github.com/dotnet/source-build-reference-packages</Uri>
-      <Sha>30ed464acd37779c64e9dc652d4460543ebf9966</Sha>
+      <Sha>fe3794a68bd668d36d4d5014a9e6c9d22c0e6d86</Sha>
       <SourceBuild RepoName="source-build-reference-packages" ManagedOnly="true" />
     </Dependency>
     <Dependency Name="Microsoft.SourceBuild.Intermediate.source-build-externals" Version="8.0.0-alpha.1.24379.1">

From 78b77de1461f3266b0f2fe8aa125caf9b8b2175e Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
 <41898282+github-actions[bot]@users.noreply.github.com>
Date: Wed, 21 Aug 2024 10:31:10 -0700
Subject: [PATCH 04/21] [release/8.0-staging] Fix Type System Equivalence
 Checks (#106667)

* Initial fix for the type not being read bug.

* Addressed initial feedback to fully fix the bug.

---------

Co-authored-by: Ivan Diaz <ivdiazsa@microsoft.com>
---
 .../Ecma/EcmaType.TypeEquivalence.cs          | 42 ++++++++++++-------
 1 file changed, 28 insertions(+), 14 deletions(-)

diff --git a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.TypeEquivalence.cs b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.TypeEquivalence.cs
index 94d7722c28485f..b7fb3327a2655d 100644
--- a/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.TypeEquivalence.cs
+++ b/src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.TypeEquivalence.cs
@@ -14,6 +14,7 @@ public partial class EcmaType
         private TypeIdentifierData ComputeTypeIdentifierFromGuids()
         {
             CustomAttributeValue<TypeDesc>? guidAttribute;
+
             if (IsInterface && _typeDefinition.Attributes.HasFlag(TypeAttributes.Import))
             {
                 // ComImport interfaces get scope from their GUID
@@ -23,6 +24,7 @@ private TypeIdentifierData ComputeTypeIdentifierFromGuids()
             {
                 // other equivalent types get it from the declaring assembly
                 var attributeHandle = this.MetadataReader.GetCustomAttributeHandle(MetadataReader.GetAssemblyDefinition().GetCustomAttributes(), "System.Runtime.InteropServices", "GuidAttribute");
+
                 if (attributeHandle.IsNil)
                     return null;
 
@@ -40,6 +42,7 @@ private TypeIdentifierData ComputeTypeIdentifierFromGuids()
 
             string scope = (string)guidAttribute.Value.FixedArguments[0].Value;
             string name = this.Name;
+
             if (this.Namespace != null)
                 name = this.Namespace + "." + name;
 
@@ -53,6 +56,7 @@ private TypeIdentifierData ComputeTypeIdentifierData()
 
             // Check for type identifier attribute
             var typeIdentifierAttribute = this.GetDecodedCustomAttribute("System.Runtime.InteropServices", "TypeIdentifierAttribute");
+
             if (typeIdentifierAttribute.HasValue)
             {
                 // If the type has a type identifier attribute it is always considered to be type equivalent
@@ -68,28 +72,38 @@ private TypeIdentifierData ComputeTypeIdentifierData()
                 if (typeIdentifierAttribute.Value.FixedArguments[1].Type != Context.GetWellKnownType(WellKnownType.String))
                     return null;
 
-                _data = new TypeIdentifierData((string)typeIdentifierAttribute.Value.FixedArguments[0].Value, (string)typeIdentifierAttribute.Value.FixedArguments[1].Value);
-                return _data;
+                return new TypeIdentifierData((string)typeIdentifierAttribute.Value.FixedArguments[0].Value, (string)typeIdentifierAttribute.Value.FixedArguments[1].Value);
             }
-            else
+
+            // In addition to the TypeIdentifierAttribute certain other types may also be opted in to type equivalence
+            if (Context.SupportsCOMInterop)
             {
-                // In addition to the TypeIdentifierAttribute certain other types may also be opted in to type equivalence
-                if (Context.SupportsCOMInterop)
+                // 1. The assembly is marked with ImportedFromTypeLibAttribute or PrimaryInteropAssemblyAttribute
+                // We will verify this by checking for their attribute handles using the Metadata Reader.
+
+                CustomAttributeHandle importedFromTypeLibHdl = this.MetadataReader.GetCustomAttributeHandle(
+                    MetadataReader.GetAssemblyDefinition().GetCustomAttributes(),
+                    "System.Runtime.InteropServices",
+                    "ImportedFromTypeLibAttribute"
+                );
+
+                CustomAttributeHandle primaryInteropAssemblyHdl = this.MetadataReader.GetCustomAttributeHandle(
+                    MetadataReader.GetAssemblyDefinition().GetCustomAttributes(),
+                    "System.Runtime.InteropServices",
+                    "PrimaryInteropAssemblyAttribute"
+                );
+
+                if (!importedFromTypeLibHdl.IsNil || !primaryInteropAssemblyHdl.IsNil)
                 {
-                    // 1. Type is within assembly marked with ImportedFromTypeLibAttribute or PrimaryInteropAssemblyAttribute
-                    if (this.HasCustomAttribute("System.Runtime.InteropServices", "ImportedFromTypeLibAttribute") || this.HasCustomAttribute("System.Runtime.InteropServices", "PrimaryInteropAssemblyAttribute"))
-                    {
-                        // This type has a TypeIdentifier attribute if it has an appropriate shape to be considered type equivalent
-                    }
-
+                    // This type has a TypeIdentifier attribute if it has an appropriate shape to be considered type equivalent
                     if (!TypeHasCharacteristicsRequiredToBeTypeEquivalent)
                         return null;
 
-                    _data = ComputeTypeIdentifierFromGuids();
+                    return ComputeTypeIdentifierFromGuids();
                 }
-
-                return null;
             }
+
+            return null;
         }
 
         public override TypeIdentifierData TypeIdentifierData

From 900c83f437c36f3b3d5385f64f26744884d6b2a3 Mon Sep 17 00:00:00 2001
From: Steve Molloy <smolloy@microsoft.com>
Date: Thu, 22 Aug 2024 16:01:16 -0700
Subject: [PATCH 05/21] [release/8.0-staging] Sys.RT.Caching.MemoryCache -
 Remove unhandled exception handler (#106221)

* Remove UnhandledException handler from MemoryCache to avoid deadlock.

* Update Sys.RT.Caching csproj for servicing build.
---
 .../src/System.Runtime.Caching.csproj          |  2 ++
 .../src/System/Runtime/Caching/MemoryCache.cs  | 18 ------------------
 2 files changed, 2 insertions(+), 18 deletions(-)

diff --git a/src/libraries/System.Runtime.Caching/src/System.Runtime.Caching.csproj b/src/libraries/System.Runtime.Caching/src/System.Runtime.Caching.csproj
index b3d85127f02129..241cbbffb21367 100644
--- a/src/libraries/System.Runtime.Caching/src/System.Runtime.Caching.csproj
+++ b/src/libraries/System.Runtime.Caching/src/System.Runtime.Caching.csproj
@@ -3,6 +3,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0</TargetFrameworks>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <AddNETFrameworkPlaceholderFileToPackage>true</AddNETFrameworkPlaceholderFileToPackage>
     <AddXamarinPlaceholderFilesToPackage>true</AddXamarinPlaceholderFilesToPackage>
     <AddNETFrameworkAssemblyReferenceToPackage>true</AddNETFrameworkAssemblyReferenceToPackage>
diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs
index e740eed69ed514..38514ce521abca 100644
--- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs
+++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs
@@ -39,7 +39,6 @@ public class MemoryCache : ObjectCache, IEnumerable, IDisposable
         private bool _useMemoryCacheManager = true;
         private bool _throwOnDisposed;
         private EventHandler _onAppDomainUnload;
-        private UnhandledExceptionEventHandler _onUnhandledException;
 #if NETCOREAPP
         [UnsupportedOSPlatformGuard("browser")]
         private static bool _countersSupported => !OperatingSystem.IsBrowser();
@@ -219,9 +218,6 @@ private void InitDisposableMembers(NameValueCollection config)
                 EventHandler onAppDomainUnload = new EventHandler(OnAppDomainUnload);
                 appDomain.DomainUnload += onAppDomainUnload;
                 _onAppDomainUnload = onAppDomainUnload;
-                UnhandledExceptionEventHandler onUnhandledException = new UnhandledExceptionEventHandler(OnUnhandledException);
-                appDomain.UnhandledException += onUnhandledException;
-                _onUnhandledException = onUnhandledException;
                 dispose = false;
             }
             finally
@@ -238,16 +234,6 @@ private void OnAppDomainUnload(object unusedObject, EventArgs unusedEventArgs)
             Dispose();
         }
 
-        private void OnUnhandledException(object sender, UnhandledExceptionEventArgs eventArgs)
-        {
-            // if the CLR is terminating, dispose the cache.
-            // This will dispose the perf counters
-            if (eventArgs.IsTerminating)
-            {
-                Dispose();
-            }
-        }
-
         private static void ValidatePolicy(CacheItemPolicy policy)
         {
             if (policy.AbsoluteExpiration != ObjectCache.InfiniteAbsoluteExpiration
@@ -500,10 +486,6 @@ private void DisposeSafeCritical()
             {
                 appDomain.DomainUnload -= _onAppDomainUnload;
             }
-            if (_onUnhandledException != null)
-            {
-                appDomain.UnhandledException -= _onUnhandledException;
-            }
         }
 
         private object GetInternal(string key, string regionName)

From 5060359ef55b882309b53f66ce639fc71fc3b52a Mon Sep 17 00:00:00 2001
From: Rich Lander <rich@lander.ca>
Date: Fri, 23 Aug 2024 09:10:59 -0700
Subject: [PATCH 06/21] Switch 8.0 build images to Azure Linux 3.0 (#106170)

* Switch build x64 image to Azure Linux 3.0

* Add remaining (existing) images

* Remove accidental 9.0

* Fix BundleLegacy.TestNetCoreApp3xApp

Stop relying on ICU - this is irrelevant to what the test targets.

---------

Co-authored-by: Elinor Fung <elfung@microsoft.com>
---
 .../building/coreclr/linux-instructions.md         | 13 +++++++------
 .../common/templates/pipeline-with-resources.yml   | 14 +++++++-------
 .../StandaloneApp3x/StandaloneApp3x.csproj         |  1 +
 3 files changed, 15 insertions(+), 13 deletions(-)

diff --git a/docs/workflow/building/coreclr/linux-instructions.md b/docs/workflow/building/coreclr/linux-instructions.md
index 8e7457ff521850..fd76171aeaf2ce 100644
--- a/docs/workflow/building/coreclr/linux-instructions.md
+++ b/docs/workflow/building/coreclr/linux-instructions.md
@@ -60,12 +60,13 @@ All official builds are cross-builds with a rootfs for the target OS, and will u
 
 | Host OS               | Target OS    | Target Arch     | Image location                                                                   | crossrootfs location |
 | --------------------- | ------------ | --------------- | -------------------------------------------------------------------------------- | -------------------- |
-| CBL-mariner 2.0 (x64) | Alpine 3.13  | x64             | `mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-amd64-alpine` | `/crossrootfs/x64`   |
-| CBL-mariner 2.0 (x64) | Ubuntu 16.04 | x64             | `mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-amd64`        | `/crossrootfs/x64`   |
-| CBL-mariner 2.0 (x64) | Alpine       | arm32 (armhf)   | `mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-arm-alpine`   | `/crossrootfs/arm`   |
-| CBL-mariner 2.0 (x64) | Ubuntu 16.04 | arm32 (armhf)   | `mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-arm`          | `/crossrootfs/arm`   |
-| CBL-mariner 2.0 (x64) | Alpine       | arm64 (arm64v8) | `mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-arm64-alpine` | `/crossrootfs/arm64` |
-| CBL-mariner 2.0 (x64) | Ubuntu 16.04 | arm64 (arm64v8) | `mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-arm64`        | `/crossrootfs/arm64` |
+| Azure Linux (x64)     | Alpine 3.13  | x64             | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-amd64-alpine-net8.0` | `/crossrootfs/x64`   |
+| Azure Linux (x64)     | Ubuntu 16.04 | x64             | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-amd64-net8.0`        | `/crossrootfs/x64`   |
+| Azure Linux (x64)     | Alpine       | arm32 (armhf)   | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm-alpine-net8.0`   | `/crossrootfs/arm`   |
+| Azure Linux (x64)     | Ubuntu 16.04 | arm32 (armhf)   | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm-net8.0`          | `/crossrootfs/arm`   |
+| Azure Linux (x64)     | Alpine       | arm64 (arm64v8) | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm64-alpine-net8.0` | `/crossrootfs/arm64` |
+| Azure Linux (x64)     | Ubuntu 16.04 | arm64 (arm64v8) | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm64-net8.0`        | `/crossrootfs/arm64` |
+| Azure Linux (x64)     | Ubuntu 16.04 | x86             | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-x86-net8.0`          | `/crossrootfs/x86` |
 | Ubuntu 18.04 (x64)    | FreeBSD      | x64             | `mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-18.04-cross-freebsd-12`      | `/crossrootfs/x64`   |
 
 These Docker images are built using the Dockerfiles maintained in the [dotnet-buildtools-prereqs-docker repo](https://github.com/dotnet/dotnet-buildtools-prereqs-docker).
diff --git a/eng/pipelines/common/templates/pipeline-with-resources.yml b/eng/pipelines/common/templates/pipeline-with-resources.yml
index f5fd4abbd25bf8..70b09a8a3270aa 100644
--- a/eng/pipelines/common/templates/pipeline-with-resources.yml
+++ b/eng/pipelines/common/templates/pipeline-with-resources.yml
@@ -17,7 +17,7 @@ extends:
 
     containers:
       linux_arm:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-arm
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm-net8.0
         env:
           ROOTFS_DIR: /crossrootfs/arm
 
@@ -27,23 +27,23 @@ extends:
           ROOTFS_DIR: /crossrootfs/armv6
 
       linux_arm64:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-biarch-amd64-arm64
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm64-net8.0
         env:
           ROOTFS_HOST_DIR: /crossrootfs/x64
           ROOTFS_DIR: /crossrootfs/arm64
 
       linux_musl_x64:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-amd64-alpine
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-amd64-alpine-net8.0
         env:
           ROOTFS_DIR: /crossrootfs/x64
 
       linux_musl_arm:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-arm-alpine
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm-alpine-net8.0
         env:
           ROOTFS_DIR: /crossrootfs/arm
 
       linux_musl_arm64:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-arm64-alpine
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm64-alpine-net8.0
         env:
           ROOTFS_DIR: /crossrootfs/arm64
 
@@ -56,12 +56,12 @@ extends:
         image: mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-android-docker
 
       linux_x64:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-amd64
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-amd64-net8.0
         env:
           ROOTFS_DIR: /crossrootfs/x64
 
       linux_x86:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-x86
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-x86-net8.0
         env:
           ROOTFS_DIR: /crossrootfs/x86
 
diff --git a/src/installer/tests/Assets/TestProjects/StandaloneApp3x/StandaloneApp3x.csproj b/src/installer/tests/Assets/TestProjects/StandaloneApp3x/StandaloneApp3x.csproj
index 567d0a28562310..27766f45945299 100644
--- a/src/installer/tests/Assets/TestProjects/StandaloneApp3x/StandaloneApp3x.csproj
+++ b/src/installer/tests/Assets/TestProjects/StandaloneApp3x/StandaloneApp3x.csproj
@@ -5,6 +5,7 @@
     <OutputType>Exe</OutputType>
     <RuntimeIdentifier>$(TestTargetRid)</RuntimeIdentifier>
     <SelfContained>true</SelfContained>
+    <InvariantGlobalization>true</InvariantGlobalization>
   </PropertyGroup>
 
   <!--

From eda809d75af0bcf399a16d56bb7bb449a238fc41 Mon Sep 17 00:00:00 2001
From: Tarek Mahmoud Sayed <10833894+tarekgh@users.noreply.github.com>
Date: Sun, 25 Aug 2024 12:28:09 -0700
Subject: [PATCH 07/21] [release/8.0-staging] Fix logging formatting (#106367)

---
 .../src/LogValuesFormatter.cs                 | 28 ++++++---------
 ...oft.Extensions.Logging.Abstractions.csproj |  4 +--
 .../ConsoleLoggerTest.cs                      | 35 ++++++++++++++++---
 3 files changed, 43 insertions(+), 24 deletions(-)

diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs
index beae39c00287ad..4f9832950084c2 100644
--- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs
+++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LogValuesFormatter.cs
@@ -192,32 +192,26 @@ internal string Format()
 #if NET8_0_OR_GREATER
         internal string Format<TArg0>(TArg0 arg0)
         {
-            object? arg0String = null;
             return
-                !TryFormatArgumentIfNullOrEnumerable(arg0, ref arg0String) ?
+                !TryFormatArgumentIfNullOrEnumerable(arg0, out object? arg0String) ?
                 string.Format(CultureInfo.InvariantCulture, _format, arg0) :
                 string.Format(CultureInfo.InvariantCulture, _format, arg0String);
         }
 
         internal string Format<TArg0, TArg1>(TArg0 arg0, TArg1 arg1)
         {
-            object? arg0String = null, arg1String = null;
             return
-                !TryFormatArgumentIfNullOrEnumerable(arg0, ref arg0String) &&
-                !TryFormatArgumentIfNullOrEnumerable(arg1, ref arg1String) ?
-                string.Format(CultureInfo.InvariantCulture, _format, arg0, arg1) :
-                string.Format(CultureInfo.InvariantCulture, _format, arg0String ?? arg0, arg1String ?? arg1);
-        }
+                TryFormatArgumentIfNullOrEnumerable(arg0, out object? arg0String) | TryFormatArgumentIfNullOrEnumerable(arg1, out object? arg1String) ?
+                string.Format(CultureInfo.InvariantCulture, _format, arg0String ?? arg0, arg1String ?? arg1) :
+                string.Format(CultureInfo.InvariantCulture, _format, arg0, arg1);
+       }
 
         internal string Format<TArg0, TArg1, TArg2>(TArg0 arg0, TArg1 arg1, TArg2 arg2)
         {
-            object? arg0String = null, arg1String = null, arg2String = null;
             return
-                !TryFormatArgumentIfNullOrEnumerable(arg0, ref arg0String) &&
-                !TryFormatArgumentIfNullOrEnumerable(arg1, ref arg1String) &&
-                !TryFormatArgumentIfNullOrEnumerable(arg2, ref arg2String) ?
-                string.Format(CultureInfo.InvariantCulture, _format, arg0, arg1, arg2) :
-                string.Format(CultureInfo.InvariantCulture, _format, arg0String ?? arg0, arg1String ?? arg1, arg2String ?? arg2);
+                TryFormatArgumentIfNullOrEnumerable(arg0, out object? arg0String) | TryFormatArgumentIfNullOrEnumerable(arg1, out object? arg1String) | TryFormatArgumentIfNullOrEnumerable(arg2, out object? arg2String) ?
+                string.Format(CultureInfo.InvariantCulture, _format, arg0String ?? arg0, arg1String ?? arg1, arg2String ?? arg2):
+                string.Format(CultureInfo.InvariantCulture, _format, arg0, arg1, arg2);
         }
 #else
         internal string Format(object? arg0) =>
@@ -259,11 +253,10 @@ internal string Format(object? arg0, object? arg1, object? arg2) =>
 
         private static object FormatArgument(object? value)
         {
-            object? stringValue = null;
-            return TryFormatArgumentIfNullOrEnumerable(value, ref stringValue) ? stringValue : value!;
+            return TryFormatArgumentIfNullOrEnumerable(value, out object? stringValue) ? stringValue : value!;
         }
 
-        private static bool TryFormatArgumentIfNullOrEnumerable<T>(T? value, [NotNullWhen(true)] ref object? stringValue)
+        private static bool TryFormatArgumentIfNullOrEnumerable<T>(T? value, [NotNullWhen(true)] out object? stringValue)
         {
             if (value == null)
             {
@@ -290,6 +283,7 @@ private static bool TryFormatArgumentIfNullOrEnumerable<T>(T? value, [NotNullWhe
                 return true;
             }
 
+            stringValue = null;
             return false;
         }
     }
diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj
index cfb15ea788e9e5..12c30e271e7738 100644
--- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj
+++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj
@@ -5,8 +5,8 @@
     <EnableDefaultItems>true</EnableDefaultItems>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <IsPackable>true</IsPackable>
-    <GeneratePackageOnBuild>false</GeneratePackageOnBuild>
-    <ServicingVersion>1</ServicingVersion>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>2</ServicingVersion>
     <PackageDescription>Logging abstractions for Microsoft.Extensions.Logging.
 
 Commonly Used Types:
diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerTest.cs b/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerTest.cs
index 0994980590122b..ab8c88f4ba3c45 100644
--- a/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerTest.cs
+++ b/src/libraries/Microsoft.Extensions.Logging.Console/tests/Microsoft.Extensions.Logging.Console.Tests/ConsoleLoggerTest.cs
@@ -32,7 +32,7 @@ internal static IEnumerable<ConsoleFormatter> GetFormatters(
             var defaultMonitor = new TestFormatterOptionsMonitor<SimpleConsoleFormatterOptions>(simpleOptions ?? new SimpleConsoleFormatterOptions());
             var systemdMonitor = new TestFormatterOptionsMonitor<ConsoleFormatterOptions>(systemdOptions ?? new ConsoleFormatterOptions());
             var jsonMonitor = new TestFormatterOptionsMonitor<JsonConsoleFormatterOptions>(jsonOptions ?? new JsonConsoleFormatterOptions());
-            var formatters = new List<ConsoleFormatter>() { 
+            var formatters = new List<ConsoleFormatter>() {
                 new SimpleConsoleFormatter(defaultMonitor),
                 new SystemdConsoleFormatter(systemdMonitor),
                 new JsonConsoleFormatter(jsonMonitor)
@@ -86,13 +86,13 @@ private static void VerifyDeprecatedPropertiesUsedOnNullFormatterName(ConsoleLog
                 Assert.Equal(formatter.FormatterOptions.IncludeScopes, logger.Options.IncludeScopes);
                 Assert.Equal(formatter.FormatterOptions.UseUtcTimestamp, logger.Options.UseUtcTimestamp);
                 Assert.Equal(formatter.FormatterOptions.TimestampFormat, logger.Options.TimestampFormat);
-                Assert.Equal(formatter.FormatterOptions.ColorBehavior, 
-                    logger.Options.DisableColors ? LoggerColorBehavior.Disabled : LoggerColorBehavior.Enabled);   
+                Assert.Equal(formatter.FormatterOptions.ColorBehavior,
+                    logger.Options.DisableColors ? LoggerColorBehavior.Disabled : LoggerColorBehavior.Enabled);
             }
             else
             {
                 var formatter = Assert.IsType<SystemdConsoleFormatter>(logger.Formatter);
-                Assert.Equal(formatter.FormatterOptions.IncludeScopes, logger.Options.IncludeScopes);   
+                Assert.Equal(formatter.FormatterOptions.IncludeScopes, logger.Options.IncludeScopes);
                 Assert.Equal(formatter.FormatterOptions.UseUtcTimestamp, logger.Options.UseUtcTimestamp);
                 Assert.Equal(formatter.FormatterOptions.TimestampFormat, logger.Options.TimestampFormat);
             }
@@ -103,7 +103,7 @@ private static void UpdateFormatterOptions(ConsoleFormatter formatter, ConsoleLo
             // kept for deprecated apis:
             if (formatter is SimpleConsoleFormatter defaultFormatter)
             {
-                defaultFormatter.FormatterOptions.ColorBehavior = deprecatedFromOptions.DisableColors ? 
+                defaultFormatter.FormatterOptions.ColorBehavior = deprecatedFromOptions.DisableColors ?
                     LoggerColorBehavior.Disabled : LoggerColorBehavior.Enabled;
                 defaultFormatter.FormatterOptions.IncludeScopes = deprecatedFromOptions.IncludeScopes;
                 defaultFormatter.FormatterOptions.TimestampFormat = deprecatedFromOptions.TimestampFormat;
@@ -1346,6 +1346,31 @@ public void ConsoleLoggerOptions_IncludeScopes_IsReadFromLoggingConfiguration()
             Assert.True(formatter.FormatterOptions.IncludeScopes);
         }
 
+        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
+        public void LogMultipleArrays()
+        {
+            // Arrange
+            var t = SetUp();
+            var logger = t.Logger;
+            var sink = t.Sink;
+
+            var define1 = LoggerMessage.Define<string[], string[]>(LogLevel.Information, new EventId(), "Log: {Array1} and {Array2}");
+            var define2 = LoggerMessage.Define<int, string[], string[]>(LogLevel.Information, new EventId(), "Log {Number}: {Array1} and {Array2}");
+
+            // Act
+            define1(logger, ["a", "b", "c"], ["d", "e", "f"], null);
+            define2(logger, 30, ["a", "b", "c"], ["d", "e", "f"], null);
+
+            var expectedMessage1 = $"{CreateHeader(ConsoleLoggerFormat.Default)}{Environment.NewLine}{_paddingString}Log: a, b, c and d, e, f{Environment.NewLine}";
+            var expectedMessage2 = $"{CreateHeader(ConsoleLoggerFormat.Default)}{Environment.NewLine}{_paddingString}Log 30: a, b, c and d, e, f{Environment.NewLine}";
+
+            Assert.Equal(4, sink.Writes.Count);
+            Assert.Equal("info", sink.Writes[0].Message);
+            Assert.Equal(expectedMessage1, sink.Writes[1].Message);
+            Assert.Equal("info", sink.Writes[2].Message);
+            Assert.Equal(expectedMessage2, sink.Writes[3].Message);
+        }
+
         public static TheoryData<ConsoleLoggerFormat, LogLevel> FormatsAndLevels
         {
             get

From e6181728ccd7d74f5b23cc0cd1cdc23132845ffa Mon Sep 17 00:00:00 2001
From: Sven Boemer <sbomer@gmail.com>
Date: Tue, 27 Aug 2024 12:06:43 -0700
Subject: [PATCH 08/21] Update Azure Linux tag names (#106884)

---
 .../building/coreclr/linux-instructions.md         | 14 +++++++-------
 .../common/templates/pipeline-with-resources.yml   | 14 +++++++-------
 2 files changed, 14 insertions(+), 14 deletions(-)

diff --git a/docs/workflow/building/coreclr/linux-instructions.md b/docs/workflow/building/coreclr/linux-instructions.md
index fd76171aeaf2ce..0d28067fe7843c 100644
--- a/docs/workflow/building/coreclr/linux-instructions.md
+++ b/docs/workflow/building/coreclr/linux-instructions.md
@@ -60,13 +60,13 @@ All official builds are cross-builds with a rootfs for the target OS, and will u
 
 | Host OS               | Target OS    | Target Arch     | Image location                                                                   | crossrootfs location |
 | --------------------- | ------------ | --------------- | -------------------------------------------------------------------------------- | -------------------- |
-| Azure Linux (x64)     | Alpine 3.13  | x64             | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-amd64-alpine-net8.0` | `/crossrootfs/x64`   |
-| Azure Linux (x64)     | Ubuntu 16.04 | x64             | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-amd64-net8.0`        | `/crossrootfs/x64`   |
-| Azure Linux (x64)     | Alpine       | arm32 (armhf)   | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm-alpine-net8.0`   | `/crossrootfs/arm`   |
-| Azure Linux (x64)     | Ubuntu 16.04 | arm32 (armhf)   | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm-net8.0`          | `/crossrootfs/arm`   |
-| Azure Linux (x64)     | Alpine       | arm64 (arm64v8) | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm64-alpine-net8.0` | `/crossrootfs/arm64` |
-| Azure Linux (x64)     | Ubuntu 16.04 | arm64 (arm64v8) | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm64-net8.0`        | `/crossrootfs/arm64` |
-| Azure Linux (x64)     | Ubuntu 16.04 | x86             | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-x86-net8.0`          | `/crossrootfs/x86` |
+| Azure Linux (x64)     | Alpine 3.13  | x64             | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-amd64-alpine` | `/crossrootfs/x64`   |
+| Azure Linux (x64)     | Ubuntu 16.04 | x64             | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-amd64`        | `/crossrootfs/x64`   |
+| Azure Linux (x64)     | Alpine       | arm32 (armhf)   | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-arm-alpine`   | `/crossrootfs/arm`   |
+| Azure Linux (x64)     | Ubuntu 16.04 | arm32 (armhf)   | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-arm`          | `/crossrootfs/arm`   |
+| Azure Linux (x64)     | Alpine       | arm64 (arm64v8) | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-arm64-alpine` | `/crossrootfs/arm64` |
+| Azure Linux (x64)     | Ubuntu 16.04 | arm64 (arm64v8) | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-arm64`        | `/crossrootfs/arm64` |
+| Azure Linux (x64)     | Ubuntu 16.04 | x86             | `mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-x86`          | `/crossrootfs/x86` |
 | Ubuntu 18.04 (x64)    | FreeBSD      | x64             | `mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-18.04-cross-freebsd-12`      | `/crossrootfs/x64`   |
 
 These Docker images are built using the Dockerfiles maintained in the [dotnet-buildtools-prereqs-docker repo](https://github.com/dotnet/dotnet-buildtools-prereqs-docker).
diff --git a/eng/pipelines/common/templates/pipeline-with-resources.yml b/eng/pipelines/common/templates/pipeline-with-resources.yml
index 70b09a8a3270aa..70252b24e4ca96 100644
--- a/eng/pipelines/common/templates/pipeline-with-resources.yml
+++ b/eng/pipelines/common/templates/pipeline-with-resources.yml
@@ -17,7 +17,7 @@ extends:
 
     containers:
       linux_arm:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm-net8.0
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-arm
         env:
           ROOTFS_DIR: /crossrootfs/arm
 
@@ -27,23 +27,23 @@ extends:
           ROOTFS_DIR: /crossrootfs/armv6
 
       linux_arm64:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm64-net8.0
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-arm64
         env:
           ROOTFS_HOST_DIR: /crossrootfs/x64
           ROOTFS_DIR: /crossrootfs/arm64
 
       linux_musl_x64:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-amd64-alpine-net8.0
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-amd64-alpine
         env:
           ROOTFS_DIR: /crossrootfs/x64
 
       linux_musl_arm:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm-alpine-net8.0
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-arm-alpine
         env:
           ROOTFS_DIR: /crossrootfs/arm
 
       linux_musl_arm64:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-arm64-alpine-net8.0
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-arm64-alpine
         env:
           ROOTFS_DIR: /crossrootfs/arm64
 
@@ -56,12 +56,12 @@ extends:
         image: mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-android-docker
 
       linux_x64:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-amd64-net8.0
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-amd64
         env:
           ROOTFS_DIR: /crossrootfs/x64
 
       linux_x86:
-        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-cross-x86-net8.0
+        image: mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net8.0-cross-x86
         env:
           ROOTFS_DIR: /crossrootfs/x86
 

From c458057069f0779d77d80bf4990c8221c512335a Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
 <41898282+github-actions[bot]@users.noreply.github.com>
Date: Wed, 4 Sep 2024 09:19:02 -0700
Subject: [PATCH 09/21] [release/8.0-staging] Do not allow a non-keyed service
 to be injected to a keyed parameter (#106877)

* Do not allow a non-keyed service to be injected into a keyed parameter

* Fix test issue on NetFx

* Add feature switch for compat: Microsoft.Extensions.DependencyInjection.AllowNonKeyedServiceInject

* Enable servicing Microsoft.Extensions.DependencyInjection

---------

Co-authored-by: Steve Harter <steveharter@users.noreply.github.com>
Co-authored-by: Eric StJohn <ericstj@microsoft.com>
---
 ...edDependencyInjectionSpecificationTests.cs | 102 +++++++++++++++++-
 .../src/ILLink/ILLink.Substitutions.xml       |   3 +
 ...soft.Extensions.DependencyInjection.csproj |   2 +
 .../src/ServiceLookup/CallSiteFactory.cs      |   7 +-
 .../src/ServiceProvider.cs                    |   5 +
 .../DI.Tests/ServiceProviderContainerTests.cs |  46 ++++++++
 6 files changed, 160 insertions(+), 5 deletions(-)

diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Specification.Tests/src/KeyedDependencyInjectionSpecificationTests.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Specification.Tests/src/KeyedDependencyInjectionSpecificationTests.cs
index a0dc73d58f820b..d3e1ee13184164 100644
--- a/src/libraries/Microsoft.Extensions.DependencyInjection.Specification.Tests/src/KeyedDependencyInjectionSpecificationTests.cs
+++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Specification.Tests/src/KeyedDependencyInjectionSpecificationTests.cs
@@ -11,7 +11,7 @@ namespace Microsoft.Extensions.DependencyInjection.Specification
 {
     public abstract partial class KeyedDependencyInjectionSpecificationTests
     {
-        protected abstract  IServiceProvider CreateServiceProvider(IServiceCollection collection);
+        protected abstract IServiceProvider CreateServiceProvider(IServiceCollection collection);
 
         [Fact]
         public void ResolveKeyedService()
@@ -205,6 +205,70 @@ public void ResolveKeyedServiceSingletonInstanceWithKeyedParameter()
             Assert.Equal("service2", svc.Service2.ToString());
         }
 
+        [Fact]
+        public void ResolveKeyedServiceWithKeyedParameter_MissingRegistration_SecondParameter()
+        {
+            var serviceCollection = new ServiceCollection();
+
+            serviceCollection.AddKeyedSingleton<IService, Service>("service1");
+            // We are missing the registration for "service2" here and OtherService requires it.
+
+            serviceCollection.AddSingleton<OtherService>();
+
+            var provider = CreateServiceProvider(serviceCollection);
+
+            Assert.Null(provider.GetService<IService>());
+            Assert.Throws<InvalidOperationException>(() => provider.GetService<OtherService>());
+        }
+
+        [Fact]
+        public void ResolveKeyedServiceWithKeyedParameter_MissingRegistration_FirstParameter()
+        {
+            var serviceCollection = new ServiceCollection();
+
+            // We are not registering "service1" and "service1" keyed IService services and OtherService requires them.
+
+            serviceCollection.AddSingleton<OtherService>();
+
+            var provider = CreateServiceProvider(serviceCollection);
+
+            Assert.Null(provider.GetService<IService>());
+            Assert.Throws<InvalidOperationException>(() => provider.GetService<OtherService>());
+        }
+
+        [Fact]
+        public void ResolveKeyedServiceWithKeyedParameter_MissingRegistrationButWithDefaults()
+        {
+            var serviceCollection = new ServiceCollection();
+
+            // We are not registering "service1" and "service1" keyed IService services and OtherServiceWithDefaultCtorArgs
+            // specifies them but has argument defaults if missing.
+
+            serviceCollection.AddSingleton<OtherServiceWithDefaultCtorArgs>();
+
+            var provider = CreateServiceProvider(serviceCollection);
+
+            Assert.Null(provider.GetService<IService>());
+            Assert.NotNull(provider.GetService<OtherServiceWithDefaultCtorArgs>());
+        }
+
+        [Fact]
+        public void ResolveKeyedServiceWithKeyedParameter_MissingRegistrationButWithUnkeyedService()
+        {
+            var serviceCollection = new ServiceCollection();
+
+            // We are not registering "service1" and "service1" keyed IService services and OtherService requires them,
+            // but we are registering an unkeyed IService service which should not be injected into OtherService.
+            serviceCollection.AddSingleton<IService, Service>();
+
+            serviceCollection.AddSingleton<OtherService>();
+
+            var provider = CreateServiceProvider(serviceCollection);
+
+            Assert.NotNull(provider.GetService<IService>());
+            Assert.Throws<InvalidOperationException>(() => provider.GetService<OtherService>());
+        }
+
         [Fact]
         public void CreateServiceWithKeyedParameter()
         {
@@ -432,9 +496,9 @@ public void ResolveKeyedTransientFromScopeServiceProvider()
             Assert.NotSame(serviceA1, serviceB1);
         }
 
-        internal interface IService { }
+        public interface IService { }
 
-        internal class Service : IService
+        public class Service : IService
         {
             private readonly string _id;
 
@@ -445,7 +509,7 @@ internal class Service : IService
             public override string? ToString() => _id;
         }
 
-        internal class OtherService
+        public class OtherService
         {
             public OtherService(
                 [FromKeyedServices("service1")] IService service1,
@@ -460,6 +524,36 @@ public OtherService(
             public IService Service2 { get; }
         }
 
+        internal class OtherServiceWithDefaultCtorArgs
+        {
+            public OtherServiceWithDefaultCtorArgs(
+                [FromKeyedServices("service1")] IService service1 = null,
+                [FromKeyedServices("service2")] IService service2 = null)
+            {
+                Service1 = service1;
+                Service2 = service2;
+            }
+
+            public IService Service1 { get; }
+
+            public IService Service2 { get; }
+        }
+
+        internal class ServiceWithOtherService
+        {
+            public ServiceWithOtherService(
+                [FromKeyedServices("service1")] IService service1,
+                [FromKeyedServices("service2")] IService service2)
+            {
+                Service1 = service1;
+                Service2 = service2;
+            }
+
+            public IService Service1 { get; }
+
+            public IService Service2 { get; }
+        }
+
         internal class ServiceWithIntKey : IService
         {
             private readonly int _id;
diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ILLink/ILLink.Substitutions.xml b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ILLink/ILLink.Substitutions.xml
index 6aa354ee23683c..e74fb0fb6ac7c6 100644
--- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ILLink/ILLink.Substitutions.xml
+++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ILLink/ILLink.Substitutions.xml
@@ -6,5 +6,8 @@
     <type fullname="Microsoft.Extensions.DependencyInjection.ServiceProvider">
       <method signature="System.Boolean get_DisableDynamicEngine()" body="stub" value="true" feature="Microsoft.Extensions.DependencyInjection.DisableDynamicEngine" featurevalue="true" />
     </type>
+    <type fullname="Microsoft.Extensions.DependencyInjection.ServiceProvider">
+      <method signature="System.Boolean get_AllowNonKeyedServiceInject()" body="stub" value="false" feature="Microsoft.Extensions.DependencyInjection.AllowNonKeyedServiceInject" featurevalue="false" />
+    </type>
   </assembly>
 </linker>
diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/Microsoft.Extensions.DependencyInjection.csproj b/src/libraries/Microsoft.Extensions.DependencyInjection/src/Microsoft.Extensions.DependencyInjection.csproj
index ce7ac08140311d..cc0bebcb2c129b 100644
--- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/Microsoft.Extensions.DependencyInjection.csproj
+++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/Microsoft.Extensions.DependencyInjection.csproj
@@ -7,6 +7,8 @@
     <!-- Type 'Microsoft.Extensions.DependencyInjection.ServiceCollection' has been forwarded down.-->
     <NoWarn>$(NoWarn);CP0001</NoWarn>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Default implementation of dependency injection for Microsoft.Extensions.DependencyInjection.</PackageDescription>
   </PropertyGroup>
 
diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs
index 29f229c17fff8d..5505b3e2a6d1bb 100644
--- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs
+++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs
@@ -571,6 +571,7 @@ private ConstructorCallSite CreateConstructorCallSite(
             for (int index = 0; index < parameters.Length; index++)
             {
                 ServiceCallSite? callSite = null;
+                bool isKeyedParameter = false;
                 Type parameterType = parameters[index].ParameterType;
                 foreach (var attribute in parameters[index].GetCustomAttributes(true))
                 {
@@ -588,11 +589,15 @@ private ConstructorCallSite CreateConstructorCallSite(
                     {
                         var parameterSvcId = new ServiceIdentifier(keyed.Key, parameterType);
                         callSite = GetCallSite(parameterSvcId, callSiteChain);
+                        isKeyedParameter = true;
                         break;
                     }
                 }
 
-                callSite ??= GetCallSite(ServiceIdentifier.FromServiceType(parameterType), callSiteChain);
+                if (!isKeyedParameter || ServiceProvider.s_allowNonKeyedServiceInject)
+                {
+                    callSite ??= GetCallSite(ServiceIdentifier.FromServiceType(parameterType), callSiteChain);
+                }
 
                 if (callSite == null && ParameterDefaultValue.TryGetDefaultValue(parameters[index], out object? defaultValue))
                 {
diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProvider.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProvider.cs
index ff5efbe98cf334..2eadf6e15a420d 100644
--- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProvider.cs
+++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceProvider.cs
@@ -40,6 +40,11 @@ public sealed class ServiceProvider : IServiceProvider, IKeyedServiceProvider, I
         internal static bool DisableDynamicEngine { get; } =
             AppContext.TryGetSwitch("Microsoft.Extensions.DependencyInjection.DisableDynamicEngine", out bool disableDynamicEngine) ? disableDynamicEngine : false;
 
+        internal static bool AllowNonKeyedServiceInject { get; } =
+            AppContext.TryGetSwitch("Microsoft.Extensions.DependencyInjection.AllowNonKeyedServiceInject", out bool allowNonKeyedServiceInject) ? allowNonKeyedServiceInject : false;
+
+        internal static readonly bool s_allowNonKeyedServiceInject = AllowNonKeyedServiceInject;
+
         internal static bool VerifyAotCompatibility =>
 #if NETFRAMEWORK || NETSTANDARD2_0
             false;
diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ServiceProviderContainerTests.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ServiceProviderContainerTests.cs
index 3e08a16db282e6..4c88d874e7b726 100644
--- a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ServiceProviderContainerTests.cs
+++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ServiceProviderContainerTests.cs
@@ -7,6 +7,7 @@
 using System.Text;
 using System.Threading;
 using System.Threading.Tasks;
+using Microsoft.DotNet.RemoteExecutor;
 using Microsoft.Extensions.DependencyInjection.Extensions;
 using Microsoft.Extensions.DependencyInjection.Fakes;
 using Microsoft.Extensions.DependencyInjection.Specification;
@@ -1290,6 +1291,51 @@ public void ScopedServiceResolvedFromSingletonAfterCompilation3()
             Assert.Same(sp.GetRequiredService<IFakeOpenGenericService<Aa>>().Value.PropertyA, sp.GetRequiredService<A>());
         }
 
+        [Fact]
+        public void ResolveKeyedServiceWithKeyedParameter_MissingRegistrationButWithUnkeyedService()
+        {
+            var serviceCollection = new ServiceCollection();
+
+            // We are not registering "service1" and "service1" keyed IService services and OtherService requires them,
+            // but we are registering an unkeyed IService service which should not be injected into OtherService.
+            serviceCollection.AddSingleton<KeyedDependencyInjectionSpecificationTests.IService, KeyedDependencyInjectionSpecificationTests.Service>();
+
+            serviceCollection.AddSingleton<KeyedDependencyInjectionSpecificationTests.OtherService>();
+
+            AggregateException ex = Assert.Throws<AggregateException>(() => serviceCollection.BuildServiceProvider(new ServiceProviderOptions
+            {
+                ValidateOnBuild = true
+            }));
+
+            Assert.Equal(1, ex.InnerExceptions.Count);
+            Assert.StartsWith("Some services are not able to be constructed", ex.Message);
+            Assert.Contains("ServiceType: Microsoft.Extensions.DependencyInjection.Specification.KeyedDependencyInjectionSpecificationTests+OtherService", ex.ToString());
+            Assert.Contains("Microsoft.Extensions.DependencyInjection.Specification.KeyedDependencyInjectionSpecificationTests+IService", ex.ToString());
+        }
+
+        [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
+        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // RuntimeConfigurationOptions are not supported on .NET Framework (and neither is trimming)
+        public void ResolveKeyedServiceWithKeyedParameter_MissingRegistrationButWithUnkeyedService_FeatureSwitch()
+        {
+            RemoteInvokeOptions options = new ();
+            options.RuntimeConfigurationOptions["Microsoft.Extensions.DependencyInjection.AllowNonKeyedServiceInject"] = bool.TrueString;
+
+            using RemoteInvokeHandle remoteHandle = RemoteExecutor.Invoke(static () =>
+            {
+                Assert.True(ServiceProvider.s_allowNonKeyedServiceInject);
+
+                var serviceCollection = new ServiceCollection();
+
+                // Similar to the test above, but we are enabling the feature switch so we don't throw here.
+                serviceCollection.AddSingleton<KeyedDependencyInjectionSpecificationTests.IService, KeyedDependencyInjectionSpecificationTests.Service>();
+                serviceCollection.AddSingleton<KeyedDependencyInjectionSpecificationTests.OtherService>();
+                serviceCollection.BuildServiceProvider(new ServiceProviderOptions
+                {
+                    ValidateOnBuild = true
+                });
+            }, options);
+        }
+
         private async Task<bool> ResolveUniqueServicesConcurrently()
         {
             var types = new Type[]

From 351060ead76e30a1aeef9aa98cc071b62281ad99 Mon Sep 17 00:00:00 2001
From: Steve Harter <steveharter@users.noreply.github.com>
Date: Wed, 4 Sep 2024 11:19:43 -0500
Subject: [PATCH 10/21] [release/8.0-staging] Return null instead of throwing
 in ServiceDescriptor.ImplementationInstance\Type\Factory if a keyed service
 (#106841)

* Return null instead of throwing in ServiceDescriptor.ImplementationInstance\Type\Factory if a keyed service

* Enable servicing Microsoft.Extensions.DependencyInjection.Abstractions

---------

Co-authored-by: Eric StJohn <ericstj@microsoft.com>
---
 ...ns.DependencyInjection.Abstractions.csproj |  4 +-
 .../src/Resources/Strings.resx                |  5 +-
 .../src/ServiceDescriptor.cs                  | 74 +++++++++----------
 ...iceCollectionKeyedServiceExtensionsTest.cs |  6 +-
 4 files changed, 39 insertions(+), 50 deletions(-)

diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj
index 46105d1f642823..478f525ba85dd5 100644
--- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj
+++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Microsoft.Extensions.DependencyInjection.Abstractions.csproj
@@ -4,8 +4,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.1;netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
-    <GeneratePackageOnBuild>false</GeneratePackageOnBuild>
-    <ServicingVersion>1</ServicingVersion>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>2</ServicingVersion>
     <PackageDescription>Abstractions for dependency injection.
 
 Commonly Used Types:
diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Resources/Strings.resx b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Resources/Strings.resx
index d9eb294211515b..0cdd3bff63ed00 100644
--- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Resources/Strings.resx
+++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/Resources/Strings.resx
@@ -170,10 +170,7 @@
   <data name="KeyedServicesNotSupported" xml:space="preserve">
     <value>This service provider doesn't support keyed services.</value>
   </data>
-  <data name="KeyedDescriptorMisuse" xml:space="preserve">
-    <value>This service descriptor is keyed. Your service provider may not support keyed services.</value>
-  </data>
   <data name="NonKeyedDescriptorMisuse" xml:space="preserve">
     <value>This service descriptor is not keyed.</value>
   </data>
-</root>
\ No newline at end of file
+</root>
diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs
index 9790066b4bc8a3..cd23910b92c3f1 100644
--- a/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs
+++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ServiceDescriptor.cs
@@ -152,24 +152,22 @@ private ServiceDescriptor(Type serviceType, object? serviceKey, ServiceLifetime
         private Type? _implementationType;
 
         /// <summary>
-        /// Gets the <see cref="Type"/> that implements the service.
+        /// Gets the <see cref="Type"/> that implements the service,
+        /// or returns <see langword="null"/> if <see cref="IsKeyedService"/> is <see langword="true"/>.
         /// </summary>
+        /// <remarks>
+        /// If <see cref="IsKeyedService"/> is <see langword="true"/>, <see cref="KeyedImplementationType"/> should be called instead.
+        /// </remarks>
         [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
-        public Type? ImplementationType
-        {
-            get
-            {
-                if (IsKeyedService)
-                {
-                    ThrowKeyedDescriptor();
-                }
-                return _implementationType;
-            }
-        }
+        public Type? ImplementationType => IsKeyedService ? null : _implementationType;
 
         /// <summary>
-        /// Gets the <see cref="Type"/> that implements the service.
+        /// Gets the <see cref="Type"/> that implements the service,
+        /// or throws <see cref="InvalidOperationException"/> if <see cref="IsKeyedService"/> is <see langword="false"/>.
         /// </summary>
+        /// <remarks>
+        /// If <see cref="IsKeyedService"/> is <see langword="false"/>, <see cref="ImplementationType"/> should be called instead.
+        /// </remarks>
         [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
         public Type? KeyedImplementationType
         {
@@ -186,23 +184,21 @@ public Type? KeyedImplementationType
         private object? _implementationInstance;
 
         /// <summary>
-        /// Gets the instance that implements the service.
+        /// Gets the instance that implements the service,
+        /// or returns <see langword="null"/> if <see cref="IsKeyedService"/> is <see langword="true"/>.
         /// </summary>
-        public object? ImplementationInstance
-        {
-            get
-            {
-                if (IsKeyedService)
-                {
-                    ThrowKeyedDescriptor();
-                }
-                return _implementationInstance;
-            }
-        }
+        /// <remarks>
+        /// If <see cref="IsKeyedService"/> is <see langword="true"/>, <see cref="KeyedImplementationInstance"/> should be called instead.
+        /// </remarks>
+        public object? ImplementationInstance =>  IsKeyedService ? null : _implementationInstance;
 
         /// <summary>
-        /// Gets the instance that implements the service.
+        /// Gets the instance that implements the service,
+        /// or throws <see cref="InvalidOperationException"/> if <see cref="IsKeyedService"/> is <see langword="false"/>.
         /// </summary>
+        /// <remarks>
+        /// If <see cref="IsKeyedService"/> is <see langword="false"/>, <see cref="ImplementationInstance"/> should be called instead.
+        /// </remarks>
         public object? KeyedImplementationInstance
         {
             get
@@ -218,23 +214,21 @@ public object? KeyedImplementationInstance
         private object? _implementationFactory;
 
         /// <summary>
-        /// Gets the factory used for creating service instances.
+        /// Gets the factory used for creating service instance,
+        /// or returns <see langword="null"/> if <see cref="IsKeyedService"/> is <see langword="true"/>.
         /// </summary>
-        public Func<IServiceProvider, object>? ImplementationFactory
-        {
-            get
-            {
-                if (IsKeyedService)
-                {
-                    ThrowKeyedDescriptor();
-                }
-                return (Func<IServiceProvider, object>?) _implementationFactory;
-            }
-        }
+        /// <remarks>
+        /// If <see cref="IsKeyedService"/> is <see langword="true"/>, <see cref="KeyedImplementationFactory"/> should be called instead.
+        /// </remarks>
+        public Func<IServiceProvider, object>? ImplementationFactory => IsKeyedService ? null : (Func<IServiceProvider, object>?) _implementationFactory;
 
         /// <summary>
-        /// Gets the factory used for creating Keyed service instances.
+        /// Gets the factory used for creating Keyed service instances,
+        /// or throws <see cref="InvalidOperationException"/> if <see cref="IsKeyedService"/> is <see langword="false"/>.
         /// </summary>
+        /// <remarks>
+        /// If <see cref="IsKeyedService"/> is <see langword="false"/>, <see cref="ImplementationFactory"/> should be called instead.
+        /// </remarks>
         public Func<IServiceProvider, object?, object>? KeyedImplementationFactory
         {
             get
@@ -1058,8 +1052,6 @@ private string DebuggerToString()
             return debugText;
         }
 
-        private static void ThrowKeyedDescriptor() => throw new InvalidOperationException(SR.KeyedDescriptorMisuse);
-
         private static void ThrowNonKeyedDescriptor() => throw new InvalidOperationException(SR.NonKeyedDescriptorMisuse);
     }
 }
diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ServiceCollectionKeyedServiceExtensionsTest.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ServiceCollectionKeyedServiceExtensionsTest.cs
index 6be7e22cce2c35..e662cd9b337c4e 100644
--- a/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ServiceCollectionKeyedServiceExtensionsTest.cs
+++ b/src/libraries/Microsoft.Extensions.DependencyInjection/tests/DI.Tests/ServiceCollectionKeyedServiceExtensionsTest.cs
@@ -579,9 +579,9 @@ public static TheoryData NotNullServiceKeyData
         public void NotNullServiceKey_IsKeyedServiceTrue(ServiceDescriptor serviceDescriptor)
         {
             Assert.True(serviceDescriptor.IsKeyedService);
-            Assert.Throws<InvalidOperationException>(() => serviceDescriptor.ImplementationInstance);
-            Assert.Throws<InvalidOperationException>(() => serviceDescriptor.ImplementationType);
-            Assert.Throws<InvalidOperationException>(() => serviceDescriptor.ImplementationFactory);
+            Assert.Null(serviceDescriptor.ImplementationInstance);
+            Assert.Null(serviceDescriptor.ImplementationType);
+            Assert.Null(serviceDescriptor.ImplementationFactory);
         }
     }
 }

From 1f47f6d67c4086080bd1664da0529afa83004784 Mon Sep 17 00:00:00 2001
From: "dotnet-maestro[bot]"
 <42748379+dotnet-maestro[bot]@users.noreply.github.com>
Date: Wed, 4 Sep 2024 15:45:48 -0600
Subject: [PATCH 11/21] Update dependencies from
 https://github.com/dotnet/hotreload-utils build 20240903.2 (#107297)

Microsoft.DotNet.HotReload.Utils.Generator.BuildTool
 From Version 8.0.0-alpha.0.24402.1 -> To Version 8.0.0-alpha.0.24453.2

Co-authored-by: dotnet-maestro[bot] <dotnet-maestro[bot]@users.noreply.github.com>
---
 NuGet.config            | 4 ++++
 eng/Version.Details.xml | 4 ++--
 eng/Versions.props      | 2 +-
 3 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/NuGet.config b/NuGet.config
index dda83539f80b93..1aa8a689cf7a8c 100644
--- a/NuGet.config
+++ b/NuGet.config
@@ -11,6 +11,10 @@
     <!--  Begin: Package sources from dotnet-emsdk -->
     <add key="darc-pub-dotnet-emsdk-d667257" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-d6672570/nuget/v3/index.json" />
     <add key="darc-pub-dotnet-emsdk-2674f58" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-2674f580/nuget/v3/index.json" />
+    <add key="darc-pub-dotnet-emsdk-2674f58-4" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-2674f580-4/nuget/v3/index.json" />
+    <add key="darc-pub-dotnet-emsdk-2674f58-3" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-2674f580-3/nuget/v3/index.json" />
+    <add key="darc-pub-dotnet-emsdk-2674f58-2" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-2674f580-2/nuget/v3/index.json" />
+    <add key="darc-pub-dotnet-emsdk-2674f58-1" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/darc-pub-dotnet-emsdk-2674f580-1/nuget/v3/index.json" />
     <!--  End: Package sources from dotnet-emsdk -->
     <!--  Begin: Package sources from dotnet-sdk -->
     <!--  End: Package sources from dotnet-sdk -->
diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml
index 4cfb890ca19ffe..6e45a2ae9593b4 100644
--- a/eng/Version.Details.xml
+++ b/eng/Version.Details.xml
@@ -354,9 +354,9 @@
       <Uri>https://dev.azure.com/dnceng/internal/_git/dotnet-optimization</Uri>
       <Sha>67613417f5e1af250e6ddfba79f8f2885d8e90fb</Sha>
     </Dependency>
-    <Dependency Name="Microsoft.DotNet.HotReload.Utils.Generator.BuildTool" Version="8.0.0-alpha.0.24402.1">
+    <Dependency Name="Microsoft.DotNet.HotReload.Utils.Generator.BuildTool" Version="8.0.0-alpha.0.24453.2">
       <Uri>https://github.com/dotnet/hotreload-utils</Uri>
-      <Sha>907017dae648b642c122f9a34573bd88ea0d9730</Sha>
+      <Sha>5339e12def2a3605d069c429840089ae27838728</Sha>
     </Dependency>
     <Dependency Name="System.Runtime.Numerics.TestData" Version="8.0.0-beta.24362.2">
       <Uri>https://github.com/dotnet/runtime-assets</Uri>
diff --git a/eng/Versions.props b/eng/Versions.props
index 82a77441ceec7a..654fcb841729af 100644
--- a/eng/Versions.props
+++ b/eng/Versions.props
@@ -188,7 +188,7 @@
     <MicrosoftDotNetXHarnessTestRunnersCommonVersion>8.0.0-prerelease.24229.2</MicrosoftDotNetXHarnessTestRunnersCommonVersion>
     <MicrosoftDotNetXHarnessTestRunnersXunitVersion>8.0.0-prerelease.24229.2</MicrosoftDotNetXHarnessTestRunnersXunitVersion>
     <MicrosoftDotNetXHarnessCLIVersion>8.0.0-prerelease.24229.2</MicrosoftDotNetXHarnessCLIVersion>
-    <MicrosoftDotNetHotReloadUtilsGeneratorBuildToolVersion>8.0.0-alpha.0.24402.1</MicrosoftDotNetHotReloadUtilsGeneratorBuildToolVersion>
+    <MicrosoftDotNetHotReloadUtilsGeneratorBuildToolVersion>8.0.0-alpha.0.24453.2</MicrosoftDotNetHotReloadUtilsGeneratorBuildToolVersion>
     <XUnitVersion>2.4.2</XUnitVersion>
     <XUnitAnalyzersVersion>1.0.0</XUnitAnalyzersVersion>
     <XUnitRunnerVisualStudioVersion>2.4.5</XUnitRunnerVisualStudioVersion>

From a99b4832ad0ddf95ee2cb05a72ad642d0545f5d4 Mon Sep 17 00:00:00 2001
From: Kevin Jones <kevin@vcsjones.com>
Date: Thu, 5 Sep 2024 13:43:35 -0400
Subject: [PATCH 12/21] [release/8.0-staging] Backport Azure Linux test changes

* Disable MD5 tests on Azure Linux

* Handle disabled algorithms on Azure Linux

* Fix MD5 failures on Azure Linux in System.Security.Cryptography.Pkcs

* Change BuildWithFactoryReadDirect to not use RSA+MD5

* Add Azure 3.0 helix test

---------

Co-authored-by: Rich Lander <rlander@microsoft.com>
---
 eng/pipelines/libraries/helix-queues-setup.yml       |  1 +
 .../AlgorithmImplementations/EC/ECKeyFileTests.cs    |  4 +++-
 .../ECDiffieHellman/ECDiffieHellmanFactory.cs        |  3 +++
 .../ECDiffieHellmanTests.ImportExport.cs             |  2 +-
 .../AlgorithmImplementations/ECDsa/ECDsaFactory.cs   |  2 ++
 .../AlgorithmImplementations/RSA/KeyGeneration.cs    |  4 ++--
 .../AlgorithmImplementations/RSA/RSAFactory.cs       |  2 ++
 .../AlgorithmImplementations/RSA/SignVerify.cs       | 12 ++++++++++--
 .../System/Security/Cryptography/SignatureSupport.cs | 11 +++++++----
 .../TestUtilities/System/PlatformDetection.Unix.cs   |  2 ++
 .../tests/RSACngProvider.cs                          |  2 ++
 .../tests/RSACryptoServiceProviderBackCompat.cs      |  9 ++++++---
 .../tests/RSACryptoServiceProviderProvider.cs        |  2 ++
 .../tests/EcDsaOpenSslProvider.cs                    |  2 +-
 .../tests/RSAOpenSslProvider.cs                      |  2 ++
 .../tests/Pkcs12/KeyBagTests.cs                      |  4 ++--
 .../tests/Pkcs12/ShroudedKeyBagTests.cs              |  8 ++++----
 .../tests/SignatureSupport.cs                        |  3 +++
 .../tests/SignedCms/SignerInfoTests.cs               |  2 +-
 .../tests/ChaCha20Poly1305Tests.cs                   |  5 +++++
 .../tests/DefaultECDiffieHellmanProvider.Unix.cs     |  2 +-
 .../tests/DefaultECDsaProvider.Unix.cs               |  2 +-
 .../tests/DefaultRSAProvider.cs                      |  2 ++
 .../System.Security.Cryptography/tests/HKDFTests.cs  |  7 ++++---
 .../tests/HmacMD5Tests.cs                            |  4 ++--
 25 files changed, 71 insertions(+), 28 deletions(-)

diff --git a/eng/pipelines/libraries/helix-queues-setup.yml b/eng/pipelines/libraries/helix-queues-setup.yml
index dcfa5a119db388..755a6d4ceb8ff8 100644
--- a/eng/pipelines/libraries/helix-queues-setup.yml
+++ b/eng/pipelines/libraries/helix-queues-setup.yml
@@ -72,6 +72,7 @@ jobs:
             - Ubuntu.2204.Amd64.Open
             - (Debian.12.Amd64.Open)Ubuntu.2204.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:debian-12-helix-amd64
             - (Mariner.2.0.Amd64.Open)Ubuntu.2204.amd64.open@mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-helix-amd64
+            - (AzureLinux.3.0.Amd64.Open)Ubuntu.2204.Amd64.open@mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-helix-amd64
             - (openSUSE.15.2.Amd64.Open)Ubuntu.2204.amd64.open@mcr.microsoft.com/dotnet-buildtools/prereqs:opensuse-15.2-helix-amd64
           - ${{ if or(ne(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}:
             - (Centos.9.Amd64.Open)Ubuntu.2204.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:centos-stream9-helix
diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs
index 492c9d451329c8..1a6686c4326db3 100644
--- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs
+++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/EC/ECKeyFileTests.cs
@@ -18,7 +18,9 @@ public abstract partial class ECKeyFileTests<T> where T : ECAlgorithm
 
         // This would need to be virtualized if there was ever a platform that
         // allowed explicit in ECDH or ECDSA but not the other.
-        public static bool SupportsExplicitCurves { get; } = EcDiffieHellman.Tests.ECDiffieHellmanFactory.ExplicitCurvesSupported;
+        public static bool SupportsExplicitCurves { get; } =
+            EcDiffieHellman.Tests.ECDiffieHellmanFactory.ExplicitCurvesSupported ||
+            EcDiffieHellman.Tests.ECDiffieHellmanFactory.ExplicitCurvesSupportFailOnUseOnly;
 
         public static bool CanDeriveNewPublicKey { get; } = EcDiffieHellman.Tests.ECDiffieHellmanFactory.CanDeriveNewPublicKey;
 
diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDiffieHellman/ECDiffieHellmanFactory.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDiffieHellman/ECDiffieHellmanFactory.cs
index 84bbea4587eef4..e45d5e88bd8874 100644
--- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDiffieHellman/ECDiffieHellmanFactory.cs
+++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDiffieHellman/ECDiffieHellmanFactory.cs
@@ -12,6 +12,7 @@ public interface IECDiffieHellmanProvider
 #endif
         bool IsCurveValid(Oid oid);
         bool ExplicitCurvesSupported { get; }
+        bool ExplicitCurvesSupportFailOnUseOnly => PlatformDetection.IsAzureLinux;
         bool CanDeriveNewPublicKey { get; }
         bool SupportsRawDerivation { get; }
         bool SupportsSha3 { get; }
@@ -48,5 +49,7 @@ public static bool IsCurveValid(Oid oid)
         public static bool SupportsRawDerivation => s_provider.SupportsRawDerivation;
 
         public static bool SupportsSha3 => s_provider.SupportsSha3;
+
+        public static bool ExplicitCurvesSupportFailOnUseOnly => s_provider.ExplicitCurvesSupportFailOnUseOnly;
     }
 }
diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDiffieHellman/ECDiffieHellmanTests.ImportExport.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDiffieHellman/ECDiffieHellmanTests.ImportExport.cs
index 82f78094bb1000..441bf94e40eb86 100644
--- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDiffieHellman/ECDiffieHellmanTests.ImportExport.cs
+++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDiffieHellman/ECDiffieHellmanTests.ImportExport.cs
@@ -319,7 +319,7 @@ public static void TestGeneralExportWithExplicitParameters()
         [Fact]
         public static void TestExplicitCurveImportOnUnsupportedPlatform()
         {
-            if (ECDiffieHellmanFactory.ExplicitCurvesSupported)
+            if (ECDiffieHellmanFactory.ExplicitCurvesSupported || ECDiffieHellmanFactory.ExplicitCurvesSupportFailOnUseOnly)
             {
                 return;
             }
diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaFactory.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaFactory.cs
index 59d45d3de99c7e..8781846d2abae5 100644
--- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaFactory.cs
+++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/ECDsa/ECDsaFactory.cs
@@ -12,6 +12,7 @@ public interface IECDsaProvider
 #endif
         bool IsCurveValid(Oid oid);
         bool ExplicitCurvesSupported { get; }
+        bool ExplicitCurvesSupportFailOnUseOnly => PlatformDetection.IsAzureLinux;
     }
 
     public static partial class ECDsaFactory
@@ -39,5 +40,6 @@ public static bool IsCurveValid(Oid oid)
         }
 
         public static bool ExplicitCurvesSupported => s_provider.ExplicitCurvesSupported;
+        public static bool ExplicitCurvesSupportFailOnUseOnly => s_provider.ExplicitCurvesSupportFailOnUseOnly;
     }
 }
diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/KeyGeneration.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/KeyGeneration.cs
index ea13e350b977f9..601118c17bd01c 100644
--- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/KeyGeneration.cs
+++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/KeyGeneration.cs
@@ -8,13 +8,13 @@ namespace System.Security.Cryptography.Rsa.Tests
     [SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser")]
     public class KeyGeneration
     {
-        [Fact]
+        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotAzureLinux))]
         public static void GenerateMinKey()
         {
             GenerateKey(rsa => GetMin(rsa.LegalKeySizes));
         }
 
-        [Fact]
+        [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotAzureLinux))]
         public static void GenerateSecondMinKey()
         {
             GenerateKey(rsa => GetSecondMin(rsa.LegalKeySizes));
diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAFactory.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAFactory.cs
index b13a6ee01d8e41..a01390dec6c982 100644
--- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAFactory.cs
+++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/RSAFactory.cs
@@ -12,6 +12,7 @@ public interface IRSAProvider
         bool SupportsSha2Oaep { get; }
         bool SupportsPss { get; }
         bool SupportsSha1Signatures { get; }
+        bool SupportsMd5Signatures { get; }
         bool SupportsSha3 { get; }
     }
 
@@ -43,6 +44,7 @@ public static RSA Create(RSAParameters rsaParameters)
         public static bool SupportsPss => s_provider.SupportsPss;
 
         public static bool SupportsSha1Signatures => s_provider.SupportsSha1Signatures;
+        public static bool SupportsMd5Signatures => s_provider.SupportsMd5Signatures;
 
         public static bool SupportsSha3 => s_provider.SupportsSha3;
         public static bool NoSupportsSha3 => !SupportsSha3;
diff --git a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/SignVerify.cs b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/SignVerify.cs
index 84c8f76d2b3eec..cc4d396d01ffb7 100644
--- a/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/SignVerify.cs
+++ b/src/libraries/Common/tests/System/Security/Cryptography/AlgorithmImplementations/RSA/SignVerify.cs
@@ -600,7 +600,11 @@ public static IEnumerable<object[]> RoundTripTheories
                         yield return new object[] { nameof(HashAlgorithmName.SHA1), rsaParameters };
                     }
 
-                    yield return new object[] { nameof(HashAlgorithmName.MD5), rsaParameters };
+                    if (RSAFactory.SupportsMd5Signatures)
+                    {
+                        yield return new object[] { nameof(HashAlgorithmName.MD5), rsaParameters };
+                    }
+
                     yield return new object[] { nameof(HashAlgorithmName.SHA256), rsaParameters };
                 }
 
@@ -1589,7 +1593,11 @@ public static IEnumerable<object[]> HashAlgorithmNames
                 yield return new object[] { HashAlgorithmName.SHA256.Name };
                 yield return new object[] { HashAlgorithmName.SHA384.Name };
                 yield return new object[] { HashAlgorithmName.SHA512.Name };
-                yield return new object[] { HashAlgorithmName.MD5.Name };
+
+                if (RSAFactory.SupportsMd5Signatures)
+                {
+                    yield return new object[] { HashAlgorithmName.MD5.Name };
+                }
 
                 if (RSAFactory.SupportsSha1Signatures)
                 {
diff --git a/src/libraries/Common/tests/System/Security/Cryptography/SignatureSupport.cs b/src/libraries/Common/tests/System/Security/Cryptography/SignatureSupport.cs
index b625df0184c2b2..94ecb8d82c5115 100644
--- a/src/libraries/Common/tests/System/Security/Cryptography/SignatureSupport.cs
+++ b/src/libraries/Common/tests/System/Security/Cryptography/SignatureSupport.cs
@@ -5,14 +5,17 @@ namespace System.Security.Cryptography.Tests
 {
     internal static class SignatureSupport
     {
-        internal static bool CanProduceSha1Signature(AsymmetricAlgorithm algorithm)
+        internal static bool CanProduceSha1Signature(AsymmetricAlgorithm algorithm) => CanProduceSignature(algorithm, HashAlgorithmName.SHA1);
+        internal static bool CanProduceMd5Signature(AsymmetricAlgorithm algorithm) => CanProduceSignature(algorithm, HashAlgorithmName.MD5);
+
+        private static bool CanProduceSignature(AsymmetricAlgorithm algorithm, HashAlgorithmName hashAlgorithmName)
         {
             using (algorithm)
             {
 #if NETFRAMEWORK
                 return true;
 #else
-                // We expect all non-Linux platforms to support SHA1 signatures, currently.
+                // We expect all non-Linux platforms to support any signatures, currently.
                 if (!OperatingSystem.IsLinux())
                 {
                     return true;
@@ -23,7 +26,7 @@ internal static bool CanProduceSha1Signature(AsymmetricAlgorithm algorithm)
                     case ECDsa ecdsa:
                         try
                         {
-                            ecdsa.SignData(Array.Empty<byte>(), HashAlgorithmName.SHA1);
+                            ecdsa.SignData(Array.Empty<byte>(), hashAlgorithmName);
                             return true;
                         }
                         catch (CryptographicException)
@@ -33,7 +36,7 @@ internal static bool CanProduceSha1Signature(AsymmetricAlgorithm algorithm)
                     case RSA rsa:
                         try
                         {
-                            rsa.SignData(Array.Empty<byte>(), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
+                            rsa.SignData(Array.Empty<byte>(), hashAlgorithmName, RSASignaturePadding.Pkcs1);
                             return true;
                         }
                         catch (CryptographicException)
diff --git a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs
index 48b8ba86f730a6..2de3b94fad7640 100644
--- a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs
+++ b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs
@@ -27,9 +27,11 @@ public static partial class PlatformDetection
         public static bool IsTizen => IsDistroAndVersion("tizen");
         public static bool IsFedora => IsDistroAndVersion("fedora");
         public static bool IsLinuxBionic => IsBionic();
+        public static bool IsAzureLinux => IsDistroAndVersionOrHigher("azurelinux", 3);
 
         public static bool IsMonoLinuxArm64 => IsMonoRuntime && IsLinux && IsArm64Process;
         public static bool IsNotMonoLinuxArm64 => !IsMonoLinuxArm64;
+        public static bool IsNotAzureLinux => !IsAzureLinux;
 
         // OSX family
         public static bool IsOSXLike => IsOSX || IsiOS || IstvOS || IsMacCatalyst;
diff --git a/src/libraries/System.Security.Cryptography.Cng/tests/RSACngProvider.cs b/src/libraries/System.Security.Cryptography.Cng/tests/RSACngProvider.cs
index d41df34b61404b..025bbc426a4cdf 100644
--- a/src/libraries/System.Security.Cryptography.Cng/tests/RSACngProvider.cs
+++ b/src/libraries/System.Security.Cryptography.Cng/tests/RSACngProvider.cs
@@ -37,6 +37,8 @@ public bool Supports384PrivateKey
 
         public bool SupportsSha1Signatures => true;
 
+        public bool SupportsMd5Signatures => true;
+
         public bool SupportsSha3 { get; } = SHA3_256.IsSupported; // If SHA3_256 is supported, assume 384 and 512 are, too.
     }
 
diff --git a/src/libraries/System.Security.Cryptography.Csp/tests/RSACryptoServiceProviderBackCompat.cs b/src/libraries/System.Security.Cryptography.Csp/tests/RSACryptoServiceProviderBackCompat.cs
index 887bdc3d983e2e..8ef0c9474d73d7 100644
--- a/src/libraries/System.Security.Cryptography.Csp/tests/RSACryptoServiceProviderBackCompat.cs
+++ b/src/libraries/System.Security.Cryptography.Csp/tests/RSACryptoServiceProviderBackCompat.cs
@@ -156,9 +156,12 @@ public static void VerifyLegacySignVerifyHash(bool useLegacySign, bool useLegacy
 
         public static IEnumerable<object[]> AlgorithmIdentifiers()
         {
-            yield return new object[] { "MD5", MD5.Create() };
-            yield return new object[] { "MD5", typeof(MD5) };
-            yield return new object[] { "MD5", "1.2.840.113549.2.5" };
+            if (RSAFactory.SupportsMd5Signatures)
+            {
+                yield return new object[] { "MD5", MD5.Create() };
+                yield return new object[] { "MD5", typeof(MD5) };
+                yield return new object[] { "MD5", "1.2.840.113549.2.5" };
+            }
 
             if (RSAFactory.SupportsSha1Signatures)
             {
diff --git a/src/libraries/System.Security.Cryptography.Csp/tests/RSACryptoServiceProviderProvider.cs b/src/libraries/System.Security.Cryptography.Csp/tests/RSACryptoServiceProviderProvider.cs
index 7cd358cd5d1213..fb40b5ece1d0fc 100644
--- a/src/libraries/System.Security.Cryptography.Csp/tests/RSACryptoServiceProviderProvider.cs
+++ b/src/libraries/System.Security.Cryptography.Csp/tests/RSACryptoServiceProviderProvider.cs
@@ -9,6 +9,7 @@ namespace System.Security.Cryptography.Rsa.Tests
     public class RSACryptoServiceProviderProvider : IRSAProvider
     {
         private bool? _supportsSha1Signatures;
+        private bool? _supportsMd5Signatures;
 
         public RSA Create() => new RSACryptoServiceProvider();
 
@@ -23,6 +24,7 @@ public class RSACryptoServiceProviderProvider : IRSAProvider
         public bool SupportsPss => false;
 
         public bool SupportsSha1Signatures => _supportsSha1Signatures ??= SignatureSupport.CanProduceSha1Signature(Create());
+        public bool SupportsMd5Signatures => _supportsMd5Signatures ??= SignatureSupport.CanProduceMd5Signature(Create());
 
         public bool SupportsSha3 => false;
     }
diff --git a/src/libraries/System.Security.Cryptography.OpenSsl/tests/EcDsaOpenSslProvider.cs b/src/libraries/System.Security.Cryptography.OpenSsl/tests/EcDsaOpenSslProvider.cs
index aac122ce56d587..4735038ec0184c 100644
--- a/src/libraries/System.Security.Cryptography.OpenSsl/tests/EcDsaOpenSslProvider.cs
+++ b/src/libraries/System.Security.Cryptography.OpenSsl/tests/EcDsaOpenSslProvider.cs
@@ -50,7 +50,7 @@ public bool ExplicitCurvesSupported
         {
             get
             {
-                return true;
+                return !PlatformDetection.IsAzureLinux;
             }
         }
     }
diff --git a/src/libraries/System.Security.Cryptography.OpenSsl/tests/RSAOpenSslProvider.cs b/src/libraries/System.Security.Cryptography.OpenSsl/tests/RSAOpenSslProvider.cs
index 0adcda4bfad5ec..18aa9528877d9d 100644
--- a/src/libraries/System.Security.Cryptography.OpenSsl/tests/RSAOpenSslProvider.cs
+++ b/src/libraries/System.Security.Cryptography.OpenSsl/tests/RSAOpenSslProvider.cs
@@ -8,6 +8,7 @@ namespace System.Security.Cryptography.Rsa.Tests
     public class RSAOpenSslProvider : IRSAProvider
     {
         private bool? _supportsSha1Signatures;
+        private bool? _supportsMd5Signatures;
 
         public RSA Create() => new RSAOpenSsl();
 
@@ -22,6 +23,7 @@ public class RSAOpenSslProvider : IRSAProvider
         public bool SupportsPss => true;
 
         public bool SupportsSha1Signatures => _supportsSha1Signatures ??= SignatureSupport.CanProduceSha1Signature(Create());
+        public bool SupportsMd5Signatures => _supportsMd5Signatures ??= SignatureSupport.CanProduceMd5Signature(Create());
 
         public bool SupportsSha3 => SHA3_256.IsSupported; // If SHA3_256 is supported, assume 384 and 512 are, too.
     }
diff --git a/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/KeyBagTests.cs b/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/KeyBagTests.cs
index 2a3ba970c01aef..071a210c79dd55 100644
--- a/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/KeyBagTests.cs
+++ b/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/KeyBagTests.cs
@@ -29,7 +29,7 @@ public static void BuildWithFactoryReadDirect()
                     Assert.True(rsa2.TrySignData(
                         keyBag.Pkcs8PrivateKey.Span,
                         sig,
-                        HashAlgorithmName.MD5,
+                        HashAlgorithmName.SHA256,
                         RSASignaturePadding.Pkcs1,
                         out int sigLen));
 
@@ -38,7 +38,7 @@ public static void BuildWithFactoryReadDirect()
                     Assert.True(rsa.VerifyData(
                         keyBag.Pkcs8PrivateKey.Span,
                         sig,
-                        HashAlgorithmName.MD5,
+                        HashAlgorithmName.SHA256,
                         RSASignaturePadding.Pkcs1));
                 }
             }
diff --git a/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/ShroudedKeyBagTests.cs b/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/ShroudedKeyBagTests.cs
index b2141a822c218e..aebe413b357633 100644
--- a/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/ShroudedKeyBagTests.cs
+++ b/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/ShroudedKeyBagTests.cs
@@ -40,7 +40,7 @@ public static void BuildWithCharsFactoryReadDirect()
                     Assert.True(rsa2.TrySignData(
                         keyBag.EncryptedPkcs8PrivateKey.Span,
                         sig,
-                        HashAlgorithmName.MD5,
+                        HashAlgorithmName.SHA256,
                         RSASignaturePadding.Pkcs1,
                         out int sigLen));
 
@@ -49,7 +49,7 @@ public static void BuildWithCharsFactoryReadDirect()
                     Assert.True(rsa.VerifyData(
                         keyBag.EncryptedPkcs8PrivateKey.Span,
                         sig,
-                        HashAlgorithmName.MD5,
+                        HashAlgorithmName.SHA256,
                         RSASignaturePadding.Pkcs1));
                 }
             }
@@ -77,7 +77,7 @@ public static void BuildWithBytesFactoryReadDirect()
                     Assert.True(rsa2.TrySignData(
                         keyBag.EncryptedPkcs8PrivateKey.Span,
                         sig,
-                        HashAlgorithmName.MD5,
+                        HashAlgorithmName.SHA256,
                         RSASignaturePadding.Pkcs1,
                         out int sigLen));
 
@@ -86,7 +86,7 @@ public static void BuildWithBytesFactoryReadDirect()
                     Assert.True(rsa.VerifyData(
                         keyBag.EncryptedPkcs8PrivateKey.Span,
                         sig,
-                        HashAlgorithmName.MD5,
+                        HashAlgorithmName.SHA256,
                         RSASignaturePadding.Pkcs1));
                 }
             }
diff --git a/src/libraries/System.Security.Cryptography.Pkcs/tests/SignatureSupport.cs b/src/libraries/System.Security.Cryptography.Pkcs/tests/SignatureSupport.cs
index ee31485341cab3..5e317d841cfc48 100644
--- a/src/libraries/System.Security.Cryptography.Pkcs/tests/SignatureSupport.cs
+++ b/src/libraries/System.Security.Cryptography.Pkcs/tests/SignatureSupport.cs
@@ -10,5 +10,8 @@ public class SignatureSupport
     {
         public static bool SupportsRsaSha1Signatures { get; } =
             System.Security.Cryptography.Tests.SignatureSupport.CanProduceSha1Signature(RSA.Create());
+
+        public static bool SupportsRsaMd5Signatures { get; } =
+            System.Security.Cryptography.Tests.SignatureSupport.CanProduceMd5Signature(RSA.Create());
     }
 }
diff --git a/src/libraries/System.Security.Cryptography.Pkcs/tests/SignedCms/SignerInfoTests.cs b/src/libraries/System.Security.Cryptography.Pkcs/tests/SignedCms/SignerInfoTests.cs
index 10a51fc819545a..c3ff48deb9eb85 100644
--- a/src/libraries/System.Security.Cryptography.Pkcs/tests/SignedCms/SignerInfoTests.cs
+++ b/src/libraries/System.Security.Cryptography.Pkcs/tests/SignedCms/SignerInfoTests.cs
@@ -198,7 +198,7 @@ public static void CheckSignature_ExtraStore_IsAdditional()
             signer.CheckSignature(new X509Certificate2Collection(), true);
         }
 
-        [Fact]
+        [ConditionalFact(typeof(SignatureSupport), nameof(SignatureSupport.SupportsRsaMd5Signatures))]
         public static void CheckSignature_MD5WithRSA()
         {
             SignedCms cms = new SignedCms();
diff --git a/src/libraries/System.Security.Cryptography/tests/ChaCha20Poly1305Tests.cs b/src/libraries/System.Security.Cryptography/tests/ChaCha20Poly1305Tests.cs
index ced6edcf350951..24ec6ffbc99fc6 100644
--- a/src/libraries/System.Security.Cryptography/tests/ChaCha20Poly1305Tests.cs
+++ b/src/libraries/System.Security.Cryptography/tests/ChaCha20Poly1305Tests.cs
@@ -478,6 +478,11 @@ public static void CheckIsSupported()
                 // CryptoKit is supported on macOS 10.15+, which is our minimum target.
                 expectedIsSupported = true;
             }
+            else if (PlatformDetection.IsAzureLinux)
+            {
+                // Though Azure Linux uses OpenSSL, they build OpenSSL without ChaCha20-Poly1305.
+                expectedIsSupported = false;
+            }
             else if (PlatformDetection.OpenSslPresentOnSystem && PlatformDetection.IsOpenSslSupported)
             {
                 const int OpenSslChaChaMinimumVersion = 0x1_01_00_00_F; //major_minor_fix_patch_status
diff --git a/src/libraries/System.Security.Cryptography/tests/DefaultECDiffieHellmanProvider.Unix.cs b/src/libraries/System.Security.Cryptography/tests/DefaultECDiffieHellmanProvider.Unix.cs
index 162831d72ac696..b1c51483231ddb 100644
--- a/src/libraries/System.Security.Cryptography/tests/DefaultECDiffieHellmanProvider.Unix.cs
+++ b/src/libraries/System.Security.Cryptography/tests/DefaultECDiffieHellmanProvider.Unix.cs
@@ -25,7 +25,7 @@ public bool ExplicitCurvesSupported
         {
             get
             {
-                if (PlatformDetection.IsOSXLike)
+                if (PlatformDetection.IsOSXLike || PlatformDetection.IsAzureLinux)
                 {
                     return false;
                 }
diff --git a/src/libraries/System.Security.Cryptography/tests/DefaultECDsaProvider.Unix.cs b/src/libraries/System.Security.Cryptography/tests/DefaultECDsaProvider.Unix.cs
index 53e9198720360b..5ade1828c02774 100644
--- a/src/libraries/System.Security.Cryptography/tests/DefaultECDsaProvider.Unix.cs
+++ b/src/libraries/System.Security.Cryptography/tests/DefaultECDsaProvider.Unix.cs
@@ -25,7 +25,7 @@ public bool ExplicitCurvesSupported
         {
             get
             {
-                if (PlatformDetection.IsOSXLike)
+                if (PlatformDetection.IsOSXLike || PlatformDetection.IsAzureLinux)
                 {
                     return false;
                 }
diff --git a/src/libraries/System.Security.Cryptography/tests/DefaultRSAProvider.cs b/src/libraries/System.Security.Cryptography/tests/DefaultRSAProvider.cs
index c65b78ace1288e..d6883088f06f24 100644
--- a/src/libraries/System.Security.Cryptography/tests/DefaultRSAProvider.cs
+++ b/src/libraries/System.Security.Cryptography/tests/DefaultRSAProvider.cs
@@ -10,6 +10,7 @@ public class DefaultRSAProvider : IRSAProvider
     {
         private bool? _supports384PrivateKey;
         private bool? _supportsSha1Signatures;
+        private bool? _supportsMd5Signatures;
 
         public RSA Create() => RSA.Create();
 
@@ -41,6 +42,7 @@ public bool Supports384PrivateKey
         }
 
         public bool SupportsSha1Signatures => _supportsSha1Signatures ??= SignatureSupport.CanProduceSha1Signature(Create());
+        public bool SupportsMd5Signatures => _supportsMd5Signatures ??= SignatureSupport.CanProduceMd5Signature(Create());
 
         public bool SupportsLargeExponent => true;
 
diff --git a/src/libraries/System.Security.Cryptography/tests/HKDFTests.cs b/src/libraries/System.Security.Cryptography/tests/HKDFTests.cs
index 6f58c00e80994c..9c3537808b0a70 100644
--- a/src/libraries/System.Security.Cryptography/tests/HKDFTests.cs
+++ b/src/libraries/System.Security.Cryptography/tests/HKDFTests.cs
@@ -14,6 +14,8 @@ public abstract class HKDFTests
         protected abstract byte[] Expand(HashAlgorithmName hash, byte[] prk, int outputLength, byte[] info);
         protected abstract byte[] DeriveKey(HashAlgorithmName hash, byte[] ikm, int outputLength, byte[] salt, byte[] info);
 
+        internal static bool MD5Supported => !PlatformDetection.IsBrowser && !PlatformDetection.IsAzureLinux;
+
         [Theory]
         [MemberData(nameof(GetHkdfTestCases))]
         public void ExtractTests(HkdfTestCase test)
@@ -22,9 +24,8 @@ public void ExtractTests(HkdfTestCase test)
             Assert.Equal(test.Prk, prk);
         }
 
-        [Theory]
+        [ConditionalTheory(nameof(MD5Supported))]
         [MemberData(nameof(GetHkdfTestCases))]
-        [SkipOnPlatform(TestPlatforms.Browser, "MD5 is not supported on Browser")]
         public void ExtractTamperHashTests(HkdfTestCase test)
         {
             byte[] prk = Extract(HashAlgorithmName.MD5, 128 / 8, test.Ikm, test.Salt);
@@ -257,7 +258,7 @@ public static IEnumerable<object[]> GetPrkTooShortTestCases()
             yield return new object[] { HashAlgorithmName.SHA256, 256 / 8 - 1 };
             yield return new object[] { HashAlgorithmName.SHA512, 512 / 8 - 1 };
 
-            if (!PlatformDetection.IsBrowser)
+            if (MD5Supported)
             {
                 yield return new object[] { HashAlgorithmName.MD5, 128 / 8 - 1 };
             }
diff --git a/src/libraries/System.Security.Cryptography/tests/HmacMD5Tests.cs b/src/libraries/System.Security.Cryptography/tests/HmacMD5Tests.cs
index 2adf417aec8458..fa18da8e11cbde 100644
--- a/src/libraries/System.Security.Cryptography/tests/HmacMD5Tests.cs
+++ b/src/libraries/System.Security.Cryptography/tests/HmacMD5Tests.cs
@@ -9,12 +9,12 @@
 
 namespace System.Security.Cryptography.Tests
 {
-    [SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser")]
+    [ConditionalClass(typeof(HmacMD5Tests.Traits), nameof(HmacMD5Tests.Traits.IsSupported))]
     public class HmacMD5Tests : Rfc2202HmacTests<HmacMD5Tests.Traits>
     {
         public sealed class Traits : IHmacTrait
         {
-            public static bool IsSupported => true;
+            public static bool IsSupported => !PlatformDetection.IsAzureLinux && !PlatformDetection.IsBrowser;
             public static int HashSizeInBytes => HMACSHA1.HashSizeInBytes;
         }
 

From 1d093702e96f83b470a54fb7b43f68b6811e5e10 Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
 <41898282+github-actions[bot]@users.noreply.github.com>
Date: Thu, 5 Sep 2024 10:52:49 -0700
Subject: [PATCH 13/21] [release/8.0-staging] Fix copying ephemeral keys to
 keychains.

Starting on macOS Sequoia, at least in beta, SecKeychainitemCopyKeychain no longer returns errSecNoSuchKeychain for ephemeral keys.
Instead, it returns errSecInvalidItemRef.

This adds the error code in the handling logic for when we need to add an ephemeral key to the target keychain.

Co-authored-by: Kevin Jones <kevin@vcsjones.com>
---
 .../System.Security.Cryptography.Native.Apple/pal_x509_macos.c  | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/native/libs/System.Security.Cryptography.Native.Apple/pal_x509_macos.c b/src/native/libs/System.Security.Cryptography.Native.Apple/pal_x509_macos.c
index 41ba9648259c76..fc261117a1588b 100644
--- a/src/native/libs/System.Security.Cryptography.Native.Apple/pal_x509_macos.c
+++ b/src/native/libs/System.Security.Cryptography.Native.Apple/pal_x509_macos.c
@@ -391,7 +391,7 @@ int32_t AppleCryptoNative_X509CopyWithPrivateKey(SecCertificateRef cert,
     SecKeychainItemRef itemCopy = NULL;
 
     // This only happens with an ephemeral key, so the keychain we're adding it to is temporary.
-    if (status == errSecNoSuchKeychain)
+    if (status == errSecNoSuchKeychain || status == errSecInvalidItemRef)
     {
         status = AddKeyToKeychain(privateKey, targetKeychain, NULL);
     }

From 8072b235c7742ac2178dee11cfb44ee8585304bd Mon Sep 17 00:00:00 2001
From: Eric StJohn <ericstj@microsoft.com>
Date: Thu, 5 Sep 2024 11:45:28 -0700
Subject: [PATCH 14/21] [Release/8.0-staging] Reduce net core app current
 package dependencies (#107161)

* Avoid package dependencies on libraries in the shared framework (#106172)

* Avoid package dependencies on libraries in the shared framework

We can avoid these dependencies since we can count on the library being
part of the shared framework.  Fewer dependencies means less packages
downloaded, less for customers to service, less copied into the output
directory when serviced.

* Add warning code.

* Address feedback

* Add an option to enable servicing for transitive dependencies

* Enable all packages that removed dependencies

* Add additional packages required for up-stack servicing

* Permit settting ServiceTransitiveDependencies in projects as well
---
 docs/coding-guidelines/libraries-packaging.md |  8 +++
 docs/project/library-servicing.md             |  4 ++
 eng/packaging.targets                         | 58 +++++++++++++++++--
 ...Microsoft.Extensions.Caching.Memory.csproj |  2 +
 ...osoft.Extensions.Configuration.Json.csproj |  7 ++-
 ...xtensions.Configuration.UserSecrets.csproj |  2 +
 ...rosoft.Extensions.Configuration.Xml.csproj |  4 +-
 ...icrosoft.Extensions.DependencyModel.csproj | 12 ++--
 ...Extensions.Diagnostics.Abstractions.csproj |  7 ++-
 .../Microsoft.Extensions.Diagnostics.csproj   |  2 +
 ...oft.Extensions.Hosting.Abstractions.csproj |  2 +
 ...icrosoft.Extensions.Hosting.Systemd.csproj |  2 +
 ....Extensions.Hosting.WindowsServices.csproj |  2 +
 .../src/Microsoft.Extensions.Hosting.csproj   |  2 +
 .../src/Microsoft.Extensions.Http.csproj      |  2 +
 ...oft.Extensions.Logging.Abstractions.csproj |  4 ++
 ...ft.Extensions.Logging.Configuration.csproj |  2 +
 ...icrosoft.Extensions.Logging.Console.csproj |  5 ++
 .../Microsoft.Extensions.Logging.Debug.csproj |  2 +
 ...crosoft.Extensions.Logging.EventLog.csproj |  2 +
 ...soft.Extensions.Logging.EventSource.csproj |  7 ++-
 ...soft.Extensions.Logging.TraceSource.csproj |  2 +
 .../src/Microsoft.Extensions.Logging.csproj   |  4 +-
 ....Configuration.ConfigurationManager.csproj |  4 +-
 .../src/System.Data.Odbc.csproj               |  5 +-
 .../src/System.Data.OleDb.csproj              |  2 +
 ...stem.Diagnostics.PerformanceCounter.csproj |  2 +
 ...DirectoryServices.AccountManagement.csproj |  2 +
 .../src/System.Memory.Data.csproj             |  6 +-
 .../src/System.Net.Http.Json.csproj           |  5 +-
 .../src/System.Reflection.Metadata.csproj     |  5 +-
 ...stem.Reflection.MetadataLoadContext.csproj |  6 +-
 .../System.Security.Cryptography.Pkcs.csproj  |  4 +-
 .../System.Security.Cryptography.Xml.csproj   |  4 +-
 ...em.ServiceProcess.ServiceController.csproj |  2 +
 .../src/System.Text.Json.csproj               |  7 ++-
 36 files changed, 167 insertions(+), 31 deletions(-)

diff --git a/docs/coding-guidelines/libraries-packaging.md b/docs/coding-guidelines/libraries-packaging.md
index f7c926890bf8e8..406937131c891d 100644
--- a/docs/coding-guidelines/libraries-packaging.md
+++ b/docs/coding-guidelines/libraries-packaging.md
@@ -18,6 +18,14 @@ Source generators and analyzers can be included in the shared framework by addin
 
 Removing a library from the shared framework is a breaking change and should be avoided.
 
+### References to libraries in the shared framework that produce packages
+
+It's beneficial to avoid project references to libraries that are in the shared framework because it makes the package graph smaller which reduces the number of packages that require servicing and the number of libraries that end up being copied into the application directory.
+
+If a dependency is part of the shared framework a project/package reference is never required on the latest version (`NetCoreAppCurrent`).  A reference is required for previous .NET versions even if the dependency is part of the shared framework if the project you are building targets .NETStandard and references the project there.  You may completely avoid a package dependency on .NETStandard and .NET if it's not needed for .NETStandard (for example - if it is an implementation only dependency and you're building a PNSE assembly for .NETStandard).
+
+Warning NETPKG0001 is emitted when you have an unnecessary reference to a library that is part of the shared framework.  To avoid this warning, make sure your ProjectReference is conditioned so that it doesn't apply on `NetCoreAppCurrent`.
+
 ## Transport package
 
 Transport packages are non-shipping packages that dotnet/runtime produces in order to share binaries with other repositories.
diff --git a/docs/project/library-servicing.md b/docs/project/library-servicing.md
index bea41e65265b46..8c1f86be2694e3 100644
--- a/docs/project/library-servicing.md
+++ b/docs/project/library-servicing.md
@@ -16,6 +16,10 @@ If a library is packable (check for the `<IsPackable>true</IsPackable>` property
 
 When you make a change to a library & ship it during the servicing release, the `ServicingVersion` must be bumped. This property is found in the library's source project. It's also possible that the property is not in that file, in which case you'll need to add it to the library's source project and set it to 1. If the property is already present in your library's source project, just increment the servicing version by 1.
 
+## Optionally ensure all up-stack packages are also produced
+
+If you wish to ensure that every package that references a serviced package is also serviced itself, you can enable validation by setting `ServiceTransitiveDependencies` to true.  This can be done in an individual project, or globally.  When doing this then building the repo, eg: `build libs -allConfigurations` you'll see errors from any project that didn't enable servicing.  Reasons for forcing packages which depend on your package to service are security servicing or removing dependencies.
+
 ## Test your changes
 
 All that's left is to ensure that your changes have worked as expected. To do so, execute the following steps:
diff --git a/eng/packaging.targets b/eng/packaging.targets
index 67405cb51aeff0..2207a9d1f29a84 100644
--- a/eng/packaging.targets
+++ b/eng/packaging.targets
@@ -196,6 +196,21 @@
     </ItemGroup>
   </Target>
 
+  <Target Name="WarnOnProjectReferenceToFrameworkAssemblies"
+          BeforeTargets="IncludeTransitiveProjectReferences"
+          Condition="'$(TargetFramework)' == '$(NetCoreAppCurrent)' and
+                     '@(ProjectReference)' != ''">
+    <!-- Find project references that overlap with NetCoreApp, are direct (NuGetPackageId is not set), actually referenced (ReferenceOutputAssembly), and not hidden with PrivateAssets
+         ProjectReferences can opt out of this checking by setting AllowFrameworkPackageReference, though they should not. -->
+    <Warning Text="Project reference '%(ProjectReference.Identity)' is a reference to a framework assembly and is not required in $(NetCoreAppCurrent) (NetCoreAppCurrent)."
+             Code="NETPKG0001"
+             Condition="$(NetCoreAppLibrary.Contains('%(ProjectReference.Filename);')) and
+                        '%(ProjectReference.ReferenceOutputAssembly)' != 'false' and
+                        '%(ProjectReference.NuGetPackageId)' == '' and
+                        '%(ProjectReference.PrivateAssets)' != 'all' and
+                        '%(ProjectReference.AllowFrameworkPackageReference)' != 'true'" />
+  </Target>
+
   <Target Name="GenerateMultiTargetRoslynComponentTargetsFile"
           Inputs="$(MSBuildProjectFullPath);$(_MultiTargetRoslynComponentTargetsTemplate)"
           Outputs="$(MultiTargetRoslynComponentTargetsFileIntermediatePath)">
@@ -303,12 +318,47 @@
     </ItemGroup>
   </Target>
 
-  <Target Name="ValidateServicingVersionIsProperlySet"
+  <ItemDefinitionGroup>
+    <TargetPathWithTargetPlatformMoniker>
+      <!-- When ServiceTransitiveDependencies is set, flow the packaging state -->
+      <GeneratePackageOnBuild Condition="'$(ServiceTransitiveDependencies)' == 'true'">$(GeneratePackageOnBuild)</GeneratePackageOnBuild>
+    </TargetPathWithTargetPlatformMoniker>
+  </ItemDefinitionGroup>
+
+  <!-- Flows the list of ProjectReferences that are enabled for packaging when building a multi-targeting project -->
+  <Target Name="_AddTransitiveServicedPackagesToOutput"
+          AfterTargets="GetTargetPathWithTargetPlatformMoniker"
+          Condition="'$(IsInnerBuild)' == 'true'">
+    <PropertyGroup>
+      <_TransitiveServicedPackages
+          Condition="'%(ReferencePath.ReferenceSourceTarget)' == 'ProjectReference' and
+                     '%(ReferencePath.GeneratePackageOnBuild)' == 'true'"
+                     >@(ReferencePath->'%(OriginalProjectReferenceItemSpec)')</_TransitiveServicedPackages>
+    </PropertyGroup>
+    <ItemGroup>
+      <TargetPathWithTargetPlatformMoniker TransitiveServicedPackages="$(_TransitiveServicedPackages)" />
+    </ItemGroup>
+  </Target>
+
+  <!-- Validate that ServicingVersion is set and packing is enabled.  Runs once in the outer build (or only build if no outer build exists). -->
+  <Target Name="ValidateServicingProperties"
           Condition="'$(PreReleaseVersionLabel)' == 'servicing' and
                      '$(PackageUseIncrementalServicingVersion)' == 'true' and
-                     '$(DotNetBuildFromSource)' != 'true'"
-          AfterTargets="GenerateNuspec">
-    <Error Condition="'$(ServicingVersion)' == '0'" Text="ServicingVersion is set to 0 and it should be an increment of the patch version from the last released package." />
+                     '$(DotNetBuildFromSource)' != 'true' and
+                     '$(IsInnerBuild)' != 'true'"
+          AfterTargets="Build">
+    <ItemGroup>
+      <TransitiveServicedPackages Include="%(InnerOutput.TransitiveServicedPackages)" Condition="'$(IsCrossTargetingBuild)' == 'true'" />
+      <TransitiveServicedPackages Include="'%(ReferencePath.OriginalProjectReferenceItemSpec)"
+                                  Condition="'%(ReferencePath.ReferenceSourceTarget)' == 'ProjectReference' and
+                                             '%(ReferencePath.GeneratePackageOnBuild)' == 'true'" />
+    </ItemGroup>
+    <Error Condition="'$(ServicingVersion)' == '0' and '$(GeneratePackageOnBuild)' == 'true'"
+           Text="ServicingVersion is set to 0 and it should be an increment of the patch version from the last released package." />
+
+    <Error Condition="'$(GeneratePackageOnBuild)' != 'true' and
+                  '@(TransitiveServicedPackages)' != ''"
+        Text="This project did not set GeneratePackageOnBuild, but dependencies '@(TransitiveServicedPackages)' did.  Please ship this project by setting GeneratePackageOnBuild to true and incrementing ServicingVersion." />
   </Target>
 
 </Project>
diff --git a/src/libraries/Microsoft.Extensions.Caching.Memory/src/Microsoft.Extensions.Caching.Memory.csproj b/src/libraries/Microsoft.Extensions.Caching.Memory/src/Microsoft.Extensions.Caching.Memory.csproj
index 469e6e572536ef..a24f2352fc42a0 100644
--- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/Microsoft.Extensions.Caching.Memory.csproj
+++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/Microsoft.Extensions.Caching.Memory.csproj
@@ -4,6 +4,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>In-memory cache implementation of Microsoft.Extensions.Caching.Memory.IMemoryCache.</PackageDescription>
   </PropertyGroup>
 
diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj b/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj
index f981f3e064bbd7..91ba0df583c61e 100644
--- a/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj
+++ b/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj
@@ -5,6 +5,8 @@
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>JSON configuration provider implementation for Microsoft.Extensions.Configuration. This package enables you to read your application's settings from a JSON file. You can use JsonConfigurationExtensions.AddJsonFile extension method on IConfigurationBuilder to add the JSON configuration provider to the configuration builder.</PackageDescription>
   </PropertyGroup>
 
@@ -13,9 +15,12 @@
     <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Configuration.Abstractions\src\Microsoft.Extensions.Configuration.Abstractions.csproj" />
     <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Configuration.FileExtensions\src\Microsoft.Extensions.Configuration.FileExtensions.csproj" />
     <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.FileProviders.Abstractions\src\Microsoft.Extensions.FileProviders.Abstractions.csproj" />
-    <ProjectReference Include="$(LibrariesProjectRoot)System.Text.Json\src\System.Text.Json.csproj" />
     <Compile Include="$(CommonPath)System\ThrowHelper.cs"
              Link="Common\System\ThrowHelper.cs" />
   </ItemGroup>
 
+  <ItemGroup Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">
+    <ProjectReference Include="$(LibrariesProjectRoot)System.Text.Json\src\System.Text.Json.csproj" />
+  </ItemGroup>
+
 </Project>
diff --git a/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/Microsoft.Extensions.Configuration.UserSecrets.csproj b/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/Microsoft.Extensions.Configuration.UserSecrets.csproj
index 4b200df893380c..472db60e169b88 100644
--- a/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/Microsoft.Extensions.Configuration.UserSecrets.csproj
+++ b/src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/Microsoft.Extensions.Configuration.UserSecrets.csproj
@@ -4,6 +4,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>User secrets configuration provider implementation for Microsoft.Extensions.Configuration. User secrets mechanism enables you to override application configuration settings with values stored in the local secrets file. You can use UserSecretsConfigurationExtensions.AddUserSecrets extension method on IConfigurationBuilder to add user secrets provider to the configuration builder.</PackageDescription>
   </PropertyGroup>
 
diff --git a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/Microsoft.Extensions.Configuration.Xml.csproj b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/Microsoft.Extensions.Configuration.Xml.csproj
index 7cf288a00eb842..82fb8a995b4792 100644
--- a/src/libraries/Microsoft.Extensions.Configuration.Xml/src/Microsoft.Extensions.Configuration.Xml.csproj
+++ b/src/libraries/Microsoft.Extensions.Configuration.Xml/src/Microsoft.Extensions.Configuration.Xml.csproj
@@ -4,6 +4,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>XML configuration provider implementation for Microsoft.Extensions.Configuration. This package enables you to read configuration parameters from XML files. You can use XmlConfigurationExtensions.AddXmlFile extension method on IConfigurationBuilder to add XML configuration provider to the configuration builder.</PackageDescription>
   </PropertyGroup>
 
@@ -24,7 +26,7 @@
   <ItemGroup Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))">
     <Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\RequiresDynamicCodeAttribute.cs" />
   </ItemGroup>
-  
+
   <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
     <Reference Include="System.Security" />
   </ItemGroup>
diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Microsoft.Extensions.DependencyModel.csproj b/src/libraries/Microsoft.Extensions.DependencyModel/src/Microsoft.Extensions.DependencyModel.csproj
index e135c23a6bb90f..c53c917361b1b2 100644
--- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Microsoft.Extensions.DependencyModel.csproj
+++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Microsoft.Extensions.DependencyModel.csproj
@@ -3,8 +3,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
-    <GeneratePackageOnBuild>false</GeneratePackageOnBuild>
-    <ServicingVersion>1</ServicingVersion>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>2</ServicingVersion>
     <PackageDescription>Provides abstractions for reading `.deps` files. When a .NET application is compiled, the SDK generates a JSON manifest file (`&lt;ApplicationName&gt;.deps.json`) that contains information about application dependencies. You can use `Microsoft.Extensions.DependencyModel` to read information from this manifest at run time. This is useful when you want to dynamically compile code (for example, using Roslyn Emit API) referencing the same dependencies as your main application.
 
 By default, the dependency manifest contains information about the application's target framework and runtime dependencies. Set the PreserveCompilationContext project property to `true` to additionally include information about reference assemblies used during compilation.</PackageDescription>
@@ -22,7 +22,7 @@ By default, the dependency manifest contains information about the application's
   <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'">
     <Compile Remove="**\*.netstandard.cs" />
   </ItemGroup>
-  
+
   <ItemGroup Condition="'$(TargetFrameworkIdentifier)' != '.NETCoreApp'">
     <Compile Remove="**\*.netcoreapp.cs" />
     <Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\RequiresAssemblyFilesAttribute.cs" />
@@ -30,10 +30,10 @@ By default, the dependency manifest contains information about the application's
   </ItemGroup>
 
   <ItemGroup>
-    <InternalsVisibleTo Include="Microsoft.Extensions.DependencyModel.Tests" /> 
+    <InternalsVisibleTo Include="Microsoft.Extensions.DependencyModel.Tests" />
   </ItemGroup>
 
-  <ItemGroup>
+  <ItemGroup Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">
     <ProjectReference Include="$(LibrariesProjectRoot)System.Text.Encodings.Web\src\System.Text.Encodings.Web.csproj" />
     <ProjectReference Include="$(LibrariesProjectRoot)System.Text.Json\src\System.Text.Json.csproj" />
   </ItemGroup>
@@ -46,5 +46,5 @@ By default, the dependency manifest contains information about the application's
   <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
     <Reference Include="System.Runtime" />
   </ItemGroup>
-  
+
 </Project>
diff --git a/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Microsoft.Extensions.Diagnostics.Abstractions.csproj b/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Microsoft.Extensions.Diagnostics.Abstractions.csproj
index a56170373401ee..69066028e63829 100644
--- a/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Microsoft.Extensions.Diagnostics.Abstractions.csproj
+++ b/src/libraries/Microsoft.Extensions.Diagnostics.Abstractions/src/Microsoft.Extensions.Diagnostics.Abstractions.csproj
@@ -4,6 +4,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <!-- Disabling baseline validation since this is a brand new package.
        Once this package has shipped a stable version, the following line
        should be removed in order to re-enable validation. -->
@@ -31,8 +33,11 @@ Microsoft.Extensions.Diagnostics.Metrics.MetricsOptions</PackageDescription>
     <Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\DynamicallyAccessedMemberTypes.cs" />
   </ItemGroup>
 
-  <ItemGroup>
+  <ItemGroup Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">
     <ProjectReference Include="$(LibrariesProjectRoot)System.Diagnostics.DiagnosticSource\src\System.Diagnostics.DiagnosticSource.csproj" />
+  </ItemGroup>
+
+  <ItemGroup>
     <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.DependencyInjection.Abstractions\src\Microsoft.Extensions.DependencyInjection.Abstractions.csproj" />
     <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Options\src\Microsoft.Extensions.Options.csproj" />
   </ItemGroup>
diff --git a/src/libraries/Microsoft.Extensions.Diagnostics/src/Microsoft.Extensions.Diagnostics.csproj b/src/libraries/Microsoft.Extensions.Diagnostics/src/Microsoft.Extensions.Diagnostics.csproj
index 443137251e6412..c5cbe11dcabd39 100644
--- a/src/libraries/Microsoft.Extensions.Diagnostics/src/Microsoft.Extensions.Diagnostics.csproj
+++ b/src/libraries/Microsoft.Extensions.Diagnostics/src/Microsoft.Extensions.Diagnostics.csproj
@@ -8,6 +8,8 @@
        should be removed in order to re-enable validation. -->
     <DisablePackageBaselineValidation>true</DisablePackageBaselineValidation>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>This package includes the default implementation of IMeterFactory and additional extension methods to easily register it with the Dependency Injection framework.</PackageDescription>
   </PropertyGroup>
 
diff --git a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/Microsoft.Extensions.Hosting.Abstractions.csproj b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/Microsoft.Extensions.Hosting.Abstractions.csproj
index c2a3841ec4902f..790938b691599b 100644
--- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/Microsoft.Extensions.Hosting.Abstractions.csproj
+++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/Microsoft.Extensions.Hosting.Abstractions.csproj
@@ -5,6 +5,8 @@
     <RootNamespace>Microsoft.Extensions.Hosting</RootNamespace>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Hosting and startup abstractions for applications.</PackageDescription>
   </PropertyGroup>
 
diff --git a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj
index 94ee3bbf79c373..434042ad58b334 100644
--- a/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj
+++ b/src/libraries/Microsoft.Extensions.Hosting.Systemd/src/Microsoft.Extensions.Hosting.Systemd.csproj
@@ -5,6 +5,8 @@
     <EnableDefaultItems>true</EnableDefaultItems>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>.NET hosting infrastructure for Systemd Services.</PackageDescription>
   </PropertyGroup>
 
diff --git a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj
index 827ed114b0cf64..58822f2b49a5bd 100644
--- a/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj
+++ b/src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj
@@ -4,6 +4,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.1;netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>.NET hosting infrastructure for Windows Services.</PackageDescription>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
   </PropertyGroup>
diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Microsoft.Extensions.Hosting.csproj b/src/libraries/Microsoft.Extensions.Hosting/src/Microsoft.Extensions.Hosting.csproj
index aac48bc7861490..6d699c5ade7387 100644
--- a/src/libraries/Microsoft.Extensions.Hosting/src/Microsoft.Extensions.Hosting.csproj
+++ b/src/libraries/Microsoft.Extensions.Hosting/src/Microsoft.Extensions.Hosting.csproj
@@ -5,6 +5,8 @@
     <EnableDefaultItems>true</EnableDefaultItems>
     <PackageDescription>Hosting and startup infrastructures for applications.</PackageDescription>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
   </PropertyGroup>
 
   <ItemGroup>
diff --git a/src/libraries/Microsoft.Extensions.Http/src/Microsoft.Extensions.Http.csproj b/src/libraries/Microsoft.Extensions.Http/src/Microsoft.Extensions.Http.csproj
index 598f8974c25935..1e553f65ae93a4 100644
--- a/src/libraries/Microsoft.Extensions.Http/src/Microsoft.Extensions.Http.csproj
+++ b/src/libraries/Microsoft.Extensions.Http/src/Microsoft.Extensions.Http.csproj
@@ -4,6 +4,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>The HttpClient factory is a pattern for configuring and retrieving named HttpClients in a composable way. The HttpClient factory provides extensibility to plug in DelegatingHandlers that address cross-cutting concerns such as service location, load balancing, and reliability. The default HttpClient factory provides built-in diagnostics and logging and manages the lifetimes of connections in a performant way.
 
 Commonly Used Types:
diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj
index 12c30e271e7738..087ad684431f9f 100644
--- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj
+++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/Microsoft.Extensions.Logging.Abstractions.csproj
@@ -40,6 +40,10 @@ Microsoft.Extensions.Logging.Abstractions.NullLogger</PackageDescription>
     <PackageReference Include="System.Memory" Version="$(SystemMemoryVersion)" />
   </ItemGroup>
 
+  <ItemGroup Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">
+    <ProjectReference Include="$(LibrariesProjectRoot)System.Diagnostics.DiagnosticSource\src\System.Diagnostics.DiagnosticSource.csproj" />
+  </ItemGroup>
+
   <ItemGroup>
     <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.DependencyInjection.Abstractions\src\Microsoft.Extensions.DependencyInjection.Abstractions.csproj" />
 
diff --git a/src/libraries/Microsoft.Extensions.Logging.Configuration/src/Microsoft.Extensions.Logging.Configuration.csproj b/src/libraries/Microsoft.Extensions.Logging.Configuration/src/Microsoft.Extensions.Logging.Configuration.csproj
index 820eb7fa062e72..faf13fa8cb3047 100644
--- a/src/libraries/Microsoft.Extensions.Logging.Configuration/src/Microsoft.Extensions.Logging.Configuration.csproj
+++ b/src/libraries/Microsoft.Extensions.Logging.Configuration/src/Microsoft.Extensions.Logging.Configuration.csproj
@@ -8,6 +8,8 @@
     <InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>
     <EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Configuration support for Microsoft.Extensions.Logging.</PackageDescription>
   </PropertyGroup>
 
diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj b/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj
index e83340eb0eae55..877c57a45288cc 100644
--- a/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj
+++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/Microsoft.Extensions.Logging.Console.csproj
@@ -7,6 +7,8 @@
     <DefineConstants>$(DefineConstants);NO_SUPPRESS_GC_TRANSITION</DefineConstants>
     <IncludePlatformAttributes>true</IncludePlatformAttributes>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <Features>$(Features);InterceptorsPreview</Features>
     <!-- TODO: Remove InterceptorsPreview feature after 8.0 RC2 SDK is used for build -->
     <InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Microsoft.Extensions.Configuration.Binder.SourceGeneration</InterceptorsPreviewNamespaces>
@@ -49,6 +51,9 @@
     <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging.Abstractions\src\Microsoft.Extensions.Logging.Abstractions.csproj" />
     <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging.Configuration\src\Microsoft.Extensions.Logging.Configuration.csproj" />
     <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Options\src\Microsoft.Extensions.Options.csproj" />
+  </ItemGroup>
+
+  <ItemGroup Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">
     <ProjectReference Include="$(LibrariesProjectRoot)System.Text.Json\src\System.Text.Json.csproj" />
   </ItemGroup>
 
diff --git a/src/libraries/Microsoft.Extensions.Logging.Debug/src/Microsoft.Extensions.Logging.Debug.csproj b/src/libraries/Microsoft.Extensions.Logging.Debug/src/Microsoft.Extensions.Logging.Debug.csproj
index da5ffceed4231e..b534471c34ab7d 100644
--- a/src/libraries/Microsoft.Extensions.Logging.Debug/src/Microsoft.Extensions.Logging.Debug.csproj
+++ b/src/libraries/Microsoft.Extensions.Logging.Debug/src/Microsoft.Extensions.Logging.Debug.csproj
@@ -4,6 +4,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Debug output logger provider implementation for Microsoft.Extensions.Logging. This logger logs messages to a debugger monitor by writing messages with System.Diagnostics.Debug.WriteLine().</PackageDescription>
   </PropertyGroup>
 
diff --git a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj
index 140fddf49e83b7..38c1909633cd8a 100644
--- a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj
+++ b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/Microsoft.Extensions.Logging.EventLog.csproj
@@ -4,6 +4,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Windows Event Log logger provider implementation for Microsoft.Extensions.Logging.</PackageDescription>
   </PropertyGroup>
 
diff --git a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/Microsoft.Extensions.Logging.EventSource.csproj b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/Microsoft.Extensions.Logging.EventSource.csproj
index 3f4ab0080443cc..57c8653fde3925 100644
--- a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/Microsoft.Extensions.Logging.EventSource.csproj
+++ b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/Microsoft.Extensions.Logging.EventSource.csproj
@@ -5,6 +5,8 @@
     <EnableDefaultItems>true</EnableDefaultItems>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>EventSource/EventListener logger provider implementation for Microsoft.Extensions.Logging.</PackageDescription>
   </PropertyGroup>
 
@@ -29,7 +31,10 @@
     <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging.Abstractions\src\Microsoft.Extensions.Logging.Abstractions.csproj" />
     <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Options\src\Microsoft.Extensions.Options.csproj" />
     <ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Primitives\src\Microsoft.Extensions.Primitives.csproj" />
-    <!-- Application tfms (.NETCoreApp, .NETFramework) need to use the same or higher version of .NETStandard's dependencies. -->
+  </ItemGroup>
+
+  <!-- Application tfms (.NETCoreApp, .NETFramework) need to use the same or higher version of .NETStandard's dependencies. -->
+  <ItemGroup Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">
     <ProjectReference Include="$(LibrariesProjectRoot)System.Text.Json\src\System.Text.Json.csproj" />
   </ItemGroup>
 
diff --git a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/Microsoft.Extensions.Logging.TraceSource.csproj b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/Microsoft.Extensions.Logging.TraceSource.csproj
index 6568c9908c14f2..7d26e0db14499d 100644
--- a/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/Microsoft.Extensions.Logging.TraceSource.csproj
+++ b/src/libraries/Microsoft.Extensions.Logging.TraceSource/src/Microsoft.Extensions.Logging.TraceSource.csproj
@@ -4,6 +4,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>TraceSource logger provider implementation for Microsoft.Extensions.Logging. This logger logs messages to a trace listener by writing messages with System.Diagnostics.TraceSource.TraceEvent().</PackageDescription>
   </PropertyGroup>
 
diff --git a/src/libraries/Microsoft.Extensions.Logging/src/Microsoft.Extensions.Logging.csproj b/src/libraries/Microsoft.Extensions.Logging/src/Microsoft.Extensions.Logging.csproj
index 8501fd465db6e5..fd85f184890eb5 100644
--- a/src/libraries/Microsoft.Extensions.Logging/src/Microsoft.Extensions.Logging.csproj
+++ b/src/libraries/Microsoft.Extensions.Logging/src/Microsoft.Extensions.Logging.csproj
@@ -4,6 +4,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.1;netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <EnableDefaultItems>true</EnableDefaultItems>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Logging infrastructure default implementation for Microsoft.Extensions.Logging.</PackageDescription>
   </PropertyGroup>
 
@@ -27,7 +29,7 @@
   </ItemGroup>
 
   <ItemGroup Condition="'$(TargetFrameworkIdentifier)' != '.NETCoreApp'">
-    <ProjectReference Include="$(LibrariesProjectRoot)System.Diagnostics.DiagnosticSource\src\System.Diagnostics.DiagnosticSource.csproj" /> 
+    <ProjectReference Include="$(LibrariesProjectRoot)System.Diagnostics.DiagnosticSource\src\System.Diagnostics.DiagnosticSource.csproj" />
   </ItemGroup>
 
   <ItemGroup Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'netstandard2.1'))">
diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System.Configuration.ConfigurationManager.csproj b/src/libraries/System.Configuration.ConfigurationManager/src/System.Configuration.ConfigurationManager.csproj
index fbed89bbb19943..775ea60ff588d8 100644
--- a/src/libraries/System.Configuration.ConfigurationManager/src/System.Configuration.ConfigurationManager.csproj
+++ b/src/libraries/System.Configuration.ConfigurationManager/src/System.Configuration.ConfigurationManager.csproj
@@ -7,6 +7,8 @@
     <EnableAOTAnalyzer>false</EnableAOTAnalyzer>
     <IncludeInternalObsoleteAttribute>true</IncludeInternalObsoleteAttribute>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Provides types that support using XML configuration files (app.config). This package exists only to support migrating existing .NET Framework code that already uses System.Configuration. When writing new code, use another configuration system instead, such as Microsoft.Extensions.Configuration.</PackageDescription>
 
     <!-- TODO https://github.com/dotnet/runtime/issues/90400: Annotate for nullable reference types -->
@@ -262,7 +264,7 @@
     <Compile Include="$(CommonPath)System\Obsoletions.cs" Link="Common\System\Obsoletions.cs" />
     <Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\UnconditionalSuppressMessageAttribute.cs" Condition="'$(TargetFrameworkIdentifier)' != '.NETCoreApp'" />
   </ItemGroup>
-  
+
   <ItemGroup Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))">
     <Compile Include="System\Diagnostics\DiagnosticsConfiguration.cs" />
     <Compile Include="System\Diagnostics\FilterElement.cs" />
diff --git a/src/libraries/System.Data.Odbc/src/System.Data.Odbc.csproj b/src/libraries/System.Data.Odbc/src/System.Data.Odbc.csproj
index 356e81f71489f4..a4e1d023274629 100644
--- a/src/libraries/System.Data.Odbc/src/System.Data.Odbc.csproj
+++ b/src/libraries/System.Data.Odbc/src/System.Data.Odbc.csproj
@@ -5,6 +5,8 @@
     <NoWarn>$(NoWarn);CA2249;CA1838</NoWarn>
     <EnableAOTAnalyzer>false</EnableAOTAnalyzer>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Provides a collection of classes used to access an ODBC data source in the managed space
 
 Commonly Used Types:
@@ -161,7 +163,4 @@ System.Data.Odbc.OdbcTransaction</PackageDescription>
     <None Include="DatabaseSetupInstructions.md" />
   </ItemGroup>
 
-  <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'">
-    <ProjectReference Include="$(LibrariesProjectRoot)System.Text.Encoding.CodePages\src\System.Text.Encoding.CodePages.csproj" />
-  </ItemGroup>
 </Project>
diff --git a/src/libraries/System.Data.OleDb/src/System.Data.OleDb.csproj b/src/libraries/System.Data.OleDb/src/System.Data.OleDb.csproj
index bb549009216e33..96acfcbb72f133 100644
--- a/src/libraries/System.Data.OleDb/src/System.Data.OleDb.csproj
+++ b/src/libraries/System.Data.OleDb/src/System.Data.OleDb.csproj
@@ -8,6 +8,8 @@
     <NoWarn>$(NoWarn);SYSLIB0004</NoWarn>
     <EnableAOTAnalyzer>false</EnableAOTAnalyzer>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Provides a collection of classes for OLEDB.
 
 Commonly Used Types:
diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System.Diagnostics.PerformanceCounter.csproj b/src/libraries/System.Diagnostics.PerformanceCounter/src/System.Diagnostics.PerformanceCounter.csproj
index 8f8c2613c20613..c6024f6b92ae0f 100644
--- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System.Diagnostics.PerformanceCounter.csproj
+++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System.Diagnostics.PerformanceCounter.csproj
@@ -3,6 +3,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Provides the System.Diagnostics.PerformanceCounter class, which allows access to Windows performance counters.
 
 Commonly Used Types:
diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj b/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj
index 31119b28425124..518f441dc9d0df 100644
--- a/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj
+++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj
@@ -7,6 +7,8 @@
     <NoWarn>$(NoWarn);IDE0059;IDE0060;CA1822;CA1859</NoWarn>
     <EnableAOTAnalyzer>false</EnableAOTAnalyzer>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <AddNETFrameworkPlaceholderFileToPackage>true</AddNETFrameworkPlaceholderFileToPackage>
     <AddNETFrameworkAssemblyReferenceToPackage>true</AddNETFrameworkAssemblyReferenceToPackage>
     <PackageDescription>Provides uniform access and manipulation of user, computer, and group security principals across the multiple principal stores: Active Directory Domain Services (AD DS), Active Directory Lightweight Directory Services (AD LDS), and Machine SAM (MSAM).</PackageDescription>
diff --git a/src/libraries/System.Memory.Data/src/System.Memory.Data.csproj b/src/libraries/System.Memory.Data/src/System.Memory.Data.csproj
index 639e4a3dfdf4fa..ab32e2805f0b6a 100644
--- a/src/libraries/System.Memory.Data/src/System.Memory.Data.csproj
+++ b/src/libraries/System.Memory.Data/src/System.Memory.Data.csproj
@@ -3,6 +3,8 @@
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>A lightweight abstraction for a payload of bytes. Provides methods for converting between strings, streams, JSON, and bytes.
 
 Commonly Used Types:
@@ -23,8 +25,8 @@ System.BinaryData</PackageDescription>
   <ItemGroup Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net8.0'))">
     <Compile Include="$(CommonPath)System\Threading\Tasks\TaskToAsyncResult.cs" Link="Common\System\Threading\Tasks\TaskToAsyncResult.cs" />
   </ItemGroup>
-  
-  <ItemGroup>
+
+  <ItemGroup Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">
     <ProjectReference Include="$(LibrariesProjectRoot)System.Text.Json\src\System.Text.Json.csproj" />
   </ItemGroup>
 
diff --git a/src/libraries/System.Net.Http.Json/src/System.Net.Http.Json.csproj b/src/libraries/System.Net.Http.Json/src/System.Net.Http.Json.csproj
index 08375656e0598b..dbd3fa7d7ebab7 100644
--- a/src/libraries/System.Net.Http.Json/src/System.Net.Http.Json.csproj
+++ b/src/libraries/System.Net.Http.Json/src/System.Net.Http.Json.csproj
@@ -2,6 +2,8 @@
   <PropertyGroup>
     <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Provides extension methods for System.Net.Http.HttpClient and System.Net.Http.HttpContent that perform automatic serialization and deserialization using System.Text.Json.
 
 Commonly Used Types:
@@ -52,7 +54,7 @@ System.Net.Http.Json.JsonContent</PackageDescription>
     <Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\StringSyntaxAttribute.cs" />
   </ItemGroup>
 
-  <ItemGroup>
+  <ItemGroup Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">
     <ProjectReference Include="$(LibrariesProjectRoot)System.Text.Json\src\System.Text.Json.csproj" />
   </ItemGroup>
 
@@ -60,6 +62,7 @@ System.Net.Http.Json.JsonContent</PackageDescription>
     <Reference Include="System.Net.Http" />
     <Reference Include="System.Net.Primitives" />
     <Reference Include="System.Runtime" />
+    <Reference Include="System.Text.Json" />
   </ItemGroup>
 
   <ItemGroup Condition="'$(TargetFrameworkIdentifier)' != '.NETCoreApp'">
diff --git a/src/libraries/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj b/src/libraries/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj
index d241f17a26486d..5afd6058e7c826 100644
--- a/src/libraries/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj
+++ b/src/libraries/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj
@@ -5,6 +5,8 @@
     <DefaultLanguage>en-US</DefaultLanguage>
     <CLSCompliant>false</CLSCompliant>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>This package provides a low-level .NET (ECMA-335) metadata reader and writer. It's geared for performance and is the ideal choice for building higher-level libraries that intend to provide their own object model, such as compilers. The metadata format is defined by the ECMA-335 - Common Language Infrastructure (CLI) specification.
 
 The System.Reflection.Metadata library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.</PackageDescription>
@@ -251,7 +253,7 @@ The System.Reflection.Metadata library is built-in as part of the shared framewo
     <Compile Include="$(CommonPath)System\Obsoletions.cs" Link="Common\System\Obsoletions.cs" />
   </ItemGroup>
 
-  <ItemGroup>
+  <ItemGroup Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">
     <ProjectReference Include="$(LibrariesProjectRoot)System.Collections.Immutable\src\System.Collections.Immutable.csproj" />
   </ItemGroup>
 
@@ -261,6 +263,7 @@ The System.Reflection.Metadata library is built-in as part of the shared framewo
 
   <ItemGroup Condition="'$(TargetFramework)' == '$(NetCoreAppCurrent)'">
     <Reference Include="System.Collections" />
+    <Reference Include="System.Collections.Immutable" />
     <Reference Include="System.IO.Compression" />
     <Reference Include="System.IO.MemoryMappedFiles" />
     <Reference Include="System.Memory" />
diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System.Reflection.MetadataLoadContext.csproj b/src/libraries/System.Reflection.MetadataLoadContext/src/System.Reflection.MetadataLoadContext.csproj
index 76d07ddacf18dc..111bd36fc19d4d 100644
--- a/src/libraries/System.Reflection.MetadataLoadContext/src/System.Reflection.MetadataLoadContext.csproj
+++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System.Reflection.MetadataLoadContext.csproj
@@ -5,6 +5,8 @@
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <EnableAOTAnalyzer>false</EnableAOTAnalyzer>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Provides read-only reflection on assemblies in an isolated context with support for assemblies that target different processor architectures and runtimes. Using MetadataLoadContext enables you to inspect assemblies without loading them into the main execution context. Assemblies in MetadataLoadContext are treated only as metadata, that is, you can read information about their members, but cannot execute any code contained in them.</PackageDescription>
   </PropertyGroup>
 
@@ -155,8 +157,8 @@
     <Compile Include="$(CoreLibSharedDir)System\Diagnostics\CodeAnalysis\RequiresUnreferencedCodeAttribute.cs" />
   </ItemGroup>
 
-  <ItemGroup>
-    <!-- Application tfms (.NETCoreApp, .NETFramework) need to use the same or higher version of .NETStandard's dependencies. -->
+  <!-- Application tfms (.NETCoreApp, .NETFramework) need to use the same or higher version of .NETStandard's dependencies. -->
+  <ItemGroup Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">
     <ProjectReference Include="$(LibrariesProjectRoot)System.Collections.Immutable\src\System.Collections.Immutable.csproj" />
     <ProjectReference Include="$(LibrariesProjectRoot)System.Reflection.Metadata\src\System.Reflection.Metadata.csproj" />
   </ItemGroup>
diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System.Security.Cryptography.Pkcs.csproj b/src/libraries/System.Security.Cryptography.Pkcs/src/System.Security.Cryptography.Pkcs.csproj
index 4988c8cc6a0e99..04b16db1929601 100644
--- a/src/libraries/System.Security.Cryptography.Pkcs/src/System.Security.Cryptography.Pkcs.csproj
+++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System.Security.Cryptography.Pkcs.csproj
@@ -6,6 +6,8 @@
     <IncludeDllSafeSearchPathAttribute>true</IncludeDllSafeSearchPathAttribute>
     <NoWarn>$(NoWarn);CA5384</NoWarn>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Provides support for PKCS and CMS algorithms.
 
 Commonly Used Types:
@@ -650,7 +652,7 @@ System.Security.Cryptography.Pkcs.EnvelopedCms</PackageDescription>
     <None Include="@(AsnXml)" />
   </ItemGroup>
 
-  <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'">
+  <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true' and '$(TargetFramework)' != '$(NetCoreAppCurrent)'">
     <ProjectReference Include="$(LibrariesProjectRoot)System.Formats.Asn1\src\System.Formats.Asn1.csproj" />
   </ItemGroup>
 
diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj b/src/libraries/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj
index 398bd5ad04ef4b..381297c2a4b799 100644
--- a/src/libraries/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj
+++ b/src/libraries/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj
@@ -4,8 +4,8 @@
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <NoWarn>$(NoWarn);CA1850</NoWarn> <!-- CA1850 suppressed due to multitargeting -->
     <IsPackable>true</IsPackable>
-    <GeneratePackageOnBuild>false</GeneratePackageOnBuild>
-    <ServicingVersion>1</ServicingVersion>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>2</ServicingVersion>
     <PackageDescription>Provides classes to support the creation and validation of XML digital signatures. The classes in this namespace implement the World Wide Web Consortium Recommendation, "XML-Signature Syntax and Processing", described at http://www.w3.org/TR/xmldsig-core/.
 
 Commonly Used Types:
diff --git a/src/libraries/System.ServiceProcess.ServiceController/src/System.ServiceProcess.ServiceController.csproj b/src/libraries/System.ServiceProcess.ServiceController/src/System.ServiceProcess.ServiceController.csproj
index fec4052c5c0374..9406ea37a3b6ec 100644
--- a/src/libraries/System.ServiceProcess.ServiceController/src/System.ServiceProcess.ServiceController.csproj
+++ b/src/libraries/System.ServiceProcess.ServiceController/src/System.ServiceProcess.ServiceController.csproj
@@ -4,6 +4,8 @@
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <NoWarn>$(NoWarn);CA2249</NoWarn>
     <IsPackable>true</IsPackable>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Provides the System.ServiceProcess.ServiceController class, which allows you to connect to a Windows service, manipulate it, or get information about it.
 
 Commonly Used Types:
diff --git a/src/libraries/System.Text.Json/src/System.Text.Json.csproj b/src/libraries/System.Text.Json/src/System.Text.Json.csproj
index 7e73fd3b12a50b..45ceafbf34daf9 100644
--- a/src/libraries/System.Text.Json/src/System.Text.Json.csproj
+++ b/src/libraries/System.Text.Json/src/System.Text.Json.csproj
@@ -8,8 +8,8 @@
     <NoWarn>CS8969</NoWarn>
     <IncludeInternalObsoleteAttribute>true</IncludeInternalObsoleteAttribute>
     <IsPackable>true</IsPackable>
-    <GeneratePackageOnBuild>false</GeneratePackageOnBuild>
-    <ServicingVersion>4</ServicingVersion>
+    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <ServicingVersion>5</ServicingVersion>
     <PackageDescription>Provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.
 
 The System.Text.Json library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.</PackageDescription>
@@ -381,7 +381,7 @@ The System.Text.Json library is built-in as part of the shared framework in .NET
   </ItemGroup>
 
   <!-- Application tfms (.NETCoreApp, .NETFramework) need to use the same or higher version of .NETStandard's dependencies. -->
-  <ItemGroup>
+  <ItemGroup Condition="'$(TargetFramework)' != '$(NetCoreAppCurrent)'">
     <ProjectReference Include="$(LibrariesProjectRoot)System.Text.Encodings.Web\src\System.Text.Encodings.Web.csproj" />
   </ItemGroup>
 
@@ -398,6 +398,7 @@ The System.Text.Json library is built-in as part of the shared framework in .NET
     <Reference Include="System.Runtime.Intrinsics" />
     <Reference Include="System.Runtime.Loader" />
     <Reference Include="System.Text.Encoding.Extensions" />
+    <Reference Include="System.Text.Encodings.Web" />
     <Reference Include="System.Threading" />
   </ItemGroup>
 

From e2e089c92e73bb01aeb46d1a56770ca4b4d6fdc3 Mon Sep 17 00:00:00 2001
From: Steve Harter <steveharter@users.noreply.github.com>
Date: Thu, 5 Sep 2024 15:57:50 -0500
Subject: [PATCH 15/21] [release/8.0] ComponentModel threading fixes (#107353)

---
 ...System.ComponentModel.TypeConverter.csproj |  1 +
 .../ComponentModel/PropertyDescriptor.cs      | 35 +++++++----
 .../ReflectTypeDescriptionProvider.cs         | 62 +++++++------------
 .../System/ComponentModel/TypeDescriptor.cs   | 58 ++++++++++-------
 .../tests/PropertyDescriptorTests.cs          | 38 +++++++++---
 5 files changed, 107 insertions(+), 87 deletions(-)

diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System.ComponentModel.TypeConverter.csproj b/src/libraries/System.ComponentModel.TypeConverter/src/System.ComponentModel.TypeConverter.csproj
index f8b998c751ef22..fd01b2a1614a4f 100644
--- a/src/libraries/System.ComponentModel.TypeConverter/src/System.ComponentModel.TypeConverter.csproj
+++ b/src/libraries/System.ComponentModel.TypeConverter/src/System.ComponentModel.TypeConverter.csproj
@@ -253,6 +253,7 @@
                       SetTargetFramework="TargetFramework=netstandard2.0"
                       OutputItemType="Analyzer" />
     <Reference Include="System.Collections" />
+    <Reference Include="System.Collections.Concurrent" />
     <Reference Include="System.Collections.NonGeneric" />
     <Reference Include="System.Collections.Specialized" />
     <Reference Include="System.ComponentModel" />
diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs
index 51fad8dd06d90c..90db74959d1572 100644
--- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs
+++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs
@@ -2,9 +2,11 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 
 using System.Collections;
+using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Diagnostics.CodeAnalysis;
 using System.Reflection;
+using System.Threading;
 
 namespace System.ComponentModel
 {
@@ -16,10 +18,11 @@ public abstract class PropertyDescriptor : MemberDescriptor
         internal const string PropertyDescriptorPropertyTypeMessage = "PropertyDescriptor's PropertyType cannot be statically discovered.";
 
         private TypeConverter? _converter;
-        private Dictionary<object, EventHandler?>? _valueChangedHandlers;
+        private ConcurrentDictionary<object, EventHandler?>? _valueChangedHandlers;
         private object?[]? _editors;
         private Type[]? _editorTypes;
         private int _editorCount;
+        private object? _syncObject;
 
         /// <summary>
         /// Initializes a new instance of the <see cref='System.ComponentModel.PropertyDescriptor'/> class with the specified name and
@@ -49,6 +52,8 @@ protected PropertyDescriptor(MemberDescriptor descr, Attribute[]? attrs) : base(
         {
         }
 
+        private object SyncObject => LazyInitializer.EnsureInitialized(ref _syncObject);
+
         /// <summary>
         /// When overridden in a derived class, gets the type of the
         /// component this property is bound to.
@@ -124,10 +129,11 @@ public virtual void AddValueChanged(object component, EventHandler handler)
             ArgumentNullException.ThrowIfNull(component);
             ArgumentNullException.ThrowIfNull(handler);
 
-            _valueChangedHandlers ??= new Dictionary<object, EventHandler?>();
-
-            EventHandler? h = _valueChangedHandlers.GetValueOrDefault(component, defaultValue: null);
-            _valueChangedHandlers[component] = (EventHandler?)Delegate.Combine(h, handler);
+            lock (SyncObject)
+            {
+                _valueChangedHandlers ??= new ConcurrentDictionary<object, EventHandler?>(concurrencyLevel: 1, capacity: 0);
+                _valueChangedHandlers.AddOrUpdate(component, handler, (k, v) => (EventHandler?)Delegate.Combine(v, handler));
+            }
         }
 
         /// <summary>
@@ -392,15 +398,18 @@ public virtual void RemoveValueChanged(object component, EventHandler handler)
 
             if (_valueChangedHandlers != null)
             {
-                EventHandler? h = _valueChangedHandlers.GetValueOrDefault(component, defaultValue: null);
-                h = (EventHandler?)Delegate.Remove(h, handler);
-                if (h != null)
-                {
-                    _valueChangedHandlers[component] = h;
-                }
-                else
+                lock (SyncObject)
                 {
-                    _valueChangedHandlers.Remove(component);
+                    EventHandler? h = _valueChangedHandlers.GetValueOrDefault(component, defaultValue: null);
+                    h = (EventHandler?)Delegate.Remove(h, handler);
+                    if (h != null)
+                    {
+                        _valueChangedHandlers[component] = h;
+                    }
+                    else
+                    {
+                        _valueChangedHandlers.Remove(component, out EventHandler? _);
+                    }
                 }
             }
         }
diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs
index aa29c8173e72bc..7c9870b579d8d7 100644
--- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs
+++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs
@@ -3,6 +3,7 @@
 
 using System.Collections;
 using System.Collections.Generic;
+using System.Collections.Concurrent;
 using System.ComponentModel.Design;
 using System.Diagnostics;
 using System.Diagnostics.CodeAnalysis;
@@ -22,10 +23,8 @@ namespace System.ComponentModel
     /// </summary>
     internal sealed partial class ReflectTypeDescriptionProvider : TypeDescriptionProvider
     {
-        // Hastable of Type -> ReflectedTypeData. ReflectedTypeData contains all
-        // of the type information we have gathered for a given type.
-        //
-        private Hashtable? _typeData;
+        // ReflectedTypeData contains all of the type information we have gathered for a given type.
+        private readonly ConcurrentDictionary<Type, ReflectedTypeData> _typeData = new ConcurrentDictionary<Type, ReflectedTypeData>();
 
         // This is the signature we look for when creating types that are generic, but
         // want to know what type they are dealing with. Enums are a good example of this;
@@ -91,8 +90,6 @@ private static Type[] InitializeSkipInterfaceAttributeList()
 
         internal static Guid ExtenderProviderKey { get; } = Guid.NewGuid();
 
-
-        private static readonly object s_internalSyncObject = new object();
         /// <summary>
         /// Creates a new ReflectTypeDescriptionProvider. The type is the
         /// type we will obtain type information for.
@@ -243,7 +240,7 @@ internal static void AddEditorTable(Type editorBaseType, Hashtable table)
 
             Debug.Assert(table != null, "COMPAT: Editor table should not be null"); // don't throw; RTM didn't so we can't do it either.
 
-            lock (s_internalSyncObject)
+            lock (TypeDescriptor.s_commonSyncObject)
             {
                 Hashtable editorTables = EditorTables;
                 if (!editorTables.ContainsKey(editorBaseType))
@@ -298,7 +295,6 @@ internal static void AddEditorTable(Type editorBaseType, Hashtable table)
             return obj ?? Activator.CreateInstance(objectType, args);
         }
 
-
         /// <summary>
         /// Helper method to create editors and type converters. This checks to see if the
         /// type implements a Type constructor, and if it does it invokes that ctor.
@@ -429,7 +425,7 @@ internal TypeConverter GetConverter([DynamicallyAccessedMembers(DynamicallyAcces
                 //
                 if (table == null)
                 {
-                    lock (s_internalSyncObject)
+                    lock (TypeDescriptor.s_commonSyncObject)
                     {
                         table = editorTables[editorBaseType];
                         if (table == null)
@@ -837,22 +833,11 @@ internal Type[] GetPopulatedTypes(Module module)
         {
             List<Type> typeList = new List<Type>();
 
-            lock (s_internalSyncObject)
+            foreach (KeyValuePair<Type, ReflectedTypeData> kvp in _typeData)
             {
-                Hashtable? typeData = _typeData;
-                if (typeData != null)
+                if (kvp.Key.Module == module && kvp.Value!.IsPopulated)
                 {
-                    // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
-                    IDictionaryEnumerator e = typeData.GetEnumerator();
-                    while (e.MoveNext())
-                    {
-                        DictionaryEntry de = e.Entry;
-                        Type type = (Type)de.Key;
-                        if (type.Module == module && ((ReflectedTypeData)de.Value!).IsPopulated)
-                        {
-                            typeList.Add(type);
-                        }
-                    }
+                    typeList.Add(kvp.Key);
                 }
             }
 
@@ -897,28 +882,23 @@ public override Type GetReflectionType(
         /// </summary>
         private ReflectedTypeData? GetTypeData([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, bool createIfNeeded)
         {
-            ReflectedTypeData? td = null;
-
-            if (_typeData != null)
+            if (_typeData.TryGetValue(type, out ReflectedTypeData? td))
             {
-                td = (ReflectedTypeData?)_typeData[type];
-                if (td != null)
-                {
-                    return td;
-                }
+                Debug.Assert(td != null);
+                return td;
             }
 
-            lock (s_internalSyncObject)
+            lock (TypeDescriptor.s_commonSyncObject)
             {
-                if (_typeData != null)
+                if (_typeData.TryGetValue(type, out td))
                 {
-                    td = (ReflectedTypeData?)_typeData[type];
+                    Debug.Assert(td != null);
+                    return td;
                 }
 
-                if (td == null && createIfNeeded)
+                if (createIfNeeded)
                 {
                     td = new ReflectedTypeData(type);
-                    _typeData ??= new Hashtable();
                     _typeData[type] = td;
                 }
             }
@@ -1006,7 +986,7 @@ internal static Attribute[] ReflectGetAttributes(Type type)
                 return attrs;
             }
 
-            lock (s_internalSyncObject)
+            lock (TypeDescriptor.s_commonSyncObject)
             {
                 attrs = (Attribute[]?)attributeCache[type];
                 if (attrs == null)
@@ -1034,7 +1014,7 @@ internal static Attribute[] ReflectGetAttributes(MemberInfo member)
                 return attrs;
             }
 
-            lock (s_internalSyncObject)
+            lock (TypeDescriptor.s_commonSyncObject)
             {
                 attrs = (Attribute[]?)attributeCache[member];
                 if (attrs == null)
@@ -1063,7 +1043,7 @@ private static EventDescriptor[] ReflectGetEvents(
                 return events;
             }
 
-            lock (s_internalSyncObject)
+            lock (TypeDescriptor.s_commonSyncObject)
             {
                 events = (EventDescriptor[]?)eventCache[type];
                 if (events == null)
@@ -1160,7 +1140,7 @@ private static PropertyDescriptor[] ReflectGetExtendedProperties(IExtenderProvid
             ReflectPropertyDescriptor[]? extendedProperties = (ReflectPropertyDescriptor[]?)extendedPropertyCache[providerType];
             if (extendedProperties == null)
             {
-                lock (s_internalSyncObject)
+                lock (TypeDescriptor.s_commonSyncObject)
                 {
                     extendedProperties = (ReflectPropertyDescriptor[]?)extendedPropertyCache[providerType];
 
@@ -1240,7 +1220,7 @@ private static PropertyDescriptor[] ReflectGetProperties(
                 return properties;
             }
 
-            lock (s_internalSyncObject)
+            lock (TypeDescriptor.s_commonSyncObject)
             {
                 properties = (PropertyDescriptor[]?)propertyCache[type];
 
diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs
index 948e3f4b386f35..c9ef20510aa1e3 100644
--- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs
+++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 
 using System.Collections;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
 using System.Collections.Specialized;
 using System.ComponentModel.Design;
 using System.Diagnostics;
@@ -26,12 +28,23 @@ public sealed class TypeDescriptor
         // lock on it for thread safety. It is used from nearly
         // every call to this class, so it will be created soon after
         // class load anyway.
-        private static readonly WeakHashtable s_providerTable = new WeakHashtable();     // mapping of type or object hash to a provider list
-        private static readonly Hashtable s_providerTypeTable = new Hashtable();         // A direct mapping from type to provider.
+        private static readonly WeakHashtable s_providerTable = new WeakHashtable();
+
+        // This lock object protects access to several thread-unsafe areas below, and is a single lock object to prevent deadlocks.
+        // - During s_providerTypeTable access.
+        // - To act as a mutex for CheckDefaultProvider() when it needs to create the default provider, which may re-enter the above case.
+        // - For cache access in the ReflectTypeDescriptionProvider class which may re-enter the above case.
+        // - For logic added by consumers, such as custom provider, constructor and property logic, which may re-enter the above cases in unexpected ways.
+        internal static readonly object s_commonSyncObject = new object();
+
+        // A direct mapping from type to provider.
+        private static readonly ConcurrentDictionary<Type, TypeDescriptionNode> s_providerTypeTable = new ConcurrentDictionary<Type, TypeDescriptionNode>();
+
+        // Tracks DefaultTypeDescriptionProviderAttributes.
+        // A value of `null` indicates initialization is in progress.
+        // A value of s_initializedDefaultProvider indicates the provider is initialized.
+        private static readonly ConcurrentDictionary<Type, object?> s_defaultProviderInitialized = new ConcurrentDictionary<Type, object?>();
 
-        private static readonly Hashtable s_defaultProviderInitialized = new Hashtable(); // A table of type -> object to track DefaultTypeDescriptionProviderAttributes.
-                                                                                          // A value of `null` indicates initialization is in progress.
-                                                                                          // A value of s_initializedDefaultProvider indicates the provider is initialized.
         private static readonly object s_initializedDefaultProvider = new object();
 
         private static WeakHashtable? s_associationTable;
@@ -179,7 +192,7 @@ public static void AddProvider(TypeDescriptionProvider provider, Type type)
             ArgumentNullException.ThrowIfNull(provider);
             ArgumentNullException.ThrowIfNull(type);
 
-            lock (s_providerTable)
+            lock (s_commonSyncObject)
             {
                 // Get the root node, hook it up, and stuff it back into
                 // the provider cache.
@@ -209,7 +222,7 @@ public static void AddProvider(TypeDescriptionProvider provider, object instance
 
             // Get the root node, hook it up, and stuff it back into
             // the provider cache.
-            lock (s_providerTable)
+            lock (s_commonSyncObject)
             {
                 refreshNeeded = s_providerTable.ContainsKey(instance);
                 TypeDescriptionNode node = NodeFor(instance, true);
@@ -265,15 +278,12 @@ public static void AddProviderTransparent(TypeDescriptionProvider provider, obje
         /// </summary>
         private static void CheckDefaultProvider(Type type)
         {
-            if (s_defaultProviderInitialized[type] == s_initializedDefaultProvider)
+            if (s_defaultProviderInitialized.TryGetValue(type, out object? provider) && provider == s_initializedDefaultProvider)
             {
                 return;
             }
 
-            // Lock on s_providerTable even though s_providerTable is not modified here.
-            // Using a single lock prevents deadlocks since other methods that call into or are called
-            // by this method also lock on s_providerTable and the ordering of the locks may be different.
-            lock (s_providerTable)
+            lock (s_commonSyncObject)
             {
                 AddDefaultProvider(type);
             }
@@ -281,7 +291,7 @@ private static void CheckDefaultProvider(Type type)
 
         /// <summary>
         /// Add the default provider, if it exists.
-        /// For threading, this is always called under a 'lock (s_providerTable)'.
+        /// For threading, this is always called under a 'lock (s_commonSyncObject)'.
         /// </summary>
         private static void AddDefaultProvider(Type type)
         {
@@ -295,7 +305,7 @@ private static void AddDefaultProvider(Type type)
 
             // Immediately set this to null to indicate we are in progress setting the default provider for a type.
             // This prevents re-entrance to this method.
-            s_defaultProviderInitialized[type] = null;
+            s_defaultProviderInitialized.TryAdd(type, null);
 
             // Always use core reflection when checking for the default provider attribute.
             // If there is a provider, we probably don't want to build up our own cache state against the type.
@@ -1475,8 +1485,10 @@ private static TypeDescriptionNode NodeFor(Type type, bool createDelegator)
 
             while (node == null)
             {
-                node = (TypeDescriptionNode?)s_providerTypeTable[searchType] ??
-                       (TypeDescriptionNode?)s_providerTable[searchType];
+                if (!s_providerTypeTable.TryGetValue(searchType, out node))
+                {
+                    node = (TypeDescriptionNode?)s_providerTable[searchType];
+                }
 
                 if (node == null)
                 {
@@ -1484,7 +1496,7 @@ private static TypeDescriptionNode NodeFor(Type type, bool createDelegator)
 
                     if (searchType == typeof(object) || baseType == null)
                     {
-                        lock (s_providerTable)
+                        lock (s_commonSyncObject)
                         {
                             node = (TypeDescriptionNode?)s_providerTable[searchType];
 
@@ -1500,9 +1512,9 @@ private static TypeDescriptionNode NodeFor(Type type, bool createDelegator)
                     else if (createDelegator)
                     {
                         node = new TypeDescriptionNode(new DelegatingTypeDescriptionProvider(baseType));
-                        lock (s_providerTable)
+                        lock (s_commonSyncObject)
                         {
-                            s_providerTypeTable[searchType] = node;
+                            s_providerTypeTable.TryAdd(searchType, node);
                         }
                     }
                     else
@@ -1603,7 +1615,7 @@ private static TypeDescriptionNode NodeFor(object instance, bool createDelegator
         /// </summary>
         private static void NodeRemove(object key, TypeDescriptionProvider provider)
         {
-            lock (s_providerTable)
+            lock (s_commonSyncObject)
             {
                 TypeDescriptionNode? head = (TypeDescriptionNode?)s_providerTable[key];
                 TypeDescriptionNode? target = head;
@@ -2124,7 +2136,7 @@ private static void Refresh(object component, bool refreshReflectionProvider)
             {
                 Type type = component.GetType();
 
-                lock (s_providerTable)
+                lock (s_commonSyncObject)
                 {
                     // ReflectTypeDescritionProvider is only bound to object, but we
                     // need go to through the entire table to try to find custom
@@ -2208,7 +2220,7 @@ public static void Refresh(Type type)
 
             bool found = false;
 
-            lock (s_providerTable)
+            lock (s_commonSyncObject)
             {
                 // ReflectTypeDescritionProvider is only bound to object, but we
                 // need go to through the entire table to try to find custom
@@ -2273,7 +2285,7 @@ public static void Refresh(Module module)
             // each of these levels.
             Hashtable? refreshedTypes = null;
 
-            lock (s_providerTable)
+            lock (s_commonSyncObject)
             {
                 // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
                 IDictionaryEnumerator e = s_providerTable.GetEnumerator();
diff --git a/src/libraries/System.ComponentModel.TypeConverter/tests/PropertyDescriptorTests.cs b/src/libraries/System.ComponentModel.TypeConverter/tests/PropertyDescriptorTests.cs
index f791d46824f829..4786d3966a7e18 100644
--- a/src/libraries/System.ComponentModel.TypeConverter/tests/PropertyDescriptorTests.cs
+++ b/src/libraries/System.ComponentModel.TypeConverter/tests/PropertyDescriptorTests.cs
@@ -28,13 +28,21 @@ public void RaiseAddedValueChangedHandler()
             var component = new DescriptorTestComponent();
             var properties = TypeDescriptor.GetProperties(component.GetType());
             PropertyDescriptor propertyDescriptor = properties.Find(nameof(component.Property), false);
-            var handlerWasCalled = false;
-            EventHandler valueChangedHandler = (_, __) => handlerWasCalled = true;
+            int handlerCalledCount = 0;
 
-            propertyDescriptor.AddValueChanged(component, valueChangedHandler);
-            propertyDescriptor.SetValue(component, int.MaxValue);
+            EventHandler valueChangedHandler1 = (_, __) => handlerCalledCount++;
+            EventHandler valueChangedHandler2 = (_, __) => handlerCalledCount++;
+
+            propertyDescriptor.AddValueChanged(component, valueChangedHandler1);
+
+            // Add case.
+            propertyDescriptor.SetValue(component, int.MaxValue); // Add to delegate.
+            Assert.Equal(1, handlerCalledCount);
 
-            Assert.True(handlerWasCalled);
+
+            propertyDescriptor.AddValueChanged(component, valueChangedHandler2);
+            propertyDescriptor.SetValue(component, int.MaxValue);  // Update delegate.
+            Assert.Equal(3, handlerCalledCount);
         }
 
         [Fact]
@@ -42,15 +50,25 @@ public void RemoveAddedValueChangedHandler()
         {
             var component = new DescriptorTestComponent();
             var properties = TypeDescriptor.GetProperties(component.GetType());
-            var handlerWasCalled = false;
-            EventHandler valueChangedHandler = (_, __) => handlerWasCalled = true;
+            int handlerCalledCount = 0;
+
+            EventHandler valueChangedHandler1 = (_, __) => handlerCalledCount++;
+            EventHandler valueChangedHandler2 = (_, __) => handlerCalledCount++;
+
             PropertyDescriptor propertyDescriptor = properties.Find(nameof(component.Property), false);
 
-            propertyDescriptor.AddValueChanged(component, valueChangedHandler);
-            propertyDescriptor.RemoveValueChanged(component, valueChangedHandler);
+            propertyDescriptor.AddValueChanged(component, valueChangedHandler1);
+            propertyDescriptor.AddValueChanged(component, valueChangedHandler2);
+            propertyDescriptor.SetValue(component, int.MaxValue);
+            Assert.Equal(2, handlerCalledCount);
+
             propertyDescriptor.SetValue(component, int.MaxValue);
+            Assert.Equal(4, handlerCalledCount);
 
-            Assert.False(handlerWasCalled);
+            propertyDescriptor.RemoveValueChanged(component, valueChangedHandler1);
+            propertyDescriptor.RemoveValueChanged(component, valueChangedHandler2);
+            propertyDescriptor.SetValue(component, int.MaxValue);
+            Assert.Equal(4, handlerCalledCount);
         }
 
         [Fact]

From 423fd78cffccba8fbfb2116c383b0711850d29b5 Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
 <41898282+github-actions[bot]@users.noreply.github.com>
Date: Mon, 9 Sep 2024 13:46:09 +0200
Subject: [PATCH 16/21] [release/8.0-staging] [Mono AOT] Fix error when
 returning zero sized struct (#107198)

* Fix error when returning zero sized struct

* Add test

* Fix x64 errors

---------

Co-authored-by: Jeremi Kurdek <jkurdek@gmail.com>
---
 src/mono/mono/mini/mini-llvm.c                | 11 +++++--
 .../JitBlue/Runtime_103628/Runtime_103628.cs  | 29 +++++++++++++++++++
 .../Runtime_103628/Runtime_103628.csproj      |  8 +++++
 3 files changed, 46 insertions(+), 2 deletions(-)
 create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_103628/Runtime_103628.cs
 create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_103628/Runtime_103628.csproj

diff --git a/src/mono/mono/mini/mini-llvm.c b/src/mono/mono/mini/mini-llvm.c
index 657bb23d5cf63d..668b2c2ed53e12 100644
--- a/src/mono/mono/mini/mini-llvm.c
+++ b/src/mono/mono/mini/mini-llvm.c
@@ -1557,7 +1557,7 @@ sig_to_llvm_sig_full (EmitContext *ctx, MonoMethodSignature *sig, LLVMCallInfo *
 			ret_type = LLVMStructType (members, 1, FALSE);
 		} else if (cinfo->ret.pair_storage [0] == LLVMArgNone && cinfo->ret.pair_storage [1] == LLVMArgNone) {
 			/* Empty struct */
-			ret_type = LLVMVoidType ();
+			ret_type = LLVMStructType (NULL, 0, FALSE);
 		} else if (cinfo->ret.pair_storage [0] == LLVMArgInIReg && cinfo->ret.pair_storage [1] == LLVMArgInIReg) {
 			LLVMTypeRef members [2];
 
@@ -1574,7 +1574,11 @@ sig_to_llvm_sig_full (EmitContext *ctx, MonoMethodSignature *sig, LLVMCallInfo *
 	case LLVMArgVtypeAsScalar: {
 		int size = mono_class_value_size (mono_class_from_mono_type_internal (rtype), NULL);
 		/* LLVM models this by returning an int */
-		if (size < TARGET_SIZEOF_VOID_P) {
+		if (size == 0) {
+			/* Empty struct with LayoutKind attribute and without specified size */
+			g_assert(cinfo->ret.nslots == 0);
+			ret_type = LLVMIntType (8);
+		} else if (size < TARGET_SIZEOF_VOID_P) {
 			g_assert (cinfo->ret.nslots == 1);
 			ret_type = LLVMIntType (size * 8);
 		} else {
@@ -4806,6 +4810,9 @@ process_call (EmitContext *ctx, MonoBasicBlock *bb, LLVMBuilderRef *builder_ref,
 			/* Empty struct */
 			break;
 
+		if (LLVMTypeOf (lcall) == LLVMStructType (NULL, 0, FALSE))
+			break;
+
 		if (!addresses [ins->dreg])
 			addresses [ins->dreg] = build_alloca_address (ctx, sig->ret);
 
diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_103628/Runtime_103628.cs b/src/tests/JIT/Regression/JitBlue/Runtime_103628/Runtime_103628.cs
new file mode 100644
index 00000000000000..ef904b9699168a
--- /dev/null
+++ b/src/tests/JIT/Regression/JitBlue/Runtime_103628/Runtime_103628.cs
@@ -0,0 +1,29 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System.Runtime.InteropServices;
+using Xunit;
+
+[StructLayout(LayoutKind.Sequential)]
+public struct S1
+{
+}
+
+[StructLayout(LayoutKind.Auto)]
+public struct S2
+{
+}
+
+public class Runtime_103628
+{
+    public static S1 Get_S1() => new S1();
+
+    public static S2 Get_S2() => new S2();
+
+    [Fact]
+    public static void TestEntryPoint()
+    {
+        S1 s1 = Get_S1();
+        S2 s2 = Get_S2();
+    }
+}
diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_103628/Runtime_103628.csproj b/src/tests/JIT/Regression/JitBlue/Runtime_103628/Runtime_103628.csproj
new file mode 100644
index 00000000000000..de6d5e08882e86
--- /dev/null
+++ b/src/tests/JIT/Regression/JitBlue/Runtime_103628/Runtime_103628.csproj
@@ -0,0 +1,8 @@
+<Project Sdk="Microsoft.NET.Sdk">
+  <PropertyGroup>
+    <Optimize>True</Optimize>
+  </PropertyGroup>
+  <ItemGroup>
+    <Compile Include="$(MSBuildProjectName).cs" />
+  </ItemGroup>
+</Project>

From 88d07e4f7120a7b15581b90327f339ba90c42b50 Mon Sep 17 00:00:00 2001
From: Matous Kozak <55735845+matouskozak@users.noreply.github.com>
Date: Mon, 9 Sep 2024 20:49:15 +0200
Subject: [PATCH 17/21] [mono][infra] fix typo in Android helix queue name
 (#107023)

---
 eng/pipelines/coreclr/templates/helix-queues-setup.yml | 2 +-
 eng/pipelines/libraries/helix-queues-setup.yml         | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/eng/pipelines/coreclr/templates/helix-queues-setup.yml b/eng/pipelines/coreclr/templates/helix-queues-setup.yml
index 8f1d99396b4633..7d7acb772f82b4 100644
--- a/eng/pipelines/coreclr/templates/helix-queues-setup.yml
+++ b/eng/pipelines/coreclr/templates/helix-queues-setup.yml
@@ -48,7 +48,7 @@ jobs:
 
     # Android x64
     - ${{ if in(parameters.platform, 'android_x64') }}:
-      - Ubuntu.2004.Amd64.Android.29.Open
+      - Ubuntu.2204.Amd64.Android.29.Open
 
     # Browser wasm
     - ${{ if eq(parameters.platform, 'browser_wasm') }}:
diff --git a/eng/pipelines/libraries/helix-queues-setup.yml b/eng/pipelines/libraries/helix-queues-setup.yml
index 755a6d4ceb8ff8..f2a7c9622eaaf5 100644
--- a/eng/pipelines/libraries/helix-queues-setup.yml
+++ b/eng/pipelines/libraries/helix-queues-setup.yml
@@ -100,7 +100,7 @@ jobs:
 
     # Android
     - ${{ if in(parameters.platform, 'android_x86', 'android_x64', 'linux_bionic_x64') }}:
-      - Ubuntu.2004.Amd64.Android.29.Open
+      - Ubuntu.2204.Amd64.Android.29.Open
     - ${{ if in(parameters.platform, 'android_arm', 'android_arm64', 'linux_bionic_arm64') }}:
       - Windows.11.Amd64.Android.Open
 

From bcb0c09086898d944bbdca82bcb1a20207693877 Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
 <41898282+github-actions[bot]@users.noreply.github.com>
Date: Mon, 9 Sep 2024 22:56:52 +0200
Subject: [PATCH 18/21] Fix hardware exception context extraction on Rosetta
 (#107199)

The recently added AVX support in hardware exception handling path on macOS x64
has introduced a problem when running under Rosetta.
When we extract the floating point part of the context of the failing thread,
the thread can have AVX or AVX512 active, or none of these. The code accidentally
leaves CONTEXT_XSTATE set on the context even when no AVX was enabled on the thread.

Rosetta doesn't support AVX, so having CONTEXT_XSTATE set in the context flags
can lead to later call to RtlRestoreContext attempting to set ymm registers using
instructions that Rosetta cannot emulate and the app crashes due to that.

This doesn't happen in .NET 9, since we always clear the CONTEXT_XSTATE before
exception handling stack unwinding. But in .NET 8, this causes stack overflow
under Rosetta, since the attemt to execute the ymm instruction triggers the
hardware exception handling again and again.

Co-authored-by: Jan Vorlicek <janvorli@microsoft.com>
---
 src/coreclr/pal/src/thread/context.cpp | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/src/coreclr/pal/src/thread/context.cpp b/src/coreclr/pal/src/thread/context.cpp
index b7e7c6fab35f05..e15f482e4c42fe 100644
--- a/src/coreclr/pal/src/thread/context.cpp
+++ b/src/coreclr/pal/src/thread/context.cpp
@@ -1496,6 +1496,12 @@ CONTEXT_GetThreadContextFromThreadState(
 
                 // AMD64's FLOATING_POINT includes the xmm registers.
                 memcpy(&lpContext->Xmm0, &pState->__fpu_xmm0, 16 * 16);
+
+                if (threadStateFlavor == x86_FLOAT_STATE64)
+                {
+                     // There was just a floating point state, so make sure the CONTEXT_XSTATE is not set
+                     lpContext->ContextFlags &= ~(CONTEXT_XSTATE & CONTEXT_AREA_MASK);
+                }
             }
             break;
         }

From fe7898a0ba5d3fc91a2913399bc026b1a470316d Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
 <41898282+github-actions[bot]@users.noreply.github.com>
Date: Mon, 9 Sep 2024 14:03:02 -0700
Subject: [PATCH 19/21] Ensure that integer parsing correctly handles non-zero
 fractional data (#106701)

Co-authored-by: Tanner Gooding <tagoo@outlook.com>
---
 .../src/System/Number.Parsing.cs              |  2 +-
 .../System.Runtime/tests/System/Int32Tests.cs | 40 +++++++++++++++++++
 2 files changed, 41 insertions(+), 1 deletion(-)

diff --git a/src/libraries/System.Private.CoreLib/src/System/Number.Parsing.cs b/src/libraries/System.Private.CoreLib/src/System/Number.Parsing.cs
index 77164243594258..2aefc7c407685d 100644
--- a/src/libraries/System.Private.CoreLib/src/System/Number.Parsing.cs
+++ b/src/libraries/System.Private.CoreLib/src/System/Number.Parsing.cs
@@ -107,7 +107,7 @@ private static unsafe bool TryNumberBufferToBinaryInteger<TInteger>(ref NumberBu
 
             int i = number.Scale;
 
-            if ((i > TInteger.MaxDigitCount) || (i < number.DigitsCount) || (!TInteger.IsSigned && number.IsNegative))
+            if ((i > TInteger.MaxDigitCount) || (i < number.DigitsCount) || (!TInteger.IsSigned && number.IsNegative) || number.HasNonZeroTail)
             {
                 return false;
             }
diff --git a/src/libraries/System.Runtime/tests/System/Int32Tests.cs b/src/libraries/System.Runtime/tests/System/Int32Tests.cs
index 0b5f7c8250efe3..4d0dec7e37200f 100644
--- a/src/libraries/System.Runtime/tests/System/Int32Tests.cs
+++ b/src/libraries/System.Runtime/tests/System/Int32Tests.cs
@@ -663,6 +663,46 @@ public static IEnumerable<object[]> Parse_Invalid_TestData()
             yield return new object[] { "2147483649-", NumberStyles.AllowTrailingSign, null, typeof(OverflowException) };
             yield return new object[] { "(2147483649)", NumberStyles.AllowParentheses, null, typeof(OverflowException) };
             yield return new object[] { "2E10", NumberStyles.AllowExponent, null, typeof(OverflowException) };
+
+            // Test trailing non zeros
+
+            yield return new object[] { "-9223372036854775808.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "-2147483648.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "-32768.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "-128.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "127.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "255.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "32767.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "65535.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "2147483647.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "4294967295.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "9223372036854775807.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "18446744073709551615.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+
+            yield return new object[] { "-9223372036854775808.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "-2147483648.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "-32768.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "-128.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "127.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "255.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "32767.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "65535.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "2147483647.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "4294967295.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "9223372036854775807.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "18446744073709551615.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+
+            yield return new object[] { "3.001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "3.000000001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "3.0000000001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "3.00000000001", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+
+            yield return new object[] { "3.100", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "3.100000000", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "3.1000000000", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+            yield return new object[] { "3.10000000000", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
+
+            yield return new object[] { "2147483646.1", NumberStyles.Number, CultureInfo.InvariantCulture, typeof(OverflowException) };
         }
 
         [Theory]

From f34e9ac55aa658af77c616b9e7267c92bfdc9e44 Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
 <41898282+github-actions[bot]@users.noreply.github.com>
Date: Mon, 9 Sep 2024 16:25:44 -0600
Subject: [PATCH 20/21] Fix infinite loop in genAddrMode (#106767)

Co-authored-by: EgorBo <egorbo@gmail.com>
---
 src/coreclr/jit/codegencommon.cpp             |  3 +-
 .../JitBlue/Runtime_106607/Runtime_106607.il  | 40 +++++++++++++++++++
 .../Runtime_106607/Runtime_106607.ilproj      |  9 +++++
 3 files changed, 50 insertions(+), 2 deletions(-)
 create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_106607/Runtime_106607.il
 create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_106607/Runtime_106607.ilproj

diff --git a/src/coreclr/jit/codegencommon.cpp b/src/coreclr/jit/codegencommon.cpp
index c6892747e0548d..f39596c1329df2 100644
--- a/src/coreclr/jit/codegencommon.cpp
+++ b/src/coreclr/jit/codegencommon.cpp
@@ -1289,9 +1289,8 @@ bool CodeGen::genCreateAddrMode(
                 {
                     cns += addConst->IconValue();
                     op2 = op2->AsOp()->gtOp1;
+                    goto AGAIN;
                 }
-
-                goto AGAIN;
             }
             break;
 
diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_106607/Runtime_106607.il b/src/tests/JIT/Regression/JitBlue/Runtime_106607/Runtime_106607.il
new file mode 100644
index 00000000000000..8eba69b7303605
--- /dev/null
+++ b/src/tests/JIT/Regression/JitBlue/Runtime_106607/Runtime_106607.il
@@ -0,0 +1,40 @@
+// 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 extern xunit.core { }
+.assembly Runtime_106607 { }
+
+.class Runtime_106607 extends [System.Runtime]System.Object
+{
+  .method public static int32 Main() nooptimization
+  {
+    .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = (
+        01 00 00 00
+    )
+    .entrypoint
+    .maxstack 8
+    .locals init ([0] int32 num)
+
+    ldc.i4       42
+    stloc.0
+    ldloc.0
+    ldc.i4       1620763441
+    ldc.i4       1453536392
+    add
+    add
+    ldloc.0
+    ldloc.0 
+    sub
+    ldc.i4       152872638
+    ldc.i4.s     31
+    and
+    shl
+    add
+    call  void [System.Console]System.Console::WriteLine(int32)
+
+    ldc.i4 100
+    ret
+  }
+}
diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_106607/Runtime_106607.ilproj b/src/tests/JIT/Regression/JitBlue/Runtime_106607/Runtime_106607.ilproj
new file mode 100644
index 00000000000000..4b3a54c1abb8a4
--- /dev/null
+++ b/src/tests/JIT/Regression/JitBlue/Runtime_106607/Runtime_106607.ilproj
@@ -0,0 +1,9 @@
+<Project Sdk="Microsoft.NET.Sdk.IL">
+  <PropertyGroup>
+    <DebugType>None</DebugType>
+    <Optimize>True</Optimize>
+  </PropertyGroup>
+  <ItemGroup>
+    <Compile Include="$(MSBuildProjectName).il" />
+  </ItemGroup>
+</Project>

From 2ecd5b5c6936ed988bdfe3304c5e23105b5253de Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Carlos=20S=C3=A1nchez=20L=C3=B3pez?=
 <1175054+carlossanlop@users.noreply.github.com>
Date: Mon, 9 Sep 2024 15:43:48 -0700
Subject: [PATCH 21/21] Reset OOB package that was built in the September
 Release but was not enabled again for the October release.

---
 .../src/System.Diagnostics.EventLog.csproj                      | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/libraries/System.Diagnostics.EventLog/src/System.Diagnostics.EventLog.csproj b/src/libraries/System.Diagnostics.EventLog/src/System.Diagnostics.EventLog.csproj
index 5bf9cee3c8725a..32185c679f3d1d 100644
--- a/src/libraries/System.Diagnostics.EventLog/src/System.Diagnostics.EventLog.csproj
+++ b/src/libraries/System.Diagnostics.EventLog/src/System.Diagnostics.EventLog.csproj
@@ -3,7 +3,7 @@
     <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <IsPackable>true</IsPackable>
-    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
+    <GeneratePackageOnBuild>false</GeneratePackageOnBuild>
     <ServicingVersion>1</ServicingVersion>
     <PackageDescription>Provides the System.Diagnostics.EventLog class, which allows the applications to use the Windows event log service.
 
