diff --git a/Directory.Build.props b/Directory.Build.props index 4be686d4..92e2d14e 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -6,7 +6,7 @@ https://github.com/Washi1337/Echo/LICENSE.md https://github.com/Washi1337/Echo git - 12 + 14 enable 1.0.0 alpha.1 diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Echo.Platforms.AsmResolver.csproj b/src/Platforms/Echo.Platforms.AsmResolver/Echo.Platforms.AsmResolver.csproj index 16aec40e..1d837109 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Echo.Platforms.AsmResolver.csproj +++ b/src/Platforms/Echo.Platforms.AsmResolver/Echo.Platforms.AsmResolver.csproj @@ -22,7 +22,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/CilVirtualMachine.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/CilVirtualMachine.cs index 80417b82..b0941951 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/CilVirtualMachine.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/CilVirtualMachine.cs @@ -35,12 +35,12 @@ public class CilVirtualMachine /// /// The main module to base the context on. /// Indicates whether the virtual machine runs in 32-bit mode or 64-bit mode. - public CilVirtualMachine(ModuleDefinition contextModule, bool is32Bit) + public CilVirtualMachine(RuntimeContext runtimeContext, bool is32Bit) { Memory = new VirtualMemory(is32Bit ? uint.MaxValue : long.MaxValue); Loader = new PELoader(Memory); - ValueFactory = new ValueFactory(contextModule, is32Bit); + ValueFactory = new ValueFactory(runtimeContext, is32Bit); HostObjects = new ObjectMapMemory(0x1000_0000, o => new HostObject(o, this)); ObjectMarshaller = new ObjectMarshaller(this); @@ -114,11 +114,8 @@ public ValueFactory ValueFactory get; } - /// - /// Gets the main module the emulator is executing instructions for. - /// - public ModuleDefinition ContextModule => ValueFactory.ContextModule; - + public RuntimeContext RuntimeContext => ValueFactory.RuntimeContext; + /// /// Gets the service that is responsible for mapping executable files in memory. /// diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/CliMarshaller.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/CliMarshaller.cs index 0d7a9941..0c9ce854 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/CliMarshaller.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/CliMarshaller.cs @@ -31,8 +31,7 @@ private TypeSignature GetElementType(TypeSignature type) case ElementType.ValueType: if (!_resolvedTypes.TryGetValue(type, out var definition)) { - definition = type.Resolve(); - if (definition is not null) + if (type.TryResolve(_valueFactory.RuntimeContext, out definition)) _resolvedTypes.Add(type, definition); } diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/LdElemHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/LdElemHandler.cs index 0cec281f..61cec420 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/LdElemHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/LdElemHandler.cs @@ -93,10 +93,10 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex private static TypeSignature GetElementType(CilExecutionContext context, CilInstruction instruction) { - var factory = context.Machine.ValueFactory.ContextModule.CorLibTypeFactory; + var factory = context.Machine.ValueFactory.CorLibTypeFactory; return instruction.OpCode.Code switch { - CilCode.Ldelem => ((ITypeDefOrRef) instruction.Operand!).ToTypeSignature(), + CilCode.Ldelem => ((ITypeDefOrRef) instruction.Operand!).ToTypeSignature(context.Machine.RuntimeContext), CilCode.Ldelem_I => factory.IntPtr, CilCode.Ldelem_I1 => factory.SByte, CilCode.Ldelem_I2 => factory.Int16, diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/LdElemaHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/LdElemaHandler.cs index a36d406c..91443d62 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/LdElemaHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/LdElemaHandler.cs @@ -20,7 +20,10 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex var genericContext = GenericContext.FromMethod(context.CurrentFrame.Method); // Determine parameters. - var elementType = ((ITypeDefOrRef) instruction.Operand!).ToTypeSignature().InstantiateGenericTypes(genericContext); + var elementType = ((ITypeDefOrRef) instruction.Operand!) + .ToTypeSignature(context.RuntimeContext) + .InstantiateGenericTypes(genericContext); + var arrayIndex = stack.Pop(); var arrayAddress = stack.Pop(); var result = factory.RentNativeInteger(false); diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/NewArrHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/NewArrHandler.cs index d573c596..042137fe 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/NewArrHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/NewArrHandler.cs @@ -1,7 +1,6 @@ using AsmResolver.DotNet; using AsmResolver.DotNet.Signatures; using AsmResolver.PE.DotNet.Cil; -using Echo.Memory; using Echo.Platforms.AsmResolver.Emulation.Stack; namespace Echo.Platforms.AsmResolver.Emulation.Dispatch.Arrays @@ -19,8 +18,10 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex var factory = context.Machine.ValueFactory; var genericContext = GenericContext.FromMethod(context.CurrentFrame.Method); - var elementType = ((ITypeDefOrRef)instruction.Operand!).ToTypeSignature().InstantiateGenericTypes(genericContext); var elementCount = stack.Pop(); + var elementType = ((ITypeDefOrRef)instruction.Operand!) + .ToTypeSignature(context.RuntimeContext) + .InstantiateGenericTypes(genericContext); try { diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/StElemHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/StElemHandler.cs index 0cf4d40a..71732339 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/StElemHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Arrays/StElemHandler.cs @@ -89,10 +89,10 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex private static TypeSignature GetElementType(CilExecutionContext context, CilInstruction instruction) { - var factory = context.Machine.ValueFactory.ContextModule.CorLibTypeFactory; + var factory = context.Machine.ValueFactory.CorLibTypeFactory; return instruction.OpCode.Code switch { - CilCode.Stelem => ((ITypeDefOrRef) instruction.Operand!).ToTypeSignature(), + CilCode.Stelem => ((ITypeDefOrRef) instruction.Operand!).ToTypeSignature(context.RuntimeContext), CilCode.Stelem_I => factory.IntPtr, CilCode.Stelem_I1 => factory.SByte, CilCode.Stelem_I2 => factory.Int16, diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/CilExecutionContext.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/CilExecutionContext.cs index 8c66e367..c444d2c7 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/CilExecutionContext.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/CilExecutionContext.cs @@ -1,4 +1,5 @@ using System.Threading; +using AsmResolver.DotNet; using Echo.Platforms.AsmResolver.Emulation.Stack; namespace Echo.Platforms.AsmResolver.Emulation.Dispatch @@ -44,5 +45,7 @@ public CancellationToken CancellationToken { get; } + + public RuntimeContext RuntimeContext => Machine.RuntimeContext; } } \ No newline at end of file diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ControlFlow/RetHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ControlFlow/RetHandler.cs index 4b4fc847..b4443bbb 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ControlFlow/RetHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ControlFlow/RetHandler.cs @@ -35,7 +35,7 @@ public CilDispatchResult Dispatch(CilExecutionContext context, CilInstruction in if (index != -1 && body.Instructions[index].OpCode.Code == CilCode.Newobj) { var resultingType = calleeFrame.Method.DeclaringType! - .ToTypeSignature() + .ToTypeSignature(context.RuntimeContext) .InstantiateGenericTypes(genericContext); var slot = CreateResultingStackSlot( diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Misc/ConvHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Misc/ConvHandler.cs index 542215e2..c5c5ca1b 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Misc/ConvHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Misc/ConvHandler.cs @@ -313,7 +313,7 @@ private static (StackSlot Result, Trilean Overflow) HandleKnownFloatConversion( private static TypeSignature GetTargetType(CilExecutionContext context, CilCode code) { - var factory = context.Machine.ContextModule.CorLibTypeFactory; + var factory = context.Machine.ValueFactory.CorLibTypeFactory; return code switch { diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/BoxHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/BoxHandler.cs index 4816a882..f4c93296 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/BoxHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/BoxHandler.cs @@ -15,7 +15,7 @@ public class BoxHandler : FallThroughOpCodeHandler protected override CilDispatchResult DispatchInternal(CilExecutionContext context, CilInstruction instruction) { var genericContext = GenericContext.FromMethod(context.CurrentFrame.Method); - var type = ((ITypeDefOrRef)instruction.Operand!).ToTypeSignature(); + var type = ((ITypeDefOrRef)instruction.Operand!).ToTypeSignature(context.RuntimeContext); type = type.InstantiateGenericTypes(genericContext); diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CallHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CallHandler.cs index 70cce60d..0b421119 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CallHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CallHandler.cs @@ -18,12 +18,11 @@ protected override MethodDevirtualizationResult DevirtualizeMethodInternal( IList arguments) { // If we are constraining on a specific declaring type, we need to simulate a "virtual dispatch" on that type. - if (context.CurrentFrame.ConstrainedType?.Resolve() is { } constrainedType) + if (context.CurrentFrame.ConstrainedType?.TryResolve(context.RuntimeContext, out var constrainedType) is true) { - var resolvedBaseMethod = method.Resolve(); - if (resolvedBaseMethod is { IsVirtual: true }) + if (method.TryResolve(context.RuntimeContext, out var resolvedBaseMethod) && resolvedBaseMethod.IsVirtual) { - var implementationMethod = FindMethodImplementationInType(constrainedType, resolvedBaseMethod); + var implementationMethod = FindMethodImplementationInType(context.RuntimeContext, constrainedType, resolvedBaseMethod); if (implementationMethod is not null) return MethodDevirtualizationResult.Success(implementationMethod); } diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CallHandlerBase.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CallHandlerBase.cs index f2f9f3f0..961bbaf0 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CallHandlerBase.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CallHandlerBase.cs @@ -111,7 +111,7 @@ private static BitVector GetInstancePointer(CilExecutionContext context, IMethod var factory = context.Machine.ValueFactory; var stack = context.CurrentFrame.EvaluationStack; - var declaringType = method.DeclaringType?.ToTypeSignature() ?? factory.ContextModule.CorLibTypeFactory.Object; + var declaringType = method.DeclaringType?.ToTypeSignature(context.RuntimeContext) ?? factory.CorLibTypeFactory.Object; return stack.Pop(declaringType); } @@ -273,7 +273,7 @@ private static CilDispatchResult Invoke(CilExecutionContext context, IMethodDesc /// The type to search in. /// The method to find an implementation for. /// The method, or null if none is found. - protected static MethodDefinition? FindMethodImplementationInType(TypeDefinition? type, MethodDefinition? baseMethod) + protected static MethodDefinition? FindMethodImplementationInType(RuntimeContext context, TypeDefinition? type, MethodDefinition? baseMethod) { if (type is null || baseMethod is null || !baseMethod.IsVirtual) return baseMethod; @@ -290,15 +290,15 @@ private static CilDispatchResult Invoke(CilExecutionContext context, IMethodDesc if (baseMethod.IsStatic) { // Static base methods can only be implemented through explicit interface implementation. - implementation = TryFindExplicitInterfaceImplementationInType(type, baseMethod); + implementation = TryFindExplicitInterfaceImplementationInType(context, type, baseMethod); } else { // Prioritize interface implementations. if (declaringType.IsInterface) { - implementation = TryFindExplicitInterfaceImplementationInType(type, baseMethod) - ?? TryFindImplicitInterfaceImplementationInType(type, baseMethod); + implementation = TryFindExplicitInterfaceImplementationInType(context, type, baseMethod) + ?? TryFindImplicitInterfaceImplementationInType(context, type, baseMethod); } // Try to find other implicit implementations. @@ -309,7 +309,10 @@ private static CilDispatchResult Invoke(CilExecutionContext context, IMethodDesc break; // Move up type hierarchy tree. - type = type.BaseType?.Resolve(); + if (type.BaseType is null) + break; + + type.BaseType.TryResolve(context, out type); } // If there's no override, just use the base implementation (if available). @@ -334,13 +337,13 @@ private static CilDispatchResult Invoke(CilExecutionContext context, IMethodDesc return null; } - private static MethodDefinition? TryFindImplicitInterfaceImplementationInType(TypeDefinition type, MethodDefinition baseMethod) + private static MethodDefinition? TryFindImplicitInterfaceImplementationInType(RuntimeContext context, TypeDefinition type, MethodDefinition baseMethod) { // Find the correct interface implementation and instantiate any generics. MethodSignature? baseMethodSig = null; foreach (var interfaceImpl in type.Interfaces) { - if (SignatureComparer.Default.Equals(interfaceImpl.Interface?.ToTypeSignature().GetUnderlyingTypeDefOrRef(), baseMethod.DeclaringType)) + if (context.SignatureComparer.Equals(interfaceImpl.Interface?.ToTypeSignature(context).GetUnderlyingTypeDefOrRef(), baseMethod.DeclaringType)) { baseMethodSig = baseMethod.Signature?.InstantiateGenericTypes(GenericContext.FromType(interfaceImpl.Interface!)); break; @@ -356,7 +359,7 @@ private static CilDispatchResult Invoke(CilExecutionContext context, IMethodDesc // Only public virtual instance methods can implicity implement interface methods. (ECMA-335, 6th edition, II.12.2) if (method is { IsPublic: true, IsVirtual: true, IsStatic: false } && method.Name == baseMethod.Name - && SignatureComparer.Default.Equals(method.Signature, baseMethodSig)) + && context.SignatureComparer.Equals(method.Signature, baseMethodSig)) { return method; } @@ -365,7 +368,7 @@ private static CilDispatchResult Invoke(CilExecutionContext context, IMethodDesc return null; } - private static MethodDefinition? TryFindExplicitInterfaceImplementationInType(TypeDefinition type, MethodDefinition baseMethod) + private static MethodDefinition? TryFindExplicitInterfaceImplementationInType(RuntimeContext context, TypeDefinition type, MethodDefinition baseMethod) { for (int i = 0; i < type.MethodImplementations.Count; i++) { @@ -374,15 +377,18 @@ private static CilDispatchResult Invoke(CilExecutionContext context, IMethodDesc continue; // Compare underlying TypeDefOrRef and instantiate any generics to ensure correct comparison. - var declaringType = impl.Declaration?.DeclaringType?.ToTypeSignature().GetUnderlyingTypeDefOrRef(); - if (!SignatureComparer.Default.Equals(declaringType, baseMethod.DeclaringType)) + var declaringType = impl.Declaration?.DeclaringType?.ToTypeSignature(context).GetUnderlyingTypeDefOrRef(); + if (!context.SignatureComparer.Equals(declaringType, baseMethod.DeclaringType)) continue; - var context = GenericContext.FromMethod(impl.Declaration!); - var implMethodSig = impl.Declaration!.Signature?.InstantiateGenericTypes(context); - var baseMethodSig = baseMethod.Signature?.InstantiateGenericTypes(context); - if (SignatureComparer.Default.Equals(baseMethodSig, implMethodSig)) - return impl.Body?.Resolve(); + var genericContext = GenericContext.FromMethod(impl.Declaration!); + var implMethodSig = impl.Declaration!.Signature?.InstantiateGenericTypes(genericContext); + var baseMethodSig = baseMethod.Signature?.InstantiateGenericTypes(genericContext); + if (context.SignatureComparer.Equals(baseMethodSig, implMethodSig) + && impl.Body?.TryResolve(context, out var definition) is true) + { + return definition; + } } return null; diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CallVirtHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CallVirtHandler.cs index a9f10671..b061e169 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CallVirtHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CallVirtHandler.cs @@ -40,8 +40,9 @@ protected override MethodDevirtualizationResult DevirtualizeMethodInternal( ?? objectPointer.AsObjectHandle(context.Machine).GetObjectType(); // Find the implementation. - var implementation = FindMethodImplementationInType(objectType.Resolve(), method.Resolve()); - if (implementation is null) + if (!objectType.TryResolve(context.RuntimeContext, out var objectTypeDefinition) + || !method.TryResolve(context.RuntimeContext, out var methodDefinition) + || FindMethodImplementationInType(context.RuntimeContext, objectTypeDefinition, methodDefinition) is not { } implementation) { // There is no implementation for the method. return MethodDevirtualizationResult.Exception( @@ -51,7 +52,7 @@ protected override MethodDevirtualizationResult DevirtualizeMethodInternal( .AsObjectHandle(context.Machine) ); } - + // Instantiate any generics. var genericContext = GenericContext.FromMethod(method); if (genericContext.IsEmpty) diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CastOpCodeHandlerBase.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CastOpCodeHandlerBase.cs index 3fb70890..094e50d8 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CastOpCodeHandlerBase.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/CastOpCodeHandlerBase.cs @@ -18,7 +18,9 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex var genericContext = GenericContext.FromMethod(context.CurrentFrame.Method); var value = stack.Pop(); - var targetType = ((ITypeDefOrRef) instruction.Operand!).ToTypeSignature().InstantiateGenericTypes(genericContext); + var targetType = ((ITypeDefOrRef) instruction.Operand!) + .ToTypeSignature(context.RuntimeContext) + .InstantiateGenericTypes(genericContext); try { @@ -43,10 +45,10 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex case { } actualAddress: // A non-null reference was passed. var handle = actualAddress.AsObjectHandle(context.Machine); - var objectType = handle.GetObjectType().ToTypeSignature(); + var objectType = handle.GetObjectType().ToTypeSignature(context.RuntimeContext); // TODO: handle full verifier-assignable-to operation. - return objectType.IsAssignableTo(targetType) + return objectType.IsAssignableTo(targetType, context.RuntimeContext) ? HandleSuccessfulCast(context, handle, targetType) : HandleFailedCast(context, objectType, targetType); } diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/ConstrainedHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/ConstrainedHandler.cs index 2b0715d9..6c7d457c 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/ConstrainedHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/ConstrainedHandler.cs @@ -15,7 +15,7 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex { var genericContext = GenericContext.FromMethod(context.CurrentFrame.Method); context.CurrentFrame.ConstrainedType = ((ITypeDescriptor)instruction.Operand!) - .ToTypeSignature() + .ToTypeSignature(context.RuntimeContext) .InstantiateGenericTypes(genericContext); return CilDispatchResult.Success(); 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 dd6826e8..24fcab41 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/FieldOpCodeHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/FieldOpCodeHandler.cs @@ -19,7 +19,10 @@ public CilDispatchResult Dispatch(CilExecutionContext context, CilInstruction in && field.DeclaringType is { } declaringType) { var genericContext = GenericContext.FromMember(context.CurrentFrame.Method); - var instantiated = declaringType.ToTypeSignature().InstantiateGenericTypes(genericContext); + var instantiated = declaringType + .ToTypeSignature(context.RuntimeContext) + .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/Dispatch/ObjectModel/LdFldHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/LdFldHandler.cs index 34bbea90..08ad855c 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/LdFldHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/LdFldHandler.cs @@ -24,7 +24,7 @@ protected override CilDispatchResult DispatchInternal( try { - return field.Resolve() is { IsStatic: true } + return field.TryResolve(context.RuntimeContext, out var definition) && definition.IsStatic ? ReadStaticField(context, field) : ReadInstanceField(context, instruction, instance); } @@ -89,7 +89,7 @@ private static CilDispatchResult ReadInstanceField( case { } actualAddress: // A non-null reference was passed. - var handle = field.DeclaringType!.IsValueType + var handle = field.DeclaringType!.GetIsValueType(context.RuntimeContext) ? actualAddress.AsStructHandle(context.Machine) : actualAddress.AsObjectHandle(context.Machine).Contents; diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/LdFldaHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/LdFldaHandler.cs index 87ec9742..3bb8840f 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/LdFldaHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/LdFldaHandler.cs @@ -26,7 +26,7 @@ protected override CilDispatchResult DispatchInternal( try { // We can actually reference static fields with ldfld. The instance is then just ignored. - if (field.Resolve() is {IsStatic: true}) + if (field.TryResolve(context.RuntimeContext, out var definition) && definition.IsStatic) result.AsSpan().Write(context.Machine.StaticFields.GetFieldAddress(field)); else GetInstanceFieldAddress(context, instance, field, result); @@ -69,7 +69,7 @@ private static void GetInstanceFieldAddress( resultSpan.IntegerAdd(fieldOffsetVector); // Skip also the object header for fields defined within objects. - if (!field.DeclaringType!.IsValueType) + if (!field.DeclaringType!.TryGetIsValueType(context.RuntimeContext).GetValueOrDefault()) resultSpan.IntegerAdd(objectHeaderSize); } finally diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/LdftnHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/LdftnHandler.cs index 3d283582..3fccf672 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/LdftnHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/LdftnHandler.cs @@ -15,8 +15,8 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex { var stack = context.CurrentFrame.EvaluationStack; var factory = context.Machine.ValueFactory; - var methods = context.Machine.ValueFactory.ClrMockMemory.MethodEntryPoints; - var type = context.Machine.ContextModule.CorLibTypeFactory.IntPtr; + var methods = factory.ClrMockMemory.MethodEntryPoints; + var type = factory.CorLibTypeFactory.IntPtr; var functionPointer = methods.GetAddress((IMethodDescriptor)instruction.Operand!); stack.Push(factory.CreateNativeInteger(functionPointer), type); diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/NewObjHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/NewObjHandler.cs index f93e0837..e8f4d3de 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/NewObjHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/NewObjHandler.cs @@ -19,7 +19,7 @@ public class NewObjHandler : CallHandlerBase public override CilDispatchResult Dispatch(CilExecutionContext context, CilInstruction instruction) { var constructor = (IMethodDescriptor)instruction.Operand!; - var instanceType = constructor.DeclaringType!.ToTypeSignature(); + var instanceType = constructor.DeclaringType!.ToTypeSignature(context.RuntimeContext); var arguments = GetArguments(context, constructor); try diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/SizeOfHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/SizeOfHandler.cs index f9d6c455..3eb6ebc3 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/SizeOfHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/SizeOfHandler.cs @@ -18,7 +18,10 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex var factory = context.Machine.ValueFactory; var genericContext = GenericContext.FromMethod(context.CurrentFrame.Method); - var type = ((ITypeDefOrRef)instruction.Operand!).ToTypeSignature().InstantiateGenericTypes(genericContext); + var type = ((ITypeDefOrRef)instruction.Operand!) + .ToTypeSignature(context.RuntimeContext) + .InstantiateGenericTypes(genericContext); + var value = factory.BitVectorPool.Rent(32, false); value.AsSpan().Write(factory.GetTypeValueMemoryLayout(type).Size); stack.Push(new StackSlot(value, StackSlotTypeHint.Integer)); diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/StFldHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/StFldHandler.cs index 4930cbba..9ffcb002 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/StFldHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/ObjectModel/StFldHandler.cs @@ -24,7 +24,7 @@ protected override CilDispatchResult DispatchInternal( try { - if (field.Resolve() is {IsStatic: true}) + if (field.TryResolve(context.RuntimeContext, out var definition) && definition.IsStatic) { // Referenced field is static, we can ignore the instance object that was pushed. long fieldAddress = context.Machine.StaticFields.GetFieldAddress(field); @@ -53,7 +53,7 @@ protected override CilDispatchResult DispatchInternal( case { } actualAddress: // A non-null reference was passed. - var handle = field.DeclaringType!.IsValueType + var handle = field.DeclaringType!.GetIsValueType(context.RuntimeContext) ? actualAddress.AsStructHandle(context.Machine) : actualAddress.AsObjectHandle(context.Machine).Contents; diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/CpObjHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/CpObjHandler.cs index e5e6bc7f..2d9df961 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/CpObjHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/CpObjHandler.cs @@ -35,7 +35,7 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex return CilDispatchResult.NullReference(context); // Perform the copy. - var buffer = factory.CreateValue(type.ToTypeSignature(), false); + var buffer = factory.CreateValue(type.ToTypeSignature(context.RuntimeContext), false); // If source address is unknown, leave the buffer with unknown bits. if (sourceAddress.HasValue) diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/InitBlkHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/InitBlkHandler.cs index d35a1802..0719797a 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/InitBlkHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/InitBlkHandler.cs @@ -16,7 +16,7 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex var factory = context.Machine.ValueFactory; var size = stack.Pop(); - var value = stack.Pop(context.Machine.ContextModule.CorLibTypeFactory.Byte); + var value = stack.Pop(factory.CorLibTypeFactory.Byte); var address = stack.Pop(); try diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/InitObjHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/InitObjHandler.cs index 6b1ac573..2476eb34 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/InitObjHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/InitObjHandler.cs @@ -16,9 +16,11 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex var factory = context.Machine.ValueFactory; var genericContext = GenericContext.FromMethod(context.CurrentFrame.Method); - var type = ((ITypeDefOrRef)instruction.Operand!).ToTypeSignature().InstantiateGenericTypes(genericContext); - var address = context.CurrentFrame.EvaluationStack.Pop(); + var type = ((ITypeDefOrRef)instruction.Operand!) + .ToTypeSignature(context.RuntimeContext) + .InstantiateGenericTypes(genericContext); + var address = context.CurrentFrame.EvaluationStack.Pop(); try { diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/LdIndHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/LdIndHandler.cs index 50056b95..130068ff 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/LdIndHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/LdIndHandler.cs @@ -72,10 +72,10 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex private static TypeSignature GetElementType(CilExecutionContext context, CilInstruction instruction) { - var factory = context.Machine.ValueFactory.ContextModule.CorLibTypeFactory; + var factory = context.Machine.ValueFactory.CorLibTypeFactory; return instruction.OpCode.Code switch { - CilCode.Ldobj => ((ITypeDefOrRef) instruction.Operand!).ToTypeSignature(), + CilCode.Ldobj => ((ITypeDefOrRef) instruction.Operand!).ToTypeSignature(context.RuntimeContext), CilCode.Ldind_I => factory.IntPtr, CilCode.Ldind_I1 => factory.SByte, CilCode.Ldind_I2 => factory.Int16, diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/StIndHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/StIndHandler.cs index c4e4e1fd..e8a73fba 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/StIndHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Pointers/StIndHandler.cs @@ -69,10 +69,10 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex private static TypeSignature GetElementType(CilExecutionContext context, CilInstruction instruction) { - var factory = context.Machine.ValueFactory.ContextModule.CorLibTypeFactory; + var factory = context.Machine.ValueFactory.CorLibTypeFactory; return instruction.OpCode.Code switch { - CilCode.Stobj => ((ITypeDefOrRef) instruction.Operand!).ToTypeSignature(), + CilCode.Stobj => ((ITypeDefOrRef) instruction.Operand!).ToTypeSignature(context.RuntimeContext), CilCode.Stind_I => factory.IntPtr, CilCode.Stind_I1 => factory.SByte, CilCode.Stind_I2 => factory.Int16, diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Variables/StArgHandler.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Variables/StArgHandler.cs index e6dad30d..0810b47e 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Variables/StArgHandler.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Dispatch/Variables/StArgHandler.cs @@ -18,7 +18,7 @@ protected override CilDispatchResult DispatchInternal(CilExecutionContext contex var genericContext = GenericContext.FromMethod(context.CurrentFrame.Method); // Extract parameter in opcode or operand. - var parameter = instruction.GetParameter(frame.Body!.Owner.Parameters); + var parameter = instruction.GetParameter(frame.Body!.Owner!.Parameters); var parameterType = parameter.ParameterType.InstantiateGenericTypes(genericContext); diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Heap/HostObject.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Heap/HostObject.cs index b3e581d4..4bca7de7 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Heap/HostObject.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Heap/HostObject.cs @@ -161,8 +161,8 @@ private ITypeDescriptor GetArrayElementRepresentative() { var elementType = Object.GetType().GetElementType()!; - var factory = _machine.ContextModule.CorLibTypeFactory; - var representative = Type.GetTypeCode(elementType) switch + var factory = _machine.ValueFactory.CorLibTypeFactory; + return Type.GetTypeCode(elementType) switch { TypeCode.Boolean => factory.Boolean, TypeCode.Byte => factory.Byte, @@ -181,7 +181,6 @@ private ITypeDescriptor GetArrayElementRepresentative() _ when !elementType.IsValueType => factory.Object, _ => throw new NotSupportedException($"Could not deserialize an array with element type {elementType}.") }; - return representative; } private FieldInfo? GetFieldInfoAtOffset(uint offset) @@ -211,7 +210,7 @@ private ITypeDescriptor GetArrayElementRepresentative() private static TypeMemoryLayout GetLayout(ValueFactory factory, object value) { var type = value.GetType(); - var descriptor = factory.ContextModule.DefaultImporter.ImportType(type); + var descriptor = factory.Importer.ImportType(type); // Special treatment for array types. if (descriptor is TypeSpecification { Signature: SzArrayTypeSignature arrayType }) diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Heap/ManagedObjectHeap.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Heap/ManagedObjectHeap.cs index e3665a60..59d6a05c 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Heap/ManagedObjectHeap.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Heap/ManagedObjectHeap.cs @@ -64,7 +64,7 @@ public long AllocateFlat(uint size, bool initialize) /// public long AllocateObject(ITypeDescriptor type, bool initialize) { - switch (type.ToTypeSignature().ElementType) + switch (type.ToTypeSignature(_factory.RuntimeContext).ElementType) { case ElementType.Array: case ElementType.SzArray: @@ -132,7 +132,7 @@ public long AllocateString(int length, bool initialize) var chunkSpan = _backingHeap.GetChunkSpan(address); // Set object type. - SetMethodTable(chunkSpan, _factory.ContextModule.CorLibTypeFactory.String); + SetMethodTable(chunkSpan, _factory.CorLibTypeFactory.String); // Set string length field. chunkSpan.SliceStringLength(_factory).Write(length); @@ -155,7 +155,7 @@ public long AllocateString(BitVector contents) var chunkSpan = _backingHeap.GetChunkSpan(address); // Set object type. - SetMethodTable(chunkSpan, _factory.ContextModule.CorLibTypeFactory.String); + SetMethodTable(chunkSpan, _factory.CorLibTypeFactory.String); // Set string length field. chunkSpan.SliceStringLength(_factory).Write(stringLength); diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Invocation/DelegateInvoker.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Invocation/DelegateInvoker.cs index 7a17ea79..7e9bd4c9 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Invocation/DelegateInvoker.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Invocation/DelegateInvoker.cs @@ -22,7 +22,7 @@ public InvocationResult Invoke(CilExecutionContext context, IMethodDescriptor me if (method is not { Name.Value: { } name, DeclaringType: { } declaringType, Signature: not null }) return InvocationResult.Inconclusive(); - if (declaringType.Resolve() is { IsDelegate: false }) + if (!declaringType.TryResolve(context.RuntimeContext, out var definition) || !definition.IsDelegate) return InvocationResult.Inconclusive(); return name switch diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Invocation/NativeMethodInvoker.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Invocation/NativeMethodInvoker.cs index 28e3b339..584ef659 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Invocation/NativeMethodInvoker.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Invocation/NativeMethodInvoker.cs @@ -30,8 +30,7 @@ public IMethodInvoker BaseInvoker /// public InvocationResult Invoke(CilExecutionContext context, IMethodDescriptor method, IList arguments) { - var definition = method.Resolve(); - return definition?.CilMethodBody is null + return method.TryResolve(context.RuntimeContext, out var definition) && definition?.CilMethodBody is null ? BaseInvoker.Invoke(context, method, arguments) : InvocationResult.Inconclusive(); } diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Invocation/RuntimeHelpersInvoker.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Invocation/RuntimeHelpersInvoker.cs index d2f73144..f6fe2044 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Invocation/RuntimeHelpersInvoker.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Invocation/RuntimeHelpersInvoker.cs @@ -55,14 +55,15 @@ private static InvocationResult InvokeInitializeArray(CilExecutionContext contex if (!context.Machine.ValueFactory.ClrMockMemory.Fields.TryGetObject(fieldHandle.Address, out var field)) return InvocationResult.Inconclusive(); - // Resole the field behind the field descriptor. - var definition = field!.Resolve(); + // Resolve the field behind the field descriptor. + if (!field!.TryResolve(context.RuntimeContext, out var definition)) + return InvocationResult.Inconclusive(); // Read the data. - if (definition?.FieldRva is not IReadableSegment segment) + if (definition.FieldRva is not IReadableSegment segment) return InvocationResult.Inconclusive(); - array.WriteArrayData(segment.ToArray()); + array.WriteArrayData(segment.ToArray()); return InvocationResult.StepOver(null); } } \ No newline at end of file diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ObjectHandle.DebugProxy.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ObjectHandle.DebugProxy.cs index 95ceba6c..1f74d982 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ObjectHandle.DebugProxy.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ObjectHandle.DebugProxy.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using AsmResolver.DotNet; using AsmResolver.DotNet.Signatures; using AsmResolver.PE.DotNet.Metadata.Tables; @@ -43,10 +44,14 @@ public KeyValuePair[] Items get { if (_handle.IsNull) - return Array.Empty>(); - - var type = _handle.GetObjectType().ToTypeSignature(); - + return []; + + var descriptor = _handle.GetObjectType(); + bool? isValueType = descriptor.TryGetIsValueType(_handle.Machine.RuntimeContext); + if (!isValueType.HasValue) + return []; + + var type = descriptor.ToTypeSignature(_handle.Machine.RuntimeContext); return type switch { CorLibTypeSignature {ElementType: ElementType.String} => GetStringValue(), @@ -99,9 +104,8 @@ private KeyValuePair[] GetArrayValues(SzArrayTypeSignature type) private KeyValuePair[] GetObjectFieldValues(TypeSignature type) { // We need to resolve the type to know which fields to include. - var definition = type.Resolve(); - if (definition is null) - return Array.Empty>(); + if (!type.TryResolve(_handle.Machine!.RuntimeContext, out var definition)) + return []; // Collect all fields and their values. var result = new List>(); diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ObjectHandle.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ObjectHandle.cs index 9ce92cec..9ced30b2 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ObjectHandle.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ObjectHandle.cs @@ -374,7 +374,7 @@ public void WriteArrayElement(TypeSignature elementType, long index, BitVectorSp public BitVector ReadObjectData() { AssertIsValidHandle(); - var buffer = Machine.ValueFactory.CreateValue(GetObjectType().ToTypeSignature(), false); + var buffer = Machine.ValueFactory.CreateValue(GetObjectType().ToTypeSignature(Machine.RuntimeContext), false); ReadObjectData(buffer); return buffer; } diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ObjectMarshaller.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ObjectMarshaller.cs index a971dfa5..db67a844 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ObjectMarshaller.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ObjectMarshaller.cs @@ -2,7 +2,6 @@ using System.IO; using System.Text; using Echo.Memory; -using Echo.Platforms.AsmResolver.Emulation.Heap; namespace Echo.Platforms.AsmResolver.Emulation { @@ -147,14 +146,14 @@ private static decimal ReadDecimalVector(BitVectorSpan vector) private object? DeserializeArray(long pointer, Type elementType) { - var factory = Machine.ContextModule.CorLibTypeFactory; + var factory = Machine.ValueFactory.CorLibTypeFactory; var representative = Type.GetTypeCode(elementType) switch { TypeCode.Boolean => factory.Boolean, TypeCode.Byte => factory.Byte, TypeCode.Char => factory.Char, TypeCode.DateTime => factory.Int64, - TypeCode.Decimal => Machine.ValueFactory.DecimalType.ToTypeSignature(), + TypeCode.Decimal => Machine.ValueFactory.DecimalType.ToTypeSignature(isValueType: true), TypeCode.Double => factory.Double, TypeCode.Int16 => factory.Int16, TypeCode.Int32 => factory.Int32, diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Runtime/RuntimeTypeManager.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Runtime/RuntimeTypeManager.cs index fbfeae04..c8c0eb27 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Runtime/RuntimeTypeManager.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Runtime/RuntimeTypeManager.cs @@ -96,8 +96,7 @@ public TypeInitializerResult HandleInitialization(CilThread thread, ITypeDescrip return TypeInitializerResult.NoAction(); // Try resolve the type that is being initialized. - var definition = type.Resolve(); - if (definition is null) + if (!type.TryResolve(thread.Machine.RuntimeContext, out var definition)) { initialization.Exception = _machine.Heap .AllocateObject(_machine.ValueFactory.TypeInitializationExceptionType, true) @@ -119,13 +118,11 @@ public TypeInitializerResult HandleInitialization(CilThread thread, ITypeDescrip var result = (IMethodDescriptor) cctor; // Instantiate any args in the declaring type. - if (type.ToTypeSignature() is {} typeSignature) - { - var context = GenericContext.FromType(type); - var newType = typeSignature.InstantiateGenericTypes(context); - if (newType != typeSignature) - result = newType.ToTypeDefOrRef().CreateMemberReference(cctor.Name!, cctor.Signature!); - } + var typeSignature = type.ToTypeSignature(thread.Machine.RuntimeContext); + var context = GenericContext.FromType(type); + var newType = typeSignature.InstantiateGenericTypes(context); + if (newType != typeSignature) + result = newType.ToTypeDefOrRef().CreateMemberReference(cctor.Name!, cctor.Signature!); thread.CallStack.Push(result); return TypeInitializerResult.Redirected(); diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Runtime/StaticFieldStorage.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Runtime/StaticFieldStorage.cs index 98521943..a4850146 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Runtime/StaticFieldStorage.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Runtime/StaticFieldStorage.cs @@ -74,12 +74,13 @@ public long GetOrInitializeFieldAddress(IFieldDescriptor field, bool initializeW // Pre-initialize fields that are assigned some field rva data. // TODO: For more accuracy, we should return the address from within the mapped PE memory range. - if (field.Resolve() is { IsStatic: true, HasFieldRva: true, FieldRva: IReadableSegment data } def) + if (field.TryResolve(_valueFactory.RuntimeContext, out var definition) + && definition is { IsStatic: true, HasFieldRva: true, FieldRva: IReadableSegment data }) { - field = def; + field = definition; _heap.GetChunkSpan(address).Write(data.WriteIntoArray()); } - + _fields.Add(field, address); } diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/CallFrame.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/CallFrame.cs index 95d69c7e..177d1cbf 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/CallFrame.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/CallFrame.cs @@ -60,7 +60,7 @@ internal CallFrame(IMethodDescriptor method, ValueFactory factory, bool isRoot) _initializeLocals = false; // Allocate local variables. - if (method.Resolve()?.CilMethodBody is not { } body) + if (!method.TryResolve(factory.RuntimeContext, out var definition) || definition.CilMethodBody is not { } body) { Body = null; } @@ -81,7 +81,7 @@ internal CallFrame(IMethodDescriptor method, ValueFactory factory, bool isRoot) // Allocate this parameter if required. if (method.Signature.HasThis) - AllocateFrameField(method.DeclaringType?.ToTypeSignature() ?? method.ContextModule!.CorLibTypeFactory.Object); + AllocateFrameField(method.DeclaringType?.ToTypeSignature(factory.RuntimeContext) ?? method.ContextModule!.CorLibTypeFactory.Object); // Allocate rest of the parameters. foreach (var parameterType in method.Signature.ParameterTypes) @@ -320,7 +320,7 @@ private void InitializeExceptionHandlerFrames() { if (!merged.TryGetValue(range.ProtectedRange, out var frame)) { - frame = new ExceptionHandlerFrame(range.ProtectedRange); + frame = new ExceptionHandlerFrame(EvaluationStack.Factory, range.ProtectedRange); merged.Add(range.ProtectedRange, frame); _exceptionHandlers.Add(frame); } diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/CallStack.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/CallStack.cs index 835ecff8..40b47984 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/CallStack.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/CallStack.cs @@ -36,8 +36,12 @@ public CallStack(uint maxSize, ValueFactory factory) _factory = factory; AddressRange = new AddressRange(0, maxSize); - var rootMethod = new MethodDefinition("<>", MethodAttributes.Static, - MethodSignature.CreateStatic(factory.ContextModule.CorLibTypeFactory.Void)); + var rootMethod = new MethodDefinition( + "<>", + MethodAttributes.Static, + MethodSignature.CreateStatic(factory.CorLibTypeFactory.Void) + ); + Push(new CallFrame(rootMethod, factory, true)); } diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/EvaluationStack.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/EvaluationStack.cs index 60a149d6..9ef80b2b 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/EvaluationStack.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/EvaluationStack.cs @@ -29,7 +29,7 @@ internal ValueFactory Factory public void Push(ObjectHandle value) { var vector = Factory.RentNativeInteger(value.Address); - Push(vector, Factory.ContextModule.CorLibTypeFactory.Object, true); + Push(vector, Factory.CorLibTypeFactory.Object, true); } /// diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/ExceptionHandlerFrame.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/ExceptionHandlerFrame.cs index beffbd82..0635c427 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/ExceptionHandlerFrame.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/Stack/ExceptionHandlerFrame.cs @@ -12,6 +12,7 @@ namespace Echo.Platforms.AsmResolver.Emulation.Stack [DebuggerDisplay("Range = {ProtectedRange}, Handler Count = {Handlers.Count}, Next Offset = {NextOffset}")] public class ExceptionHandlerFrame { + private readonly ValueFactory _factory; private readonly List _handlers; private int _currentHandlerIndex = -1; @@ -19,8 +20,9 @@ public class ExceptionHandlerFrame /// Creates a new exception handler frame. /// /// The IL offset range the exception handler is protecting. - public ExceptionHandlerFrame(AddressRange protectedRange) + public ExceptionHandlerFrame(ValueFactory factory, AddressRange protectedRange) { + _factory = factory; ProtectedRange = protectedRange; _handlers = new List(); Reset(); @@ -238,10 +240,10 @@ public int Leave(int leaveTargetOffset) switch (CurrentHandler.HandlerType) { case CilExceptionHandlerType.Exception: - var supportedType = CurrentHandler.ExceptionType!.ToTypeSignature(); - var actualType = ExceptionObject.GetObjectType().ToTypeSignature(); + var supportedType = CurrentHandler.ExceptionType!.ToTypeSignature(_factory.RuntimeContext); + var actualType = ExceptionObject.GetObjectType().ToTypeSignature(_factory.RuntimeContext); - if (actualType.IsAssignableTo(supportedType)) + if (actualType.IsAssignableTo(supportedType, _factory.RuntimeContext)) { IsHandlingException = true; return CurrentHandler.HandlerStart!.Offset; diff --git a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ValueFactory.cs b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ValueFactory.cs index 69a5f5cd..cbf63360 100644 --- a/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ValueFactory.cs +++ b/src/Platforms/Echo.Platforms.AsmResolver/Emulation/ValueFactory.cs @@ -31,101 +31,99 @@ static ValueFactory() /// /// Creates a new value factory. /// - /// The manifest module to use for context. + /// The runtime context to assume when creating values and managing types. /// A value indicating whether the environment is a 32-bit or 64-bit system. - public ValueFactory(ModuleDefinition contextModule, bool is32Bit) + public ValueFactory(RuntimeContext runtimeContext, bool is32Bit) { - ContextModule = contextModule; + RuntimeContext = runtimeContext; Is32Bit = is32Bit; PointerSize = is32Bit ? 4u : 8u; ClrMockMemory = new ClrMockMemory(); BitVectorPool = new BitVectorPool(); Marshaller = new CliMarshaller(this); + var corLibScope = RuntimeContext.RuntimeCorLib?.ToAssemblyReference() + ?? throw new ArgumentException("The provided runtime context does not have an implementation."); + + // TODO: we still rely on some old behavior where we need ContextModule to be set in some fringe situations. Remove this. + var dummyModule = new ModuleDefinition("Root", corLibScope); + Importer = dummyModule.DefaultImporter; + CorLibTypeFactory = dummyModule.CorLibTypeFactory; + // CorLibTypeFactory = new CorLibTypeFactory(corLibScope); // Force System.String to be aligned at 4 bytes (required for low level string APIs). - GetTypeDefOrRefContentsLayout(contextModule.CorLibTypeFactory.String.Type, default, 4); - - DelegateType = new TypeReference( - contextModule, - contextModule.CorLibTypeFactory.CorLibScope, - nameof(System), - nameof(Delegate)).Resolve()!; - - DelegateTargetField = new MemberReference( - (IMemberRefParent)DelegateType, - "_target", - new FieldSignature(contextModule.CorLibTypeFactory.Object)); - - DelegateMethodPtrField = new MemberReference( - (IMemberRefParent)DelegateType, - "_methodPtr", - new FieldSignature(contextModule.CorLibTypeFactory.IntPtr)); - - DecimalType = new TypeReference( - contextModule, - contextModule.CorLibTypeFactory.CorLibScope, - nameof(System), - nameof(Decimal)).Resolve()!; - - InvalidProgramExceptionType = new TypeReference( - contextModule, - contextModule.CorLibTypeFactory.CorLibScope, - nameof(System), - nameof(InvalidProgramException)).Resolve()!; + GetTypeDefOrRefContentsLayout(CorLibTypeFactory.String.Type, default, 4); + + DelegateType = corLibScope + .CreateTypeReference(nameof(System), nameof(Delegate)) + .Resolve(runtimeContext); + + DelegateTargetField = DelegateType.ToTypeDefOrRef() + .CreateMemberReference("_target", new FieldSignature(CorLibTypeFactory.Object)); + + DelegateMethodPtrField = DelegateType.ToTypeDefOrRef() + .CreateMemberReference("_methodPtr", new FieldSignature(CorLibTypeFactory.IntPtr)); + + DecimalType = corLibScope + .CreateTypeReference(nameof(System), nameof(Decimal)) + .Resolve(runtimeContext); - TypeInitializationExceptionType = new TypeReference( - contextModule, - contextModule.CorLibTypeFactory.CorLibScope, - nameof(System), - nameof(TypeInitializationException)).Resolve()!; + InvalidProgramExceptionType = corLibScope + .CreateTypeReference(nameof(System), nameof(InvalidProgramException)) + .Resolve(runtimeContext); - NullReferenceExceptionType = new TypeReference( - contextModule, - contextModule.CorLibTypeFactory.CorLibScope, - nameof(System), - nameof(NullReferenceException)).Resolve()!; + TypeInitializationExceptionType = corLibScope + .CreateTypeReference(nameof(System), nameof(TypeInitializationException)) + .Resolve(runtimeContext); - InvalidProgramExceptionType = new TypeReference( - contextModule, - contextModule.CorLibTypeFactory.CorLibScope, - nameof(System), - nameof(InvalidProgramException)).Resolve()!; + NullReferenceExceptionType = corLibScope + .CreateTypeReference(nameof(System), nameof(NullReferenceException)) + .Resolve(runtimeContext); - IndexOutOfRangeExceptionType = new TypeReference( - contextModule, - contextModule.CorLibTypeFactory.CorLibScope, - nameof(System), - nameof(IndexOutOfRangeException)).Resolve()!; + InvalidProgramExceptionType = corLibScope + .CreateTypeReference(nameof(System), nameof(InvalidProgramException)) + .Resolve(runtimeContext); - StackOverflowExceptionType = new TypeReference( - contextModule, - contextModule.CorLibTypeFactory.CorLibScope, - nameof(System), - nameof(StackOverflowException)).Resolve()!; + IndexOutOfRangeExceptionType = corLibScope + .CreateTypeReference(nameof(System), nameof(IndexOutOfRangeException)) + .Resolve(runtimeContext); - MissingMethodExceptionType = new TypeReference( - contextModule, - contextModule.CorLibTypeFactory.CorLibScope, - nameof(System), - nameof(MissingMethodException)).Resolve()!; + StackOverflowExceptionType = corLibScope + .CreateTypeReference(nameof(System), nameof(StackOverflowException)) + .Resolve(runtimeContext); - InvalidCastExceptionType = new TypeReference( - contextModule, - contextModule.CorLibTypeFactory.CorLibScope, - nameof(System), - nameof(InvalidCastException)).Resolve()!; + MissingMethodExceptionType = corLibScope + .CreateTypeReference(nameof(System), nameof(MissingMethodException)) + .Resolve(runtimeContext); - OverflowExceptionType = new TypeReference( - contextModule, - contextModule.CorLibTypeFactory.CorLibScope, - nameof(System), - nameof(OverflowException)).Resolve()!; + InvalidCastExceptionType = corLibScope + .CreateTypeReference(nameof(System), nameof(InvalidCastException)) + .Resolve(runtimeContext); + + OverflowExceptionType = corLibScope + .CreateTypeReference(nameof(System), nameof(OverflowException)) + .Resolve(runtimeContext); } /// - /// Gets the manifest module to use for context. + /// Gets the runtime context the value factory assumes when managing types. /// - public ModuleDefinition ContextModule + public RuntimeContext RuntimeContext + { + get; + } + + /// + /// Gets the importer that is associated to the . + /// + public ReferenceImporter Importer + { + get; + } + + /// + /// Gets the corlib type factory that is associated to the . + /// + public CorLibTypeFactory CorLibTypeFactory { get; } @@ -157,7 +155,7 @@ public ClrMockMemory ClrMockMemory /// /// Gets a reference to the type. /// - public ITypeDescriptor DecimalType + public ITypeDefOrRef DecimalType { get; } @@ -165,7 +163,7 @@ public ITypeDescriptor DecimalType /// /// Gets a reference to the type. /// - public ITypeDescriptor DelegateType + public ITypeDefOrRef DelegateType { get; } @@ -189,7 +187,7 @@ public IFieldDescriptor DelegateMethodPtrField /// /// Gets a reference to the type. /// - public ITypeDescriptor InvalidProgramExceptionType + public ITypeDefOrRef InvalidProgramExceptionType { get; } @@ -205,7 +203,7 @@ public TypeDefinition TypeInitializationExceptionType /// /// Gets a reference to the type. /// - public ITypeDescriptor NullReferenceExceptionType + public ITypeDefOrRef NullReferenceExceptionType { get; } @@ -213,7 +211,7 @@ public ITypeDescriptor NullReferenceExceptionType /// /// Gets a reference to the type. /// - public ITypeDescriptor IndexOutOfRangeExceptionType + public ITypeDefOrRef IndexOutOfRangeExceptionType { get; } @@ -221,7 +219,7 @@ public ITypeDescriptor IndexOutOfRangeExceptionType /// /// Gets a reference to the type. /// - public ITypeDescriptor StackOverflowExceptionType + public ITypeDefOrRef StackOverflowExceptionType { get; } @@ -229,7 +227,7 @@ public ITypeDescriptor StackOverflowExceptionType /// /// Gets a reference to the type. /// - public ITypeDescriptor MissingMethodExceptionType + public ITypeDefOrRef MissingMethodExceptionType { get; } @@ -237,7 +235,7 @@ public ITypeDescriptor MissingMethodExceptionType /// /// Gets a reference to the type. /// - public ITypeDescriptor InvalidCastExceptionType + public ITypeDefOrRef InvalidCastExceptionType { get; } @@ -245,7 +243,7 @@ public ITypeDescriptor InvalidCastExceptionType /// /// Gets a reference to the type. /// - public ITypeDescriptor OverflowExceptionType + public ITypeDefOrRef OverflowExceptionType { get; } @@ -299,7 +297,7 @@ public CliMarshaller Marshaller /// The total size in bytes. public uint GetArrayObjectSize(ITypeDescriptor elementType, int elementCount) { - uint elementSize = elementType.IsValueType + uint elementSize = elementType.GetIsValueType(RuntimeContext) ? GetTypeValueMemoryLayout(elementType).Size : PointerSize; @@ -463,13 +461,13 @@ public BitVector RentValue(TypeSignature type, bool initialize) /// Occurs when the type could not be measured. public TypeMemoryLayout GetTypeValueMemoryLayout(ITypeDescriptor type) { - type = ContextModule.CorLibTypeFactory.FromType(type) ?? type; + type = CorLibTypeFactory.FromType(type) ?? type; if (!_valueLayouts.TryGetValue(type, out var memoryLayout)) { memoryLayout = type switch { - ITypeDefOrRef typeDefOrRef => typeDefOrRef.GetImpliedMemoryLayout(Is32Bit), - TypeSignature signature => signature.GetImpliedMemoryLayout(Is32Bit), + ITypeDefOrRef typeDefOrRef => typeDefOrRef.GetImpliedMemoryLayout(RuntimeContext, Is32Bit), + TypeSignature signature => signature.GetImpliedMemoryLayout(RuntimeContext, Is32Bit), _ => throw new ArgumentOutOfRangeException(nameof(type)) }; @@ -488,7 +486,7 @@ public TypeMemoryLayout GetTypeValueMemoryLayout(ITypeDescriptor type) /// Occurs when the type could not be measured. public TypeMemoryLayout GetTypeContentsMemoryLayout(ITypeDescriptor type) { - type = ContextModule.CorLibTypeFactory.FromType(type) ?? type; + type = CorLibTypeFactory.FromType(type) ?? type; if (!_contentLayouts.TryGetValue(type, out var memoryLayout)) { memoryLayout = type switch @@ -516,11 +514,9 @@ public FieldMemoryLayout GetFieldMemoryLayout(IFieldDescriptor field) throw new ArgumentException("Field declaring type is unknown."); var layout = GetTypeContentsMemoryLayout(field.DeclaringType); + var definition = field.Resolve(RuntimeContext); - if (field.Resolve() is not { } resolvedField) - throw new ArgumentException($"Could not resolve field '{field}'"); - - return layout[resolvedField]; + return layout[definition]; } /// @@ -539,8 +535,9 @@ private TypeMemoryLayout GetTypeDefOrRefContentsLayout(ITypeDefOrRef type, Gener if (type is TypeSpecification {Signature: { } signature}) return GetTypeSignatureContentsLayout(signature); - if (type.Resolve() is not {IsValueType: false} definition) - return type.GetImpliedMemoryLayout(Is32Bit); + var definition = type.Resolve(RuntimeContext); + if (definition.IsValueType) + return type.GetImpliedMemoryLayout(RuntimeContext, Is32Bit); // Hack: AsmResolver currently does not support layout detection of reference types, mainly because it // is CLR implementation specific. Therefore, we "invent" a new layout ourselves instead for our minimal @@ -550,10 +547,16 @@ private TypeMemoryLayout GetTypeDefOrRefContentsLayout(ITypeDefOrRef type, Gener // This does mean however that we need to manually construct a type layout through some reflection // since the setters in TypeMemoryLayout are marked internal. This probably is worthy of a change in // AsmResolver's API in the future. - - var finalType = context.Type != null ? definition.MakeGenericInstanceType([..context.Type.TypeArguments]).ToTypeDefOrRef() : definition; - var layout = new TypeMemoryLayout(finalType, 0, - Is32Bit ? MemoryLayoutAttributes.Is32Bit : MemoryLayoutAttributes.Is64Bit); + + var finalType = context.Type != null + ? definition.MakeGenericInstanceType(RuntimeContext, context.Type.TypeArguments).ToTypeDefOrRef() + : definition; + + var layout = new TypeMemoryLayout( + finalType, + size: 0, + Is32Bit ? MemoryLayoutAttributes.Is32Bit : MemoryLayoutAttributes.Is64Bit + ); uint currentOffset = 0; @@ -562,7 +565,7 @@ private TypeMemoryLayout GetTypeDefOrRefContentsLayout(ITypeDefOrRef type, Gener while (definition is not null) { hierarchy.Push(definition); - definition = definition.BaseType?.Resolve(); + definition = definition.BaseType?.Resolve(RuntimeContext); } // Add all fields top-to-bottom to the layout. @@ -578,10 +581,10 @@ private TypeMemoryLayout GetTypeDefOrRefContentsLayout(ITypeDefOrRef type, Gener // Infer layout for this field. var contentsLayout = field.Signature.FieldType .InstantiateGenericTypes(context) - .GetImpliedMemoryLayout(Is32Bit); + .GetImpliedMemoryLayout(RuntimeContext, Is32Bit); var fieldLayout = new FieldMemoryLayout(field, currentOffset, contentsLayout); - SetField.Invoke(layout, new object[] {field, fieldLayout}); + SetField.Invoke(layout, [field, fieldLayout]); currentOffset = (currentOffset + contentsLayout.Size).Align(alignment); } @@ -603,7 +606,7 @@ private TypeMemoryLayout GetTypeSignatureContentsLayout(TypeSignature type) return GetTypeDefOrRefContentsLayout(type.GetUnderlyingTypeDefOrRef()!, GenericContext.FromType(type), PointerSize); default: - return type.GetImpliedMemoryLayout(Is32Bit); + return type.GetImpliedMemoryLayout(RuntimeContext, Is32Bit); } } } diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/CilVirtualMachineTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/CilVirtualMachineTest.cs index 001ad384..d274c04b 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/CilVirtualMachineTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/CilVirtualMachineTest.cs @@ -33,7 +33,7 @@ public CilVirtualMachineTest(MockModuleFixture fixture, ITestOutputHelper testOu { _fixture = fixture; _testOutputHelper = testOutputHelper; - _vm = new CilVirtualMachine(fixture.MockModule, false); + _vm = new CilVirtualMachine(fixture.MockModule.RuntimeContext!, false); _mainThread = _vm.CreateThread(); } @@ -339,7 +339,7 @@ public void CallFunctionWithLoop() var sum = new MethodDefinition( "Sum", MethodAttributes.Static, - MethodSignature.CreateStatic(factory.Int32, factory.Int32.MakeSzArrayType())); + MethodSignature.CreateStatic(factory.Int32, [factory.Int32.MakeSzArrayType()])); var loopStart = new CilInstructionLabel(); sum.CilMethodBody = new CilMethodBody @@ -413,7 +413,7 @@ public void CallNestedFunction() var bar = new MethodDefinition( "Bar", MethodAttributes.Static, - MethodSignature.CreateStatic(factory.Int32, factory.Int32, factory.Int32)); + MethodSignature.CreateStatic(factory.Int32, [factory.Int32, factory.Int32])); // return Bar(3, 4) * 5; var fooBody = new CilMethodBody @@ -466,17 +466,17 @@ public void CallWithReflection() var appendMethod = stringBuilderType .CreateMemberReference("Append", MethodSignature.CreateInstance( - stringBuilderType.ToTypeSignature(false), factory.String)) + stringBuilderType.ToTypeSignature(false), [factory.String])) .ImportWith(_fixture.MockModule.DefaultImporter); // Prepare dummy method. var foo = new MethodDefinition( - "Foo", + "Foo", MethodAttributes.Static, MethodSignature.CreateStatic( - factory.Void, - stringBuilderType.ToTypeSignature(false), - factory.String)); + factory.Void, + [stringBuilderType.ToTypeSignature(false), factory.String] + )); var fooBody = new CilMethodBody { @@ -498,7 +498,7 @@ public void CallWithReflection() // Set up invoker to reflection invoke StringBuilder::Append(string), and return unknown for everything else. _vm.Invoker = DefaultInvokers.CreateShim() - .Map((IMethodDescriptor) appendMethod.Resolve()!, DefaultInvokers.ReflectionInvoke) + .Map((IMethodDescriptor) appendMethod.Resolve(_vm.RuntimeContext), DefaultInvokers.ReflectionInvoke) .WithFallback(DefaultInvokers.ReturnUnknown); // Call it with a real string builder. @@ -634,7 +634,7 @@ public void StepPrefixedInstructionsShouldStepOverAllInstructions() "DummyMethod", MethodAttributes.Static, MethodSignature.CreateStatic(factory.String, 1, - new GenericParameterSignature(GenericParameterType.Method, 0)) + [new GenericParameterSignature(GenericParameterType.Method, 0)]) ); dummyMethod.GenericParameters.Add(new GenericParameter("T")); dummyMethod.CilMethodBody = new CilMethodBody @@ -649,7 +649,7 @@ public void StepPrefixedInstructionsShouldStepOverAllInstructions() }; dummyMethod.CilMethodBody.Instructions.CalculateOffsets(); - var frame = _mainThread.CallStack.Push(dummyMethod.MakeGenericInstanceMethod(factory.Int32)); + var frame = _mainThread.CallStack.Push(dummyMethod.MakeGenericInstanceMethod([factory.Int32])); frame.WriteArgument(0, new BitVector(1337)); var instructions = dummyMethod.CilMethodBody.Instructions; diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/CliMarshallerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/CliMarshallerTest.cs index d11223c4..98e5c202 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/CliMarshallerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/CliMarshallerTest.cs @@ -17,7 +17,7 @@ public class CliMarshallerTest : IClassFixture public CliMarshallerTest(MockModuleFixture fixture) { _fixture = fixture; - _factory = new ValueFactory(_fixture.MockModule, false); + _factory = new ValueFactory(_fixture.MockModule.RuntimeContext!, false); _marshaller = new CliMarshaller(_factory); } diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/LdElemHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/LdElemHandlerTest.cs index a9fec8ff..b8f30e7e 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/LdElemHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/LdElemHandlerTest.cs @@ -17,7 +17,7 @@ public LdElemHandlerTest(MockModuleFixture fixture) private long CreateArray(int elementCount) { var factory = Context.Machine.ValueFactory; - var elementType = factory.ContextModule.CorLibTypeFactory.Int32; + var elementType = factory.CorLibTypeFactory.Int32; long array = Context.Machine.Heap.AllocateSzArray(elementType, elementCount, false); var arraySpan = Context.Machine.Heap.GetObjectSpan(array); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/LdElemaHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/LdElemaHandlerTest.cs index 9f7461c9..9f2f76ae 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/LdElemaHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/LdElemaHandlerTest.cs @@ -17,7 +17,7 @@ public LdElemaHandlerTest(MockModuleFixture fixture) private long CreateArray(int elementCount) { var factory = Context.Machine.ValueFactory; - var elementType = factory.ContextModule.CorLibTypeFactory.Int32; + var elementType = factory.CorLibTypeFactory.Int32; long array = Context.Machine.Heap.AllocateSzArray(elementType, elementCount, false); var arraySpan = Context.Machine.Heap.GetObjectSpan(array); @@ -36,7 +36,7 @@ public void GetFromNullArrayShouldThrow() var result = Dispatcher.Dispatch(Context, new CilInstruction( CilOpCodes.Ldelema, - Context.Machine.ContextModule.CorLibTypeFactory.Int32.Type)); + Context.Machine.ValueFactory.CorLibTypeFactory.Int32.Type)); Assert.False(result.IsSuccess); var exceptionType = result.ExceptionObject.GetObjectType(); @@ -54,7 +54,7 @@ public void GetOutOfRangeShouldThrow() var result = Dispatcher.Dispatch(Context, new CilInstruction( CilOpCodes.Ldelema, - Context.Machine.ContextModule.CorLibTypeFactory.Int32.Type)); + Context.Machine.ValueFactory.CorLibTypeFactory.Int32.Type)); Assert.False(result.IsSuccess); var exceptionType = result.ExceptionObject.GetObjectType(); @@ -72,7 +72,7 @@ public void GetFromUnknownArrayShouldPushUnknown() var result = Dispatcher.Dispatch(Context, new CilInstruction( CilOpCodes.Ldelema, - Context.Machine.ContextModule.CorLibTypeFactory.Int32.Type)); + Context.Machine.ValueFactory.CorLibTypeFactory.Int32.Type)); Assert.True(result.IsSuccess); Assert.Single(stack); @@ -90,7 +90,7 @@ public void GetFromKnownArrayShouldPushElement() var result = Dispatcher.Dispatch(Context, new CilInstruction( CilOpCodes.Ldelema, - Context.Machine.ContextModule.CorLibTypeFactory.Int32.Type)); + Context.Machine.ValueFactory.CorLibTypeFactory.Int32.Type)); Assert.True(result.IsSuccess); Assert.Single(stack); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/LdNullHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/LdNullHandlerTest.cs index 95830578..86c0ebea 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/LdNullHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/LdNullHandlerTest.cs @@ -1,5 +1,4 @@ using AsmResolver.PE.DotNet.Cil; -using Echo.Platforms.AsmResolver.Emulation; using Echo.Platforms.AsmResolver.Emulation.Stack; using Echo.Platforms.AsmResolver.Tests.Mock; using Xunit; @@ -43,7 +42,7 @@ public void UnknownArrayShouldPushUnknown() [InlineData(10)] public void Int32Array(int length) { - long array = Context.Machine.Heap.AllocateSzArray(Context.Machine.ContextModule.CorLibTypeFactory.Int32, length, true); + long array = Context.Machine.Heap.AllocateSzArray(Context.Machine.ValueFactory.CorLibTypeFactory.Int32, length, true); var stack = Context.CurrentFrame.EvaluationStack; stack.Push(new StackSlot(array, StackSlotTypeHint.Integer)); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/NewArrHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/NewArrHandlerTest.cs index 73ea8e76..88bbc8db 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/NewArrHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/NewArrHandlerTest.cs @@ -20,7 +20,7 @@ public void NewInt32ArrayFullyKnownSize() var factory = Context.Machine.ValueFactory; int elementCount = 10; - var elementType = factory.ContextModule.CorLibTypeFactory.Int32; + var elementType = factory.CorLibTypeFactory.Int32; Context.CurrentFrame.EvaluationStack.Push(new StackSlot(elementCount, StackSlotTypeHint.Integer)); @@ -41,7 +41,7 @@ public void NewInt32ArrayFullyKnownSize() [Fact] public void NewInt32ArrayUnknownSizeShouldPushUnknownPointer() { - var elementType = Context.Machine.ValueFactory.ContextModule.CorLibTypeFactory.Int32; + var elementType = Context.Machine.ValueFactory.CorLibTypeFactory.Int32; Context.CurrentFrame.EvaluationStack.Push(new StackSlot( new BitVector(32, false), diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/StElemHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/StElemHandlerTest.cs index a63d98d7..0d61f0f8 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/StElemHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Arrays/StElemHandlerTest.cs @@ -17,7 +17,7 @@ public StElemHandlerTest(MockModuleFixture fixture) [Fact] public void WriteOutOfRangeShouldThrow() { - long array = Context.Machine.Heap.AllocateSzArray(Context.Machine.ContextModule.CorLibTypeFactory.Int32, 10, true); + long array = Context.Machine.Heap.AllocateSzArray(Context.Machine.ValueFactory.CorLibTypeFactory.Int32, 10, true); var stack = Context.CurrentFrame.EvaluationStack; stack.Push(new StackSlot(array, StackSlotTypeHint.Integer)); @@ -36,7 +36,7 @@ public void WriteInt32Element() var factory = Context.Machine.ValueFactory; var stack = Context.CurrentFrame.EvaluationStack; - var elementType = Context.Machine.ContextModule.CorLibTypeFactory.Int32; + var elementType = Context.Machine.ValueFactory.CorLibTypeFactory.Int32; long array = Context.Machine.Heap.AllocateSzArray(elementType, 10, true); Assert.All(Enumerable.Range(0, 10), i => diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/CilDispatcherTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/CilDispatcherTest.cs index ef8f7cb2..1230277e 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/CilDispatcherTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/CilDispatcherTest.cs @@ -28,7 +28,7 @@ public CilDispatcherTest(MockModuleFixture fixture) var body = new CilMethodBody(); body.Instructions.Add(CilOpCodes.Ret); - var vm = new CilVirtualMachine(fixture.MockModule, false); + var vm = new CilVirtualMachine(fixture.MockModule.RuntimeContext!, false); var thread = vm.CreateThread(); thread.CallStack.Push(dummyMethod); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/CilOpCodeHandlerTestBase.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/CilOpCodeHandlerTestBase.cs index 7b390406..10d8d834 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/CilOpCodeHandlerTestBase.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/CilOpCodeHandlerTestBase.cs @@ -25,7 +25,7 @@ protected CilOpCodeHandlerTestBase(MockModuleFixture fixture) var body = new CilMethodBody(); body.Instructions.Add(CilOpCodes.Ret); - var vm = new CilVirtualMachine(fixture.MockModule, false); + var vm = new CilVirtualMachine(fixture.MockModule.RuntimeContext!, false); var thread = vm.CreateThread(); thread.CallStack.Push(dummyMethod); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Misc/ConvHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Misc/ConvHandlerTest.cs index 19926d54..fb49a538 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Misc/ConvHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Misc/ConvHandlerTest.cs @@ -33,7 +33,7 @@ public void ConvIToI(long value, CilCode code, long expectedValue) { var stack = Context.CurrentFrame.EvaluationStack; - stack.Push(new BitVector(value), Context.Machine.ContextModule.CorLibTypeFactory.Int64); + stack.Push(new BitVector(value), Context.Machine.ValueFactory.CorLibTypeFactory.Int64); var result = Dispatcher.Dispatch(Context, new CilInstruction(code.ToOpCode())); @@ -65,7 +65,7 @@ public void ConvIToU(long value, CilCode code, long expectedValue) { var stack = Context.CurrentFrame.EvaluationStack; - stack.Push(new BitVector(value), Context.Machine.ContextModule.CorLibTypeFactory.Int64); + stack.Push(new BitVector(value), Context.Machine.ValueFactory.CorLibTypeFactory.Int64); var result = Dispatcher.Dispatch(Context, new CilInstruction(code.ToOpCode())); @@ -88,7 +88,7 @@ public void ConvIToR4(long value, CilCode code, float expectedValue) { var stack = Context.CurrentFrame.EvaluationStack; - stack.Push(new BitVector(value), Context.Machine.ContextModule.CorLibTypeFactory.Int64); + stack.Push(new BitVector(value), Context.Machine.ValueFactory.CorLibTypeFactory.Int64); var result = Dispatcher.Dispatch(Context, new CilInstruction(code.ToOpCode())); @@ -107,7 +107,7 @@ public void ConvIToR8(long value, CilCode code, double expectedValue) { var stack = Context.CurrentFrame.EvaluationStack; - stack.Push(new BitVector(value), Context.Machine.ContextModule.CorLibTypeFactory.Int64); + stack.Push(new BitVector(value), Context.Machine.ValueFactory.CorLibTypeFactory.Int64); var result = Dispatcher.Dispatch(Context, new CilInstruction(code.ToOpCode())); @@ -161,7 +161,7 @@ public void ConvRToI(double value, CilCode code, long expectedValue) { var stack = Context.CurrentFrame.EvaluationStack; - stack.Push(new BitVector(value), Context.Machine.ContextModule.CorLibTypeFactory.Double); + stack.Push(new BitVector(value), Context.Machine.ValueFactory.CorLibTypeFactory.Double); var result = Dispatcher.Dispatch(Context, new CilInstruction(code.ToOpCode())); @@ -190,7 +190,7 @@ public void ConvRToU(double value, CilCode code, long expectedValue) { var stack = Context.CurrentFrame.EvaluationStack; - stack.Push(new BitVector(value), Context.Machine.ContextModule.CorLibTypeFactory.Double); + stack.Push(new BitVector(value), Context.Machine.ValueFactory.CorLibTypeFactory.Double); var result = Dispatcher.Dispatch(Context, new CilInstruction(code.ToOpCode())); @@ -218,7 +218,7 @@ public void ConvIOvfShouldOverflow(long value, CilCode code) { var stack = Context.CurrentFrame.EvaluationStack; - stack.Push(new BitVector(value), Context.Machine.ContextModule.CorLibTypeFactory.Int64); + stack.Push(new BitVector(value), Context.Machine.ValueFactory.CorLibTypeFactory.Int64); var result = Dispatcher.Dispatch(Context, new CilInstruction(code.ToOpCode())); @@ -242,7 +242,7 @@ public void ConvROvfShouldOverflow(double value, CilCode code) { var stack = Context.CurrentFrame.EvaluationStack; - stack.Push(new BitVector(value), Context.Machine.ContextModule.CorLibTypeFactory.Double); + stack.Push(new BitVector(value), Context.Machine.ValueFactory.CorLibTypeFactory.Double); var result = Dispatcher.Dispatch(Context, new CilInstruction(code.ToOpCode())); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/CallHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/CallHandlerTest.cs index fd262f30..63e8f565 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/CallHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/CallHandlerTest.cs @@ -55,9 +55,8 @@ public void CallStaticWithParametersUsingStepOver() var factory = ModuleFixture.MockModule.CorLibTypeFactory; var method = new MethodDefinition("Dummy", MethodAttributes.Static, MethodSignature.CreateStatic( factory.Int32, - factory.Int32, - factory.Int32, - factory.Int32)); + [factory.Int32, factory.Int32, factory.Int32] + )); Context.Machine.Invoker = invoker; @@ -72,7 +71,7 @@ public void CallStaticWithParametersUsingStepOver() Assert.Equal(InvocationResultType.StepOver, invoker.LastInvocationResult.ResultType); Assert.Single(callerFrame.EvaluationStack); Assert.Same(method, invoker.LastMethod); - Assert.Equal(new[] {0, 1, 2}, invoker.LastArguments!.Select(x => x.AsSpan().I32)); + Assert.Equal([0, 1, 2], invoker.LastArguments!.Select(x => x.AsSpan().I32)); } [Fact] @@ -82,9 +81,8 @@ public void CallInstanceWithParametersUsingStepOver() var factory = ModuleFixture.MockModule.CorLibTypeFactory; var method = new MethodDefinition("Dummy", MethodAttributes.Public, MethodSignature.CreateInstance( factory.Int32, - factory.Int32, - factory.Int32, - factory.Int32)); + [factory.Int32, factory.Int32, factory.Int32] + )); Context.Machine.Invoker = invoker; @@ -131,9 +129,8 @@ public void CallStaticWithParametersUsingStepIn() var factory = ModuleFixture.MockModule.CorLibTypeFactory; var method = new MethodDefinition("Dummy", MethodAttributes.Static, MethodSignature.CreateStatic( factory.Int32, - factory.Int32, - factory.Int32, - factory.Int32)); + [factory.Int32, factory.Int32, factory.Int32] + )); Context.Machine.Invoker = invoker; @@ -188,9 +185,8 @@ public void CallShouldMarshalArgumentsUsingCorrectTypes() var factory = ModuleFixture.MockModule.CorLibTypeFactory; var method = new MethodDefinition("Dummy", MethodAttributes.Static, MethodSignature.CreateStatic( factory.Int32, - factory.Int32, - factory.Double, - factory.Double)); + [factory.Int32, factory.Double, factory.Double] + )); Context.Machine.Invoker = invoker; @@ -222,8 +218,8 @@ public void CallMethodWithGenericArguments() var method = new MethodDefinition("Dummy", MethodAttributes.Static, MethodSignature.CreateStatic( factory.Int32, 1, - new GenericParameterSignature(GenericParameterType.Method, 0))) - .MakeGenericInstanceMethod(factory.Int32); + [new GenericParameterSignature(GenericParameterType.Method, 0)])) + .MakeGenericInstanceMethod([factory.Int32]); Context.Machine.Invoker = invoker; @@ -249,8 +245,8 @@ public void CallMethodInGenericTypeWithGenericArgumentFromCaller() var caller = new MethodDefinition( "GenericCaller", MethodAttributes.Static, - MethodSignature.CreateStatic(factory.Int32, 1, new GenericParameterSignature(GenericParameterType.Method, 0)) - ).MakeGenericInstanceMethod(factory.Int32); + MethodSignature.CreateStatic(factory.Int32, 1, [new GenericParameterSignature(GenericParameterType.Method, 0)]) + ).MakeGenericInstanceMethod([factory.Int32]); var module = new ModuleDefinition("DummyModule"); var calleeType = new TypeDefinition(null, "SomeGenericType", TypeAttributes.Class, factory.Object.Type); @@ -258,7 +254,7 @@ public void CallMethodInGenericTypeWithGenericArgumentFromCaller() // void SomeGenericType::SomeMethod(); var callee = calleeType - .MakeGenericInstanceType(new GenericParameterSignature(GenericParameterType.Method, 0)) + .MakeGenericInstanceType(isValueType: false, [new GenericParameterSignature(GenericParameterType.Method, 0)]) .ToTypeDefOrRef() .CreateMemberReference("SomeMethod", MethodSignature.CreateStatic(factory.Void)); @@ -271,7 +267,7 @@ public void CallMethodInGenericTypeWithGenericArgumentFromCaller() // void SomeGenericType::SomeMethod(); Assert.Equal(calleeType - .MakeGenericInstanceType(factory.Int32) + .MakeGenericInstanceType(isValueType: false, [factory.Int32]) .ToTypeDefOrRef() .CreateMemberReference(callee.Name!, MethodSignature.CreateStatic(factory.Void)), Context.CurrentFrame.Method, @@ -288,8 +284,8 @@ public void CallGenericMethodWithGenericMethodArgumentFromCaller() var caller = new MethodDefinition( "GenericCaller", MethodAttributes.Static, - MethodSignature.CreateStatic(factory.Int32, 1, new GenericParameterSignature(GenericParameterType.Method, 0)) - ).MakeGenericInstanceMethod(factory.Int32); + MethodSignature.CreateStatic(factory.Int32, 1, [new GenericParameterSignature(GenericParameterType.Method, 0)]) + ).MakeGenericInstanceMethod([factory.Int32]); var module = new ModuleDefinition("DummyModule"); var calleeType = new TypeDefinition(null, "SomeType", TypeAttributes.Class, factory.Object.Type); @@ -297,8 +293,8 @@ public void CallGenericMethodWithGenericMethodArgumentFromCaller() // void SomeType::SomeGenericMethod(); var callee = calleeType - .CreateMemberReference("SomeGenericMethod", MethodSignature.CreateStatic(factory.Void, 1)) - .MakeGenericInstanceMethod(new GenericParameterSignature(GenericParameterType.Method, 0)); + .CreateMemberReference("SomeGenericMethod", MethodSignature.CreateStatic(factory.Void, 1, [])) + .MakeGenericInstanceMethod([new GenericParameterSignature(GenericParameterType.Method, 0)]); Context.Thread.CallStack.Push(caller); Context.Machine.Invoker = DefaultInvokers.StepIn; @@ -309,8 +305,8 @@ public void CallGenericMethodWithGenericMethodArgumentFromCaller() // void SomeType::SomeGenericMethod(); Assert.Equal(calleeType - .CreateMemberReference(callee.Name, MethodSignature.CreateStatic(factory.Void, 1)) - .MakeGenericInstanceMethod(factory.Int32), + .CreateMemberReference(callee.Name, MethodSignature.CreateStatic(factory.Void, 1, [])) + .MakeGenericInstanceMethod([factory.Int32]), Context.CurrentFrame.Method, SignatureComparer.Default ); @@ -333,23 +329,23 @@ public void CallGenericMethodInGenericTypeWithGenericMethodArgumentFromCaller() var callerDefinition = new MethodDefinition( "GenericCaller", MethodAttributes.Static, - MethodSignature.CreateStatic(factory.Int32, 1, new GenericParameterSignature(GenericParameterType.Method, 0)) + MethodSignature.CreateStatic(factory.Int32, 1, [new GenericParameterSignature(GenericParameterType.Method, 0)]) ); // int GenericCallerType::GenericCaller(); var caller = callerTypeDefinition - .MakeGenericInstanceType(factory.Int16) + .MakeGenericInstanceType(isValueType: false, [factory.Int16]) .ToTypeDefOrRef() .CreateMemberReference(callerDefinition.Name!, callerDefinition.Signature) - .MakeGenericInstanceMethod(factory.Byte); + .MakeGenericInstanceMethod([factory.Byte]); callerTypeDefinition.Methods.Add(callerDefinition); // void SomeGenericType::SomeMethod(); var callee = calleeType - .MakeGenericInstanceType(new GenericParameterSignature(GenericParameterType.Method, 0)) + .MakeGenericInstanceType(isValueType: false, [new GenericParameterSignature(GenericParameterType.Method, 0)]) .ToTypeDefOrRef() - .CreateMemberReference("SomeMethod", MethodSignature.CreateStatic(factory.Void, 1)) - .MakeGenericInstanceMethod(factory.Int64); + .CreateMemberReference("SomeMethod", MethodSignature.CreateStatic(factory.Void, 1, [])) + .MakeGenericInstanceMethod([factory.Int64]); Context.Thread.CallStack.Push(caller); Context.Machine.Invoker = DefaultInvokers.StepIn; @@ -360,10 +356,10 @@ public void CallGenericMethodInGenericTypeWithGenericMethodArgumentFromCaller() // void SomeGenericType::SomeMethod(); Assert.Equal(calleeType - .MakeGenericInstanceType(factory.Byte) + .MakeGenericInstanceType(isValueType: false, [factory.Byte]) .ToTypeDefOrRef() - .CreateMemberReference(callee.Name, MethodSignature.CreateStatic(factory.Void, 1)) - .MakeGenericInstanceMethod(factory.Int64), + .CreateMemberReference(callee.Name, MethodSignature.CreateStatic(factory.Void, 1, [])) + .MakeGenericInstanceMethod([factory.Int64]), Context.CurrentFrame.Method, SignatureComparer.Default ); @@ -382,15 +378,15 @@ public void CallGenericMethodInGenericTypeWithGenericTypeAndMethodArgumentsFromC var callerDefinition = new MethodDefinition( "GenericCaller", MethodAttributes.Static, - MethodSignature.CreateStatic(factory.Int32, 1, new GenericParameterSignature(GenericParameterType.Method, 0)) + MethodSignature.CreateStatic(factory.Int32, 1, [new GenericParameterSignature(GenericParameterType.Method, 0)]) ); // int GenericCallerType::GenericCaller(); var caller = callerTypeDefinition - .MakeGenericInstanceType(factory.Int16) + .MakeGenericInstanceType(isValueType: false, [factory.Int16]) .ToTypeDefOrRef() .CreateMemberReference(callerDefinition.Name!, callerDefinition.Signature) - .MakeGenericInstanceMethod(factory.Int32); + .MakeGenericInstanceMethod([factory.Int32]); callerTypeDefinition.Methods.Add(callerDefinition); var module = new ModuleDefinition("DummyModule"); @@ -399,12 +395,19 @@ public void CallGenericMethodInGenericTypeWithGenericTypeAndMethodArgumentsFromC // void SomeGenericType::SomeMethod(); var callee = calleeType - .MakeGenericInstanceType(new GenericParameterSignature(GenericParameterType.Method, 0), - new GenericParameterSignature(GenericParameterType.Type, 0)) + .MakeGenericInstanceType( + isValueType: false, + [ + new GenericParameterSignature(GenericParameterType.Method, 0), + new GenericParameterSignature(GenericParameterType.Type, 0) + ]) .ToTypeDefOrRef() - .CreateMemberReference("SomeMethod", MethodSignature.CreateStatic(factory.Void, 3)) - .MakeGenericInstanceMethod(factory.Int64, new GenericParameterSignature(GenericParameterType.Method, 0), - new GenericParameterSignature(GenericParameterType.Type, 0)); + .CreateMemberReference("SomeMethod", MethodSignature.CreateStatic(factory.Void, 3, [])) + .MakeGenericInstanceMethod([ + factory.Int64, + new GenericParameterSignature(GenericParameterType.Method, 0), + new GenericParameterSignature(GenericParameterType.Type, 0) + ]); Context.Thread.CallStack.Push(caller); Context.Machine.Invoker = DefaultInvokers.StepIn; @@ -415,10 +418,10 @@ public void CallGenericMethodInGenericTypeWithGenericTypeAndMethodArgumentsFromC // void SomeGenericType::SomeMethod(); Assert.Equal(calleeType - .MakeGenericInstanceType(factory.Int32, factory.Int16) + .MakeGenericInstanceType(isValueType: false, [factory.Int32, factory.Int16]) .ToTypeDefOrRef() - .CreateMemberReference(callee.Name, MethodSignature.CreateStatic(factory.Void, 3)) - .MakeGenericInstanceMethod(factory.Int64, factory.Int32, factory.Int16), + .CreateMemberReference(callee.Name, MethodSignature.CreateStatic(factory.Void, 3, [])) + .MakeGenericInstanceMethod([factory.Int64, factory.Int32, factory.Int16]), Context.CurrentFrame.Method, SignatureComparer.Default ); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/CastHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/CastHandlerTest.cs index ce1ec321..305daac9 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/CastHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/CastHandlerTest.cs @@ -192,7 +192,7 @@ public void CastGenericTypeReturnsInt16() .Methods .First(m => m.Name == nameof(SimpleClass.GenericMethod)); - var methodSpecification = genericMethod.MakeGenericInstanceMethod(ModuleFixture.MockModule.CorLibTypeFactory.Int16); + var methodSpecification = genericMethod.MakeGenericInstanceMethod([ModuleFixture.MockModule.CorLibTypeFactory.Int16]); Context.Thread.CallStack.Push(methodSpecification); @@ -222,7 +222,7 @@ public void CastGenericTypeReturnsInt32() .Methods .First(m => m.Name == nameof(SimpleClass.GenericMethod)); - var methodSpecification = genericMethod.MakeGenericInstanceMethod(ModuleFixture.MockModule.CorLibTypeFactory.Int32); + var methodSpecification = genericMethod.MakeGenericInstanceMethod([ModuleFixture.MockModule.CorLibTypeFactory.Int32]); Context.Thread.CallStack.Push(methodSpecification); @@ -251,7 +251,7 @@ public void CastGenericTypeReturnsInt64() .Methods .First(m => m.Name == nameof(SimpleClass.GenericMethod)); - var methodSpecification = genericMethod.MakeGenericInstanceMethod(ModuleFixture.MockModule.CorLibTypeFactory.Int64); + var methodSpecification = genericMethod.MakeGenericInstanceMethod([ModuleFixture.MockModule.CorLibTypeFactory.Int64]); Context.Thread.CallStack.Push(methodSpecification); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/NewObjHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/NewObjHandlerTest.cs index 330f3a46..1d5ccf7e 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/NewObjHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/NewObjHandlerTest.cs @@ -22,7 +22,7 @@ public NewObjHandlerTest(MockModuleFixture fixture) public void NewObject() { // Find System.Object::.ctor() - var type = ModuleFixture.MockModule.CorLibTypeFactory.Object.Resolve()!; + var type = ModuleFixture.MockModule.CorLibTypeFactory.Object.Resolve(ModuleFixture.MockModule.RuntimeContext); var constructor = type.Methods.First(m => m is {IsConstructor: true, Parameters.Count: 0}); var result = Dispatcher.Dispatch(Context, new CilInstruction(CilOpCodes.Newobj, constructor)); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/ThrowHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/ThrowHandlerTest.cs index 6b154f39..2ba1e5da 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/ThrowHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/ObjectModel/ThrowHandlerTest.cs @@ -3,7 +3,6 @@ using AsmResolver.DotNet; using AsmResolver.DotNet.Signatures; using AsmResolver.PE.DotNet.Cil; -using Echo.Platforms.AsmResolver.Emulation; using Echo.Platforms.AsmResolver.Emulation.Stack; using Echo.Platforms.AsmResolver.Tests.Mock; using Xunit; @@ -39,8 +38,7 @@ public void ThrowShouldThrowExceptionOnStack() var stack = Context.CurrentFrame.EvaluationStack; var exceptionType = ModuleDefinition.FromFile(typeof(IOException).Assembly.Location) - .TopLevelTypes.First(t => t.IsTypeOf("System.IO", "IOException")) - .ImportWith(Context.Machine.ContextModule.DefaultImporter); + .TopLevelTypes.First(t => t.IsTypeOf("System.IO", "IOException")); long exceptionPointer = machine.Heap.AllocateObject(exceptionType, true); stack.Push(new StackSlot( diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Pointers/CpObjHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Pointers/CpObjHandlerTest.cs index b8cf5069..193dbc0c 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Pointers/CpObjHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Pointers/CpObjHandlerTest.cs @@ -17,7 +17,7 @@ public CpObjHandlerTest(MockModuleFixture fixture) public void CopyFromNullShouldThrow() { var stack = Context.CurrentFrame.EvaluationStack; - var type = Context.Machine.ContextModule.CorLibTypeFactory.Int32.Type; + var type = Context.Machine.ValueFactory.CorLibTypeFactory.Int32.Type; // Map some destination. long destinationAddress = 0x0600_0000; @@ -40,7 +40,7 @@ public void CopyFromNullShouldThrow() public void CopyToNullShouldThrow() { var stack = Context.CurrentFrame.EvaluationStack; - var type = Context.Machine.ContextModule.CorLibTypeFactory.Int32.Type; + var type = Context.Machine.ValueFactory.CorLibTypeFactory.Int32.Type; // Map some destination. long sourceAddress = 0x0600_0000; @@ -67,7 +67,7 @@ public void CopyValidAddresses() }; var stack = Context.CurrentFrame.EvaluationStack; - var type = Context.Machine.ContextModule.CorLibTypeFactory.Int32.Type; + var type = Context.Machine.ValueFactory.CorLibTypeFactory.Int32.Type; // Map some source. long sourceAddress = 0x0600_0000; diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Pointers/LdIndHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Pointers/LdIndHandlerTest.cs index c3c585d9..18ee833d 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Pointers/LdIndHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Pointers/LdIndHandlerTest.cs @@ -96,16 +96,14 @@ public void ReadExplicitIntFromPointer() var stack = Context.CurrentFrame.EvaluationStack; const long address = 0x0600_0000; - Context.Machine.Memory.Map(address, new BasicMemorySpace(new byte[] - { - 0x00, 0x01, 0x02, 0x03 - })); + Context.Machine.Memory.Map(address, new BasicMemorySpace([0x00, 0x01, 0x02, 0x03])); stack.Push(new StackSlot(address, StackSlotTypeHint.Integer)); var result = Dispatcher.Dispatch(Context, new CilInstruction( CilOpCodes.Ldobj, - Context.Machine.ContextModule.CorLibTypeFactory.Int32.Type)); - + Context.Machine.ValueFactory.CorLibTypeFactory.Int32.Type)) + ; + Assert.True(result.IsSuccess); var slot = Context.CurrentFrame.EvaluationStack.Peek(); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Pointers/StIndHandlerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Pointers/StIndHandlerTest.cs index 730c99da..a0ccdec6 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Pointers/StIndHandlerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Dispatch/Pointers/StIndHandlerTest.cs @@ -1,6 +1,5 @@ using AsmResolver.PE.DotNet.Cil; using Echo.Memory; -using Echo.Platforms.AsmResolver.Emulation; using Echo.Platforms.AsmResolver.Emulation.Stack; using Echo.Platforms.AsmResolver.Tests.Mock; using Xunit; @@ -92,7 +91,7 @@ public void WriteExplicitIntToPointer() var result = Dispatcher.Dispatch(Context, new CilInstruction( CilOpCodes.Stobj, - Context.Machine.ContextModule.CorLibTypeFactory.Int32.Type)); + Context.Machine.ValueFactory.CorLibTypeFactory.Int32.Type)); Assert.True(result.IsSuccess); Assert.Empty(stack); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Heap/ManagedObjectHeapTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Heap/ManagedObjectHeapTest.cs index 87bd70d7..42ec2ffd 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Heap/ManagedObjectHeapTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Heap/ManagedObjectHeapTest.cs @@ -1,7 +1,6 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using AsmResolver.DotNet; using AsmResolver.DotNet.Signatures; using Echo.Memory; using Echo.Memory.Heap; @@ -23,7 +22,7 @@ public class ManagedObjectHeapTest : IClassFixture public ManagedObjectHeapTest(MockModuleFixture fixture) { _fixture = fixture; - _factory = new ValueFactory(fixture.CurrentTestModule, false); + _factory = new ValueFactory(fixture.CurrentTestModule.RuntimeContext!, false); _objectHeap = new ManagedObjectHeap(new BasicHeap(1000), _factory); } @@ -35,7 +34,7 @@ public void StringObjects(string value) long address = _objectHeap.AllocateString(value); var objectSpan = _objectHeap.GetObjectSpan(address); - Assert.Equal(_factory.ContextModule.CorLibTypeFactory.String, + Assert.Equal(_factory.CorLibTypeFactory.String, _factory.ClrMockMemory.MethodTables.GetObject(objectSpan.SliceObjectMethodTable(_factory).I64)); Assert.Equal(value.Length, objectSpan.SliceStringLength(_factory).I32); Assert.Equal(value, new string(MemoryMarshal.Cast(objectSpan.SliceStringData(_factory).Bits))); @@ -73,7 +72,7 @@ public void IntArray() // Verify type Assert.Equal( - _factory.ContextModule.CorLibTypeFactory.Int32.MakeSzArrayType(), + _factory.CorLibTypeFactory.Int32.MakeSzArrayType(), _factory.ClrMockMemory.MethodTables.GetObject(objectSpan.SliceObjectMethodTable(_factory).I64), Comparer); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Heap/StaticFieldStorageTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Heap/StaticFieldStorageTest.cs index 11e21990..d0bf1245 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Heap/StaticFieldStorageTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Heap/StaticFieldStorageTest.cs @@ -17,7 +17,7 @@ public StaticFieldStorageTest(MockModuleFixture fixture) { _fixture = fixture; - _factory = new ValueFactory(fixture.MockModule, false); + _factory = new ValueFactory(fixture.MockModule.RuntimeContext!, false); _storage = new StaticFieldStorage(_factory, 0x0100_0000); } @@ -49,7 +49,7 @@ public void GetSpanOfPrimitiveShouldReflectSize() [Fact] public void GetSpanOfObjectShouldReflectPointer() { - var objectFIeld = new FieldDefinition("ObjectFIeld", FieldAttributes.Static, + var objectFIeld = new FieldDefinition("ObjectField", FieldAttributes.Static, _fixture.MockModule.CorLibTypeFactory.Object); var intSpan = _storage.GetFieldSpan(objectFIeld); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Invocation/MethodInvokerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Invocation/MethodInvokerTest.cs index 001f1ef9..270fa15c 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Invocation/MethodInvokerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Invocation/MethodInvokerTest.cs @@ -22,7 +22,7 @@ public MethodInvokerTest(MockModuleFixture fixture) { _fixture = fixture; - var machine = new CilVirtualMachine(fixture.MockModule, false); + var machine = new CilVirtualMachine(fixture.MockModule.RuntimeContext!, false); var thread = machine.CreateThread(); _context = new CilExecutionContext(thread, CancellationToken.None); _context.Thread.CallStack.Push(fixture.MockModule.GetOrCreateModuleConstructor()); @@ -244,7 +244,7 @@ public void DelegateInvokeOnUnknownBackingMethod() public void InternString() { var invoker = StringInvoker.Instance; - var stringType = _fixture.MockModule.CorLibTypeFactory.String.Type.Resolve()!; + var stringType = _fixture.MockModule.CorLibTypeFactory.String.Type.Resolve(_fixture.MockModule.RuntimeContext); var internMethod = stringType.Methods.First(m => m.Name == "Intern"); const string str = "Hello, world!"; @@ -264,7 +264,7 @@ public void InternString() public void InternSameStringTwiceReturnsSameAddress() { var invoker = StringInvoker.Instance; - var stringType = _fixture.MockModule.CorLibTypeFactory.String.Type.Resolve()!; + var stringType = _fixture.MockModule.CorLibTypeFactory.String.Type.Resolve(_fixture.MockModule.RuntimeContext); var internMethod = stringType.Methods.First(m => m.Name == "Intern"); const string str = "Hello, world!"; @@ -288,7 +288,7 @@ public void InternSameStringTwiceReturnsSameAddress() public void IsInternedOnInternedString() { var invoker = StringInvoker.Instance; - var stringType = _fixture.MockModule.CorLibTypeFactory.String.Type.Resolve()!; + var stringType = _fixture.MockModule.CorLibTypeFactory.String.Type.Resolve(_fixture.MockModule.RuntimeContext); var internMethod = stringType.Methods.First(m => m.Name == "Intern"); var isInternedMethod = stringType.Methods.First(m => m.Name == "IsInterned"); @@ -315,7 +315,7 @@ public void IsInternedOnInternedString() public void IsInternedOnNonInternedString() { var invoker = StringInvoker.Instance; - var stringType = _fixture.MockModule.CorLibTypeFactory.String.Type.Resolve()!; + var stringType = _fixture.MockModule.CorLibTypeFactory.String.Type.Resolve(_fixture.MockModule.RuntimeContext); var isInternedMethod = stringType.Methods.First(m => m.Name == "IsInterned"); const string str = "Never interned"; @@ -329,7 +329,7 @@ public void IsInternedOnNonInternedString() private sealed class TestDelegateUnknownResolver(IMethodDescriptor method) : ThrowUnknownResolver { - public override IMethodDescriptor? ResolveDelegateTarget( + public override IMethodDescriptor ResolveDelegateTarget( CilExecutionContext context, ObjectHandle delegateObject, IList arguments) diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Invocation/StringAllocatorTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Invocation/StringAllocatorTest.cs index 84d82d54..8b4f6b10 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Invocation/StringAllocatorTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Invocation/StringAllocatorTest.cs @@ -22,20 +22,20 @@ public class StringAllocatorTest : IClassFixture public StringAllocatorTest(MockModuleFixture fixture) { - var machine = new CilVirtualMachine(fixture.MockModule, false); + var machine = new CilVirtualMachine(fixture.MockModule.RuntimeContext!, false); var thread = machine.CreateThread(); _context = new CilExecutionContext(thread, CancellationToken.None); _context.Thread.CallStack.Push(fixture.MockModule.GetOrCreateModuleConstructor()); _corlibFactory = fixture.MockModule.CorLibTypeFactory; - _stringType = _corlibFactory.String.Type.Resolve()!; + _stringType = _corlibFactory.String.Type.Resolve(fixture.MockModule.RuntimeContext!); } [Fact] public void UsingCharArrayConstructorNull() { // Locate .ctor(char[]) - var ctor = _stringType.GetConstructor(_corlibFactory.Char.MakeSzArrayType())!; + var ctor = _stringType.GetConstructor([_corlibFactory.Char.MakeSzArrayType()])!; // Allocate using null pointer. var result = _allocator.Allocate(_context, ctor, [_context.Machine.ValueFactory.CreateNull()]); @@ -59,7 +59,7 @@ public void UsingCharArrayConstructorNonNull() array.WriteArrayData(MemoryMarshal.Cast(data)); // Allocate string using .ctor(char[]) - var ctor = _stringType.GetConstructor(_corlibFactory.Char.MakeSzArrayType())!; + var ctor = _stringType.GetConstructor([_corlibFactory.Char.MakeSzArrayType()])!; var result = _allocator.Allocate(_context, ctor, [ _context.Machine.ValueFactory.CreateNativeInteger(array.Address) ]); @@ -88,11 +88,11 @@ public void UsingCharArrayConstructorSized() array.WriteArrayData(MemoryMarshal.Cast(data)); // Allocate string using .ctor(char[], int32, int32) - var ctor = _stringType.GetConstructor( + var ctor = _stringType.GetConstructor([ _corlibFactory.Char.MakeSzArrayType(), _corlibFactory.Int32, _corlibFactory.Int32 - )!; + ])!; var result = _allocator.Allocate(_context, ctor, [ _context.Machine.ValueFactory.CreateNativeInteger(array.Address), new BitVector(startIndex), @@ -119,7 +119,7 @@ public void UsingCharPointerConstructor() _context.Machine.Memory.Write(address, MemoryMarshal.Cast(data)); // Allocate string using .ctor(char*) - var ctor = _stringType.GetConstructor(_corlibFactory.Char.MakePointerType())!; + var ctor = _stringType.GetConstructor([_corlibFactory.Char.MakePointerType()])!; var result = _allocator.Allocate(_context, ctor, [_context.Machine.ValueFactory.CreateNativeInteger(address)]); // Verify. @@ -143,11 +143,11 @@ public void UsingCharPointerConstructorSized() _context.Machine.Memory.Write(address, MemoryMarshal.Cast(data)); // Allocate string using .ctor(char*, int32, int32) - var ctor = _stringType.GetConstructor( + var ctor = _stringType.GetConstructor([ _corlibFactory.Char.MakePointerType(), _corlibFactory.Int32, _corlibFactory.Int32 - )!; + ])!; var result = _allocator.Allocate(_context, ctor, [ _context.Machine.ValueFactory.CreateNativeInteger(address), new BitVector(startIndex), @@ -170,7 +170,7 @@ public void UsingCharPointerConstructorWithUnknownBits() long address = _context.Machine.Heap.AllocateFlat(20, false); // Attempt to allocate string using .ctor(char*) - var ctor = _stringType.GetConstructor(_corlibFactory.Char.MakePointerType())!; + var ctor = _stringType.GetConstructor([_corlibFactory.Char.MakePointerType()])!; Assert.ThrowsAny(() => { _allocator.Allocate(_context, ctor, [_context.Machine.ValueFactory.CreateNativeInteger(address)]); @@ -188,7 +188,7 @@ public void UsingCharPointerConstructorWithUnknownBitsBounded() )); // Allocate string using .ctor(char*) - var ctor = _stringType.GetConstructor(_corlibFactory.Char.MakePointerType())!; + var ctor = _stringType.GetConstructor([_corlibFactory.Char.MakePointerType()])!; var result = _allocator.Allocate(_context, ctor, [_context.Machine.ValueFactory.CreateNativeInteger(address)]); // Verify @@ -209,7 +209,7 @@ public void UsingSBytePointerConstructor() _context.Machine.Memory.Write(address, data); // Allocate string using .ctor(sbyte*) - var ctor = _stringType.GetConstructor(_corlibFactory.SByte.MakePointerType())!; + var ctor = _stringType.GetConstructor([_corlibFactory.SByte.MakePointerType()])!; var result = _allocator.Allocate(_context, ctor, [_context.Machine.ValueFactory.CreateNativeInteger(address)]); // Verify. @@ -233,11 +233,11 @@ public void UsingSbytePointerConstructorSized() _context.Machine.Memory.Write(address, data); // Allocate string using .ctor(sbyte*, int32, int32) - var ctor = _stringType.GetConstructor( + var ctor = _stringType.GetConstructor([ _corlibFactory.SByte.MakePointerType(), _corlibFactory.Int32, _corlibFactory.Int32 - )!; + ])!; var result = _allocator.Allocate(_context, ctor, [ _context.Machine.ValueFactory.CreateNativeInteger(address), new BitVector(startIndex), @@ -257,7 +257,7 @@ public void UsingSbytePointerConstructorSized() public void UsingCharInt32Constructor() { // Allocate string using .ctor(char, int32) - var ctor = _stringType.GetConstructor(_corlibFactory.Char, _corlibFactory.Int32)!; + var ctor = _stringType.GetConstructor([_corlibFactory.Char, _corlibFactory.Int32])!; var result = _allocator.Allocate(_context, ctor, [ new BitVector('A'), new BitVector(30) diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/ObjectMarshallerTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/ObjectMarshallerTest.cs index 06861997..44c3e0ec 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/ObjectMarshallerTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/ObjectMarshallerTest.cs @@ -1,4 +1,3 @@ -using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; @@ -20,7 +19,7 @@ public class ObjectMarshallerTest : IClassFixture public ObjectMarshallerTest(MockModuleFixture fixture) { _fixture = fixture; - _machine = new CilVirtualMachine(fixture.MockModule, false); + _machine = new CilVirtualMachine(fixture.MockModule.RuntimeContext!, false); } [Theory] @@ -76,7 +75,7 @@ public void SerializeObjectShouldReturnProperObjectReference() var type = handle.GetObjectType(); Assert.Equal(nameof(SimpleClass), type.Name); - var definition = type.Resolve()!; + var definition = type.Resolve(_machine.RuntimeContext); var intField = definition.Fields.First(f => f.Name == nameof(SimpleClass.IntField)); var stringField = definition.Fields.First(f => f.Name == nameof(SimpleClass.StringField)); var simpleClassField = definition.Fields.First(f => f.Name == nameof(SimpleClass.SimpleClassField)); @@ -107,13 +106,16 @@ public void SerializeGenericTypeShouldRetainGenerics() var handle = _machine.ObjectMarshaller.ToBitVector(obj).AsObjectHandle(_machine); var type = handle.GetObjectType(); - var genericInstanceTypeSignature = Assert.IsType(type.ToTypeSignature()); + var genericInstanceTypeSignature = Assert.IsType(type.ToTypeSignature(_machine.RuntimeContext)); // Ensure name of the base generic type matches our reflection type name Assert.Equal(obj.GetType().Name, genericInstanceTypeSignature.GenericType.Name); // Ensure type arguments are correct - Assert.Equal(genericInstanceTypeSignature.TypeArguments, [_machine.ContextModule.CorLibTypeFactory.Int32, _machine.ContextModule.CorLibTypeFactory.String]); + Assert.Equal( + genericInstanceTypeSignature.TypeArguments, + [_machine.ValueFactory.CorLibTypeFactory.Int32, _machine.ValueFactory.CorLibTypeFactory.String] + ); } [Fact] @@ -123,9 +125,9 @@ public void SerializeInt32Array() var result = _machine.ObjectMarshaller.ToBitVector(array).AsObjectHandle(_machine); - var elementType = _machine.ContextModule.CorLibTypeFactory.Int32; + var elementType = _machine.ValueFactory.CorLibTypeFactory.Int32; - Assert.Equal(elementType.MakeSzArrayType(), result.GetObjectType().ToTypeSignature(), SignatureComparer.Default); + Assert.Equal(elementType.MakeSzArrayType(), result.GetObjectType().ToTypeSignature(_machine.RuntimeContext), SignatureComparer.Default); Assert.Equal(array.Length, result.ReadArrayLength().AsSpan().I32); Assert.All(Enumerable.Range(0, array.Length), i => { @@ -171,7 +173,7 @@ public void DeserializeInjectedObjectShouldReturnSameObject() [Fact] public void DeserializeInt32Array() { - var elementType = _machine.ContextModule.CorLibTypeFactory.Int32; + var elementType = _machine.ValueFactory.CorLibTypeFactory.Int32; var handle = _machine.Heap.AllocateSzArray(elementType, 10, true).AsObjectHandle(_machine); for (int i = 0; i < 10; i++) diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/CallFrameTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/CallFrameTest.cs index 5793b6e6..16c13ec1 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/CallFrameTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/CallFrameTest.cs @@ -16,7 +16,7 @@ public class CallFrameTest : IClassFixture public CallFrameTest(MockModuleFixture fixture) { _fixture = fixture; - _factory = new ValueFactory(fixture.CurrentTestModule, false); + _factory = new ValueFactory(fixture.CurrentTestModule.RuntimeContext!, false); } [Theory] diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/CallStackTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/CallStackTest.cs index d4b55792..b568dee6 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/CallStackTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/CallStackTest.cs @@ -16,7 +16,7 @@ public class VirtualStackTest : IClassFixture public VirtualStackTest(MockModuleFixture fixture) { _fixture = fixture; - _factory = new ValueFactory(fixture.CurrentTestModule, false); + _factory = new ValueFactory(fixture.CurrentTestModule.RuntimeContext!, false); } [Fact] diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/ExceptionHandlerFrameTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/ExceptionHandlerFrameTest.cs index ef0d3846..9fb60da7 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/ExceptionHandlerFrameTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/ExceptionHandlerFrameTest.cs @@ -20,7 +20,7 @@ public class ExceptionHandlerFrameTest : IClassFixture public ExceptionHandlerFrameTest(MockModuleFixture fixture) { _fixture = fixture; - _vm = new CilVirtualMachine(_fixture.MockModule, false); + _vm = new CilVirtualMachine(_fixture.MockModule.RuntimeContext!, false); _mainThread = _vm.CreateThread(); } @@ -73,12 +73,11 @@ public void RegisterExceptionShouldJumpToFirstCompatibleException(Type exception { var exception = _vm.ObjectMarshaller.ToObjectHandle(Activator.CreateInstance(exceptionType)); var frame = GetMockFrame(nameof(TestClass.TryCatchCatch)).ExceptionHandlers[0]; - - Assert.Equal(new[] - { - "System.IO.IOException", - "System.Net.WebException" - }, frame.Handlers.Select(x=>x.ExceptionType!.FullName)); + + Assert.Equal( + ["System.IO.IOException", "System.Net.WebException"], + frame.Handlers.Select(x => x.ExceptionType!.FullName) + ); int? offset = frame.RegisterException(exception); if (expectedIndex.HasValue) @@ -91,12 +90,11 @@ public void RegisterExceptionShouldJumpToFirstCompatibleException(Type exception public void RegisterExceptionInCatchClauseShouldReturnNull() { var frame = GetMockFrame(nameof(TestClass.TryCatchSpecificAndGeneral)).ExceptionHandlers[0]; - - Assert.Equal(new[] - { - "System.IO.EndOfStreamException", - "System.IO.IOException" - }, frame.Handlers.Select(x=>x.ExceptionType!.FullName)); + + Assert.Equal( + ["System.IO.EndOfStreamException", "System.IO.IOException"], + frame.Handlers.Select(x => x.ExceptionType!.FullName) + ); Assert.True(frame.RegisterException(_vm.ObjectMarshaller.ToObjectHandle(new EndOfStreamException())).HasValue); Assert.False(frame.RegisterException(_vm.ObjectMarshaller.ToObjectHandle(new IOException())).HasValue); diff --git a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/ExceptionHandlerStackTest.cs b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/ExceptionHandlerStackTest.cs index 1067cd49..c2392212 100644 --- a/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/ExceptionHandlerStackTest.cs +++ b/test/Platforms/Echo.Platforms.AsmResolver.Tests/Emulation/Stack/ExceptionHandlerStackTest.cs @@ -24,7 +24,7 @@ public class ExceptionHandlerStackTest : IClassFixture public ExceptionHandlerStackTest(MockModuleFixture fixture) { _fixture = fixture; - _vm = new CilVirtualMachine(_fixture.MockModule, false); + _vm = new CilVirtualMachine(_fixture.MockModule.RuntimeContext!, false); _mainThread = _vm.CreateThread(); }