diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/FieldOpCodeHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/FieldOpCodeHandler.cs index 8bd2f853..41b5ae7c 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/FieldOpCodeHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/FieldOpCodeHandler.cs @@ -1,4 +1,5 @@ using AsmResolver.DotNet; +using AsmResolver.DotNet.Signatures; using AsmResolver.PE.DotNet.Cil; namespace Echo.Platforms.AsmResolver.Emulation.Dispatch.ObjectModel; @@ -16,7 +17,9 @@ public CilDispatchResult Dispatch(CilExecutionContext context, CilInstruction in // Ensure the enclosing type is initialized in the runtime. if (field.DeclaringType is { } declaringType) { - var initResult = context.Machine.TypeManager.HandleInitialization(context.Thread, declaringType); + var genericContext = GenericContext.FromMember(context.CurrentFrame.Method); + var instantiated = declaringType.ToTypeSignature().InstantiateGenericTypes(genericContext); + var initResult = context.Machine.TypeManager.HandleInitialization(context.Thread, instantiated); if (!initResult.IsNoAction) return initResult.ToDispatchResult(); } diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Runtime/RuntimeTypeManager.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Runtime/RuntimeTypeManager.cs index be24a519..fbc4d7d5 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Runtime/RuntimeTypeManager.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Runtime/RuntimeTypeManager.cs @@ -104,10 +104,10 @@ public TypeInitializerResult HandleInitialization(CilThread thread, ITypeDescrip initialization.Exception = _machine.Heap .AllocateObject(_machine.ValueFactory.TypeInitializationExceptionType, true) .AsObjectHandle(_machine); - + return TypeInitializerResult.Exception(initialization.Exception); } - + // "Call" the constructor. initialization.ConstructorCalled = true; @@ -115,7 +115,18 @@ public TypeInitializerResult HandleInitialization(CilThread thread, ITypeDescrip var cctor = definition.GetStaticConstructor(); if (cctor is not null) { - thread.CallStack.Push(cctor); + var result = (IMethodDescriptor) cctor; + + // Instantiate any args in the declaring type. + var context = GenericContext.FromType(type); + if (type.ToTypeSignature() is {} typeSignature) + { + var newType = typeSignature.InstantiateGenericTypes(context); + if (newType != typeSignature) + result = newType.ToTypeDefOrRef().CreateMemberReference(cctor.Name!, cctor.Signature!); + } + + thread.CallStack.Push(result); return TypeInitializerResult.Redirected(); }