-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Fix generic virtual dispatch hang after multiple AssemblyLoadContext unloads #132859
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Copilot
wants to merge
4
commits into
main
Choose a base branch
from
copilot/fix-assemblyloadcontext-hang
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
c04a1be
Fix GenericCache flush sentinel detection and add regression test
Copilot 4e6307d
Compare table length with SENTINEL_TABLE_SIZE + 1 in IsSentinel
Copilot bcd9195
Use SENTINEL_TABLE_SIZE/IsSentinel in CastCache for consistency
Copilot 6cc1605
Potential fix for pull request finding
VSadov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
96 changes: 96 additions & 0 deletions
96
src/tests/Loader/CollectibleAssemblies/GenericVirtualMethod/GenericVirtualMethod.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.IO; | ||
| using System.Reflection; | ||
| using System.Runtime.CompilerServices; | ||
| using System.Runtime.Loader; | ||
| using Xunit; | ||
| using TestLibrary; | ||
|
|
||
| // Repeatedly loads an assembly into a collectible AssemblyLoadContext, invokes a generic | ||
| // virtual method on a type from that assembly and unloads the context. | ||
| // The results of the generic virtual dispatch are stored in a process-wide cache, which is | ||
| // flushed when a collectible context is unloaded. If the flush does not take effect, a stale | ||
| // entry could be returned for a new type that happens to reuse the addresses of an unloaded | ||
| // one, which results in a hang or a crash. | ||
| public class GenericVirtualMethodUnloading | ||
| { | ||
| private class TestALC : AssemblyLoadContext | ||
| { | ||
| public TestALC(int id) : base($"GenericVirtualMethod{id}", isCollectible: true) | ||
| { | ||
| } | ||
| } | ||
|
|
||
| [ActiveIssue("https://github.com/dotnet/runtimelab/issues/155: Collectible assemblies", typeof(Utilities), nameof(Utilities.IsNativeAot))] | ||
| [ActiveIssue("https://github.com/dotnet/runtime/issues/34072", TestRuntimes.Mono)] | ||
| [Fact] | ||
| public static void CallGenericVirtualMethodAcrossUnloads() | ||
| { | ||
| string payloadPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "GenericVirtualMethodUnloaded.dll"); | ||
|
|
||
| for (int iteration = 0; iteration < 10; iteration++) | ||
| { | ||
| WeakReference context = InvokeAndUnload(payloadPath, iteration); | ||
| for (int collection = 0; context.IsAlive && collection < 10; collection++) | ||
| { | ||
| GC.Collect(); | ||
| GC.WaitForPendingFinalizers(); | ||
| } | ||
|
|
||
| Assert.False(context.IsAlive, $"Context {iteration} did not unload."); | ||
| VerifyVirtualDispatchCacheIsEmpty(); | ||
| } | ||
| } | ||
|
|
||
| [MethodImpl(MethodImplOptions.NoInlining)] | ||
| private static WeakReference InvokeAndUnload(string payloadPath, int iteration) | ||
| { | ||
| TestALC alc = new TestALC(iteration); | ||
| WeakReference weakAlc = new WeakReference(alc, trackResurrection: false); | ||
|
|
||
| Assembly payload = alc.LoadFromAssemblyPath(payloadPath); | ||
| Type machineType = payload.GetType("DerivedMachine", throwOnError: true); | ||
| Type stateType = payload.GetType("MarkerState", throwOnError: true); | ||
| Type baseType = payload.GetType("Machine", throwOnError: true); | ||
|
|
||
| object machine = Activator.CreateInstance(machineType)!; | ||
| MethodInfo change = baseType.GetMethod("Change")!.MakeGenericMethod(stateType); | ||
|
|
||
| TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => change.Invoke(machine, null)); | ||
| Assert.NotNull(ex.InnerException); | ||
| Assert.Equal("ExpectedException", ex.InnerException!.GetType().FullName); | ||
|
|
||
| alc.Unload(); | ||
| return weakAlc; | ||
| } | ||
|
|
||
| // Unloading a collectible context flushes the virtual function pointer cache, so that | ||
| // targets belonging to the unloaded context cannot be returned by a later lookup. | ||
| // Check that the cache is indeed empty after the unload. | ||
| private static void VerifyVirtualDispatchCacheIsEmpty() | ||
| { | ||
| Type helpersType = typeof(object).Assembly.GetType("System.Runtime.CompilerServices.VirtualDispatchHelpers"); | ||
| if (helpersType == null) | ||
| { | ||
| // The cache is specific to CoreCLR. | ||
| return; | ||
| } | ||
|
|
||
| object cache = helpersType.GetField("s_virtualFunctionPointerCache", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); | ||
| Array table = (Array)cache.GetType().GetField("_table", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(cache); | ||
|
|
||
| FieldInfo infoField = table.GetType().GetElementType().GetField("_info", BindingFlags.NonPublic | BindingFlags.Instance); | ||
| FieldInfo versionField = infoField.FieldType.GetField("_version", BindingFlags.NonPublic | BindingFlags.Instance); | ||
|
|
||
|
VSadov marked this conversation as resolved.
|
||
| // element 0 of the table holds the auxiliary data of the table, the entries start at index 1. | ||
| // A nonzero version means the entry is in use. | ||
| for (int i = 1; i < table.Length; i++) | ||
| { | ||
| object entryInfo = infoField.GetValue(table.GetValue(i)); | ||
| Assert.Equal(0u, (uint)versionField.GetValue(entryInfo)); | ||
| } | ||
| } | ||
| } | ||
13 changes: 13 additions & 0 deletions
13
src/tests/Loader/CollectibleAssemblies/GenericVirtualMethod/GenericVirtualMethod.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
| <PropertyGroup> | ||
| <!-- Needed for GC.WaitForPendingFinalizers and to exercise the process-wide cache in isolation --> | ||
| <RequiresProcessIsolation>true</RequiresProcessIsolation> | ||
| </PropertyGroup> | ||
| <ItemGroup> | ||
| <ProjectReference Include="GenericVirtualMethodUnloaded.csproj" /> | ||
| <Compile Include="GenericVirtualMethod.cs" /> | ||
| </ItemGroup> | ||
| <ItemGroup> | ||
| <ProjectReference Include="$(TestLibraryProjectPath)" /> | ||
| </ItemGroup> | ||
| </Project> |
43 changes: 43 additions & 0 deletions
43
src/tests/Loader/CollectibleAssemblies/GenericVirtualMethod/GenericVirtualMethodUnloaded.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
|
|
||
| public class State; | ||
| public sealed class MarkerState : State; | ||
| public sealed class ExpectedException : Exception; | ||
|
|
||
| public abstract class Machine | ||
| { | ||
| private readonly Dictionary<Type, State> _states = new(); | ||
|
|
||
| public void Change<T>() where T : State | ||
| { | ||
| _ = GetOrCreate<T>(); | ||
| } | ||
|
|
||
| private T GetOrCreate<T>() where T : State | ||
| { | ||
| if (!_states.TryGetValue(typeof(T), out State state)) | ||
| { | ||
| state = Construct<T>(); | ||
| _states[typeof(T)] = state; | ||
| } | ||
|
|
||
| return (T)state; | ||
| } | ||
|
|
||
| protected virtual T Construct<T>() where T : State | ||
| { | ||
| return Activator.CreateInstance<T>(); | ||
| } | ||
| } | ||
|
|
||
| public sealed class DerivedMachine : Machine | ||
| { | ||
| protected override T Construct<T>() | ||
| { | ||
| throw new ExpectedException(); | ||
| } | ||
| } |
11 changes: 11 additions & 0 deletions
11
...sts/Loader/CollectibleAssemblies/GenericVirtualMethod/GenericVirtualMethodUnloaded.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
| <PropertyGroup> | ||
| <OutputType>Library</OutputType> | ||
| </PropertyGroup> | ||
| <ItemGroup> | ||
| <Compile Include="GenericVirtualMethodUnloaded.cs" /> | ||
| </ItemGroup> | ||
| <ItemGroup> | ||
| <ProjectReference Include="$(TestLibraryProjectPath)" /> | ||
| </ItemGroup> | ||
| </Project> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.