Repository navigation
Keep DispatchProxy from implementing the wrong copy of an interface across load contexts - #137207
caraioniurie47 wants to merge 4 commits into
Conversation
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]>
|
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. |
|
Tagging subscribers to this area: @steveisok, @dotnet/area-system-reflection |
| @@ -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; | |||
There was a problem hiding this comment.
This sounds like a bug in Mono. Instead of this, it would be better to disable the affected tests on Mono
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 givesProxyAssemblyboth ALCs and makes itRunAndCollectwhen 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
AssemblyBuilderwhen 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?
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]>
Code that calls
DispatchProxy.Createfor an interface whose assembly is loaded into two customAssemblyLoadContexts, 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>()throwsInvalidCastException, andDispatchProxy.Create(Type, Type)returns an object that is not an instance of the requested interface.DispatchProxykeeps oneAssemblyBuilderper 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 oneAssemblyBuilderper 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():New tests, each run with both
Createoverloads, 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.Createstill throwsNotSupportedException. I can open a separate issue for this.Performance. A warm
Createwith both types in the default ALC, BenchmarkDotNet, mean (StdDev), base runs before and after the fix runs:Create<IFoo, FooProxy>()Create(typeof(IFoo), typeof(FooProxy))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_AssemblyLoadContextsused an earlier version of that test.