Skip to content

Keep DispatchProxy from implementing the wrong copy of an interface across load contexts - #137207

Open
caraioniurie47 wants to merge 4 commits into
dotnet:mainfrom
caraioniurie47:issue-109398
Open

caraioniurie47 wants to merge 4 commits into
dotnet:mainfrom
caraioniurie47:issue-109398

Conversation

@caraioniurie47

@caraioniurie47 caraioniurie47 commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Code that calls DispatchProxy.Create for an interface whose assembly is loaded into two custom AssemblyLoadContexts, with the base proxy type in the default ALC, gets a second proxy that implements the wrong copy of the interface: DispatchProxy.Create<T, TProxy>() throws InvalidCastException, and DispatchProxy.Create(Type, Type) returns an object that is not an instance of the requested interface. DispatchProxy keeps one AssemblyBuilder per ALC of the base type, and a dynamic module keeps the first assembly it associated with an assembly reference (#62234), so the second proxy binds the first copy.

The fix uses the key proposed in the issue discussion: the AssemblyBuilders are grouped by the base type's ALC and then by the interface type's ALC. When both types come from the same ALC, there is still one AssemblyBuilder per ALC.

With the base type's ALC as the outer key, a collectible ALC that holds a proxy base type can also be collected after it is dropped without calling Unload(). On the unchanged code, with the interface in the default ALC or the collectible ALC, the base type was still alive after 50 GC rounds.

Not chosen; with each, a collectible ALC holding a proxy base type is not collected after it is dropped without calling Unload():

  • The interface's ALC as the outer key: when the interface comes from the default ALC.
  • Caching proxy types outside the interface-ALC grouping: in every case the new unloadability test covers.
  • Skipping the interface-ALC grouping for an interface from the base type's own ALC: when the interface comes from that ALC.

New tests, each run with both Create overloads, fail on the unchanged code:

  • Test_Interface_From_Multiple_AssemblyLoadContexts: each proxy implements its own copy of the interface.
  • Test_Unloadability_Collects_Proxy_Base_Type: the base type in a dropped collectible ALC is collected.

Not changed: with the base type in the default ALC and the interface in a collectible ALC, DispatchProxy.Create still throws NotSupportedException. I can open a separate issue for this.

Performance. A warm Create with both types in the default ALC, BenchmarkDotNet, mean (StdDev), base runs before and after the fix runs:

Method Base Fix
Create<IFoo, FooProxy>() 261.3 ns (3.27), 266.6 ns (11.73) 280.2 ns (3.94), 281.1 ns (1.24)
Create(typeof(IFoo), typeof(FooProxy)) 252.5 ns (3.11), 242.9 ns (3.57) 274.5 ns (4.92), 274.9 ns (5.75)

Allocations are unchanged (280 B).

Resolves #109398

Note

AI-generated, written at my direction and reviewed by me before posting.
Verified with CoreCLR on Windows x64 (the whole test project, the 50-round result, the benchmark). A Linux x64 run of Test_Interface_From_Multiple_AssemblyLoadContexts used an earlier version of that test.

DispatchProxyGenerator kept one AssemblyBuilder per AssemblyLoadContext
of the base proxy type. A dynamic module resolves an assembly name to
the first assembly it referenced with that name, so when the same
interface assembly was loaded into two custom ALCs and the base proxy
type lived in a third (e.g. the default ALC), the second proxy
implemented the copy of the interface that the module referenced first
and could not be cast to its own.

Group the AssemblyBuilders by the base type's ALC and then by the
interface type's ALC, using a ConditionalWeakTable nested in the
existing one. With the base type's ALC as the outer key, a collectible
ALC holding a proxy base type can now be collected once it is dropped
without calling Unload().

Fix dotnet#109398

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 9, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @steveisok, @dotnet/area-system-reflection
See info in area-owners.md if you want to be subscribed.

@@ -71,7 +74,13 @@ internal static object CreateProxyInstance(
AssemblyLoadContext? alc = AssemblyLoadContext.GetLoadContext(baseType.Assembly);
Debug.Assert(alc != null);

ProxyAssembly proxyAssembly = s_alcProxyAssemblyMap.GetOrAdd(alc, static x => new ProxyAssembly(x));
// An assembly can have no load context, such as a Reflection.Emit assembly on Mono;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sounds like a bug in Mono. Instead of this, it would be better to disable the affected tests on Mono

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 89572d1: the fallback is gone, and Invoke_Event_Add_And_Remove_And_Raise_Invokes_Correct_Methods_Generic_And_Non_Generic_Tests now skips on Mono, the one test that passes a Reflection.Emit interface.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CI on the merge with main failed Invoke_Method_With_Optional_Custom_Modifier_Invokes_Correct_Method on Mono (the interfaceAlc != null assert on the Debug legs, ArgumentNullException on browser-wasm). #135567 added it after this branch's base, and it also builds its interface with AssemblyBuilder, so "the one test" above held only for this branch. b6e58c1 merges main, and 438d5ec skips that test on Mono too.

AssemblyLoadContext.GetLoadContext returns null for a Reflection.Emit
assembly on Mono, so assert the interface's load context as for the
base type's instead of falling back to it, and skip the test that
passes a Reflection.Emit interface on Mono.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

ProxyAssembly proxyAssembly = s_alcProxyAssemblyMap
.GetOrAdd(alc, static _ => new ConditionalWeakTable<AssemblyLoadContext, ProxyAssembly>())
.GetOrAdd(interfaceAlc, static (_, x) => new ProxyAssembly(x), alc);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this solve all cases of the Proxy and Interface coming from different ALC? If the Proxy and the Interface come from two completely unrelated ALCs (and neither is present in the main ALC), is the ProxyAssembly going to be able to reference the Interface?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, unless the interface's ALC is collectible and the base type's is not (first case below): a Reflection.Emit module binds an assembly reference to the first Assembly associated with it, not by name through an ALC (commodule.cpp:102-109):

            // Don't cache if there is assembly associated with the token already. The assembly ref resolution
            // can be ambiguous because of reflection emit does not require unique assembly names.
            // We always let the first association win. Ideally, we would disallow this situation by throwing
            // exception, but that would be a breaking change.
            if(pModule->LookupAssemblyRef(tkResolution) == NULL)
            {
                pModule->ForceStoreAssemblyRef(tkResolution, pRefedAssembly);
            }

On CoreCLR, an app loading the base type and the interface into two custom ALCs, neither in the default ALC, got working proxies of public and internal interfaces with neither ALC collectible, both, or only the base type's.

It doesn't solve all cases. The issue, opened by someone else, reports one case, so I kept the cases below out of this PR and planned the first of them and the Unload() limit at the end as follow-up issues and PRs. Two cases I found still fail on CoreCLR, on the unchanged code too:

  • Base type's ALC non-collectible, interface's collectible (this includes the description's "Not changed" case): NotSupportedException: A non-collectible assembly may not reference a collectible assembly. The fix I have in mind gives ProxyAssembly both ALCs and makes it RunAndCollect when either is collectible, which needs the interface-ALC level this PR adds.
  • Two same-named assemblies under one key: for a generic interface instantiated over a type whose assembly is loaded in two ALCs, the second proxy implements the first instantiation. The key holds only the interface definition's ALC, and the first association above wins (TypeBuilder creates a type derived from the wrong base type in presence of multiple ALCs #62234). A fix would key by assembly identity or start a new AssemblyBuilder when an assembly name clashes; I haven't designed one.

One more limit, in the same cache: on CoreCLR, a collectible ALC holding a proxy's base type and interface is still not unloaded after Unload(); this PR lets it be collected only when it is dropped without calling Unload(). A fix would remove the cache entry on the ALC's Unloading event.

I can open issues for the first case and the Unload() limit and follow up with PRs, or should either go into this PR? And for later PRs: should related cases found while fixing an issue go into the PR that fixes it, or be listed in its description, as "Not changed" does here for one?

caraioniurie47 and others added 2 commits November 10, 2026 22:15
Its interface comes from a Reflection.Emit assembly, for which Mono's
AssemblyLoadContext.GetLoadContext returns null.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Reflection community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DispatchProxy generates a proxy type implementing the interface from the wrong ALC

2 participants