Open cc004 opened 2 years ago
This happens when assembly MonoMod.Utils
is loaded in a collectible AssemblyLoadContext
which prevents the non-collectible MonoMod.Utils.Cil.ILGeneratorProxy
to be loaded.
Potential fix is to load MonoMod.Utils.Cil.ILGeneratorProxy
in the same AssemblyLoadContext
as MonoMod.Utils
. This line should look like this (simplified, in reality we will need to use reflection on older target frameworks):
var utilsAssembly = Assembly.GetExecutingAssembly();
var context = AssemblyLoadContext.GetLoadContext(utilsAssembly);
asm = context.LoadFromStream(copy);
Without this fix it is a bug which got patched in the .NET Runtime 7 and now throws the exception OP posted.
I'm honestly not sure supporting MonoMod being loaded in a collectible ALC is a good idea. In fact, I'm fairly certain that it is a terrible idea. MonoMod relies on being able to root objects in statics, and must be able to keep detours alive and correct. If the runtime were to unload it, that could (in fact, would) leave detours in invalid states and be liable to inducing runtime crashes.
If we did want to support it, the only safe support we can have is allocating a GC handle to some MonoMod object as long as there are references in the DynamicReferenceManager
. This should effectively root all relevant MonoMod types, preventing them from being collected. This does also defeat the purpose of unloadable ALCs though.
I do think it's a good idea to load our dynamically generated assemblies in the same ALC that created them though. That would require some more work than just the proposed change however.
stacktrace