Пример #1
0
        public void NewStandaloneSignature()
        {
            var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);

            // Import arbitrary method signature.
            var importer  = new ReferenceImporter(module);
            var signature = new StandAloneSignature(
                importer.ImportMethodSignature(MethodSignature.CreateStatic(module.CorLibTypeFactory.Void)));

            // Ensure reference is added to the module by referencing it in main.
            var instructions = module.ManagedEntrypointMethod.CilMethodBody.Instructions;

            instructions.Insert(0, CilOpCodes.Ldnull);
            instructions.Insert(0, CilOpCodes.Calli, signature);

            // Rebuild.
            var builder = new ManagedPEImageBuilder();
            var result  = builder.CreateImage(module);

            // Assert valid token.
            var newToken = result.TokenMapping[signature];

            Assert.NotEqual(0u, newToken.Rid);

            // Assert token resolves to the same method reference.
            var newModule    = ModuleDefinition.FromImage(result.ConstructedImage);
            var newSignature = (StandAloneSignature)newModule.LookupMember(newToken);

            Assert.Equal(signature.Signature, newSignature.Signature, new SignatureComparer());
        }
Пример #2
0
        public void NewMethodDefinition()
        {
            var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);

            // Create new method.
            var method = new MethodDefinition(
                "MyMethod",
                MethodAttributes.Public | MethodAttributes.Static,
                MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));

            module.GetOrCreateModuleType().Methods.Add(method);

            // Get existing main method.
            var main = module.ManagedEntrypointMethod;

            // Rebuild.
            var builder = new ManagedPEImageBuilder();
            var result  = builder.CreateImage(module);

            // Assert valid tokens for both methods.
            var methodToken     = result.TokenMapping[method];
            var mainMethodToken = result.TokenMapping[main];

            Assert.NotEqual(0u, methodToken.Rid);
            Assert.NotEqual(0u, mainMethodToken.Rid);

            // Assert tokens resolve to the same methods.
            var newModule = ModuleDefinition.FromImage(result.ConstructedImage);
            var newMethod = (MethodDefinition)newModule.LookupMember(methodToken);

            Assert.Equal(method.Name, newMethod.Name);
            var newMain = (MethodDefinition)newModule.LookupMember(mainMethodToken);

            Assert.Equal(main.Name, newMain.Name);
        }
Пример #3
0
        public DispatcherTestBase(MockModuleFixture moduleFixture)
        {
            ModuleFixture = moduleFixture;
            const bool is32Bit = false;

            var dummyModule = moduleFixture.GetModule();
            var dummyMethod = new MethodDefinition(
                "MockMethod",
                MethodAttributes.Static,
                MethodSignature.CreateStatic(dummyModule.CorLibTypeFactory.Void));

            dummyMethod.CilMethodBody = new CilMethodBody(dummyMethod);

            var environment = new MockCilRuntimeEnvironment(dummyModule, is32Bit)
            {
                Architecture = new CilArchitecture(dummyMethod.CilMethodBody),
            };

            var methodInvoker = new ReturnUnknownMethodInvoker(environment.ValueFactory);

            environment.MethodInvoker = new HookedMethodInvoker(methodInvoker);

            var container = new ServiceContainer();

            container.AddService(typeof(ICilRuntimeEnvironment), environment);

            Dispatcher       = new CilDispatcher();
            ExecutionContext = new CilExecutionContext(
                container,
                new CilProgramState(environment.ValueFactory),
                default);
        }
        private CilInstructionCollection CreateDummyMethod(bool hasThis, int paramCount, int localCount)
        {
            var flags = hasThis
                ? MethodAttributes.Public
                : MethodAttributes.Public | MethodAttributes.Static;

            var parameterTypes = Enumerable.Repeat <TypeSignature>(_module.CorLibTypeFactory.Object, paramCount);

            var signature = hasThis
                ? MethodSignature.CreateInstance(_module.CorLibTypeFactory.Void, parameterTypes)
                : MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void, parameterTypes);

            var method = new MethodDefinition("Dummy", flags, signature);

            var body = new CilMethodBody(method);

            for (int i = 0; i < localCount; i++)
            {
                body.LocalVariables.Add(new CilLocalVariable(_module.CorLibTypeFactory.Object));
            }

            method.MethodBody = body;

            return(body.Instructions);
        }
Пример #5
0
        public void ComputeMaxStackOnBuildOverride(bool computeMaxStack, bool?computeMaxStackOverride, int expectedMaxStack)
        {
            const int maxStack = 100;

            var module = new ModuleDefinition("SomeModule", KnownCorLibs.SystemPrivateCoreLib_v4_0_0_0);
            var main   = new MethodDefinition(
                "Main",
                MethodAttributes.Public | MethodAttributes.Static,
                MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));

            main.CilMethodBody = new CilMethodBody(main)
            {
                ComputeMaxStackOnBuild = computeMaxStack,
                MaxStack       = maxStack,
                Instructions   = { new CilInstruction(CilOpCodes.Ret) },
                LocalVariables = { new CilLocalVariable(module.CorLibTypeFactory.Int32) } // Force fat method body.
            };

            module.GetOrCreateModuleType().Methods.Add(main);
            module.ManagedEntrypoint = main;

            var builder = new ManagedPEImageBuilder(new DotNetDirectoryFactory
            {
                MethodBodySerializer = new CilMethodBodySerializer
                {
                    ComputeMaxStackOnBuildOverride = computeMaxStackOverride
                }
            });

            var newImage  = builder.CreateImage(module);
            var newModule = ModuleDefinition.FromImage(newImage);

            Assert.Equal(expectedMaxStack, newModule.ManagedEntrypointMethod.CilMethodBody.MaxStack);
        }
Пример #6
0
        private static CilMethodBody CreateDummyBody(bool isVoid)
        {
            var module = new ModuleDefinition("DummyModule");
            var method = new MethodDefinition("Main",
                                              MethodAttributes.Static,
                                              MethodSignature.CreateStatic(isVoid ? module.CorLibTypeFactory.Void : module.CorLibTypeFactory.Int32));

            module.GetOrCreateModuleType().Methods.Add(method);
            return(method.CilMethodBody = new CilMethodBody(method));
        }
Пример #7
0
        public void ImportMethodFromExternalModuleShouldResultInMemberRef()
        {
            var type   = new TypeReference(_dummyAssembly, null, "Type");
            var method = new MemberReference(type, "Method",
                                             MethodSignature.CreateStatic(_module.CorLibTypeFactory.String));

            var result = _importer.ImportMethod(method);

            Assert.Equal(method, result, _comparer);
            Assert.Same(_module, result.Module);
        }
        public void RetInNonVoidMethodShouldPopOneElement()
        {
            var method = new MethodDefinition("Method", MethodAttributes.Static,
                                              MethodSignature.CreateStatic(_module.CorLibTypeFactory.Int32));

            method.CilMethodBody = new CilMethodBody(method);

            var instruction = new CilInstruction(CilOpCodes.Ret);

            Assert.Equal(1, instruction.GetStackPopCount(method.CilMethodBody));
        }
        public void NopShouldPopZeroElements()
        {
            var method = new MethodDefinition("Method", MethodAttributes.Static,
                                              MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void));

            method.CilMethodBody = new CilMethodBody(method);

            var instruction = new CilInstruction(CilOpCodes.Nop);

            Assert.Equal(0, instruction.GetStackPopCount(method.CilMethodBody));
        }
Пример #10
0
        public void InstantiateMethodSignatureWithGenericReturnType()
        {
            var signature = MethodSignature.CreateStatic(
                new GenericParameterSignature(GenericParameterType.Type, 0));

            var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null);

            var newSignature = signature.InstantiateGenericTypes(context);

            Assert.Equal(MethodSignature.CreateStatic(
                             _module.CorLibTypeFactory.String
                             ), newSignature, Comparer);
        }
        public void ResolveConsoleWriteLineMethod()
        {
            var module = new ModuleDefinition("SomeModule.dll");

            var consoleType     = new TypeReference(module.CorLibTypeFactory.CorLibScope, "System", "Console");
            var writeLineMethod = new MemberReference(consoleType, "WriteLine",
                                                      MethodSignature.CreateStatic(module.CorLibTypeFactory.Void, module.CorLibTypeFactory.String));

            var definition = _fwResolver.ResolveMethod(writeLineMethod);

            Assert.NotNull(definition);
            Assert.Equal(writeLineMethod.Name, definition.Name);
            Assert.Equal(writeLineMethod.Signature, definition.Signature, _comparer);
        }
        public void CallInstanceWithZeroParametersShouldPopOneElement()
        {
            var method = new MethodDefinition("Method", MethodAttributes.Static,
                                              MethodSignature.CreateStatic(_module.CorLibTypeFactory.Int32));

            method.CilMethodBody = new CilMethodBody(method);

            var type   = new TypeReference(_module, null, "SomeType");
            var member = new MemberReference(type, "SomeMethod",
                                             MethodSignature.CreateInstance(_module.CorLibTypeFactory.Void));

            var instruction = new CilInstruction(CilOpCodes.Call, member);

            Assert.Equal(1, instruction.GetStackPopCount(method.CilMethodBody));
        }
Пример #13
0
        public void ImportMethodFromSameModuleShouldResultInSameInstance()
        {
            var type = new TypeDefinition(null, "Type", TypeAttributes.Public);

            _module.TopLevelTypes.Add(type);

            var method = new MethodDefinition("Method", MethodAttributes.Public | MethodAttributes.Static,
                                              MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void));

            type.Methods.Add(method);

            var result = _importer.ImportMethod(method);

            Assert.Same(method, result);
        }
        private static PropertyDefinition CreateDummyProperty(TypeDefinition dummyType, string name)
        {
            var property = new PropertyDefinition(name, 0,
                                                  PropertySignature.CreateStatic(dummyType.Module.CorLibTypeFactory.Object));

            var getMethod = new MethodDefinition($"get_{property.Name}", MethodAttributes.Public | MethodAttributes.Static,
                                                 MethodSignature.CreateStatic(dummyType.Module.CorLibTypeFactory.Object));

            getMethod.CilMethodBody = new CilMethodBody(getMethod)
            {
                Instructions = { new CilInstruction(CilOpCodes.Ldnull), new CilInstruction(CilOpCodes.Ret) }
            };

            dummyType.Methods.Add(getMethod);
            property.Semantics.Add(new MethodSemantics(getMethod, MethodSemanticsAttributes.Getter));
            return(property);
        }
Пример #15
0
        public void AssignTokenToNewUnusedMemberReferenceShouldPreserveAfterBuild()
        {
            var module    = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);
            var reference = new MemberReference(
                new TypeReference(module, module, "SomeNamespace", "SomeType"),
                "SomeMethod",
                MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));

            module.TokenAllocator.AssignNextAvailableToken(reference);

            var image     = module.ToPEImage(new ManagedPEImageBuilder(MetadataBuilderFlags.PreserveMemberReferenceIndices));
            var newModule = ModuleDefinition.FromImage(image);

            var newReference = (MemberReference)newModule.LookupMember(reference.MetadataToken);

            Assert.Equal(reference.Name, newReference.Name);
        }
Пример #16
0
        public void InstantiateMethodSignatureWithGenericSentinelParameterType()
        {
            var signature = MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void);

            signature.IncludeSentinel = true;
            signature.SentinelParameterTypes.Add(new GenericParameterSignature(GenericParameterType.Type, 0));

            var context = new GenericContext(GetProvider(_module.CorLibTypeFactory.String), null);

            var newSignature = signature.InstantiateGenericTypes(context);

            var expected = MethodSignature.CreateStatic(_module.CorLibTypeFactory.Void);

            expected.IncludeSentinel = true;
            expected.SentinelParameterTypes.Add(_module.CorLibTypeFactory.String);

            Assert.Equal(expected, newSignature, Comparer);
        }
Пример #17
0
        private static MethodDefinition CreateDummyMethod(ModuleDefinition module, string name, int parameterCount)
        {
            var method = new MethodDefinition(name,
                                              MethodAttributes.Public | MethodAttributes.Static,
                                              MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));

            method.CilMethodBody = new CilMethodBody(method);
            method.CilMethodBody.Instructions.Add(new CilInstruction(CilOpCodes.Ret));

            for (int i = 0; i < parameterCount; i++)
            {
                method.Signature.ParameterTypes.Add(module.CorLibTypeFactory.Object);
                method.ParameterDefinitions.Add(new ParameterDefinition((ushort)(i + 1), $"arg_{i}", 0));
            }

            method.Parameters.PullUpdatesFromMethodSignature();
            return(method);
        }
        public MethodSemanticsCollectionTest()
        {
            var module = new ModuleDefinition("Module");

            _property = new PropertyDefinition("Property", 0,
                                               PropertySignature.CreateStatic(module.CorLibTypeFactory.Int32));

            _property2 = new PropertyDefinition("Property2", 0,
                                                PropertySignature.CreateStatic(module.CorLibTypeFactory.Int32));

            _getMethod = new MethodDefinition("get_Property",
                                              MethodAttributes.Public | MethodAttributes.Static,
                                              MethodSignature.CreateStatic(module.CorLibTypeFactory.Int32));

            _setMethod = new MethodDefinition("set_Property",
                                              MethodAttributes.Public | MethodAttributes.Static,
                                              MethodSignature.CreateStatic(module.CorLibTypeFactory.Void, module.CorLibTypeFactory.Int32));
        }
Пример #19
0
        public void ExceptionHandlerWithHandlerEndOutsideOfMethod()
        {
            // https://github.com/Washi1337/Echo/issues/101

            // Set up test case.
            var module = new ModuleDefinition("Module");
            var method = new MethodDefinition("MyMethod", MethodAttributes.Static,
                                              MethodSignature.CreateStatic(module.CorLibTypeFactory.Void));
            var body         = method.CilMethodBody = new CilMethodBody(method);
            var instructions = body.Instructions;

            var start        = new CilInstructionLabel();
            var tryStart     = new CilInstructionLabel();
            var handlerStart = new CilInstructionLabel();

            start.Instruction    = instructions.Add(CilOpCodes.Nop);
            tryStart.Instruction = instructions.Add(CilOpCodes.Nop);
            instructions.Add(CilOpCodes.Leave_S, start);
            handlerStart.Instruction = instructions.Add(CilOpCodes.Pop);
            instructions.Add(CilOpCodes.Leave_S, start);

            body.ExceptionHandlers.Add(new CilExceptionHandler
            {
                ExceptionType = module.CorLibTypeFactory.Object.ToTypeDefOrRef(),
                TryStart      = tryStart,
                TryEnd        = handlerStart,
                HandlerStart  = handlerStart,
                HandlerEnd    = instructions.EndLabel // Use end label.
            });

            instructions.CalculateOffsets();

            // Construct CFG.
            var cfg = body.ConstructStaticFlowGraph();

            // Verify handler exists.
            Assert.NotNull(cfg);
            Assert.Equal(3, cfg.Nodes.Count);
            var region = Assert.Single(cfg.Regions);
            var eh     = Assert.IsAssignableFrom <ExceptionHandlerRegion <CilInstruction> >(region);

            Assert.Single(eh.Handlers);
        }
        private static EventDefinition CreateDummyEventToType(TypeDefinition dummyType, ITypeDefOrRef eventHandlerTypeRef, string name)
        {
            var eventHandlerTypeSig = eventHandlerTypeRef.ToTypeSignature();

            // Define new event.
            var @event = new EventDefinition(name, 0, eventHandlerTypeRef);

            // Create signature for add/remove methods.
            var signature = MethodSignature.CreateStatic(
                eventHandlerTypeRef.Module.CorLibTypeFactory.Void,
                eventHandlerTypeRef.Module.CorLibTypeFactory.Object,
                eventHandlerTypeSig);

            var methodAttributes = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.SpecialName
                                   | MethodAttributes.HideBySig;

            // Define add.
            var addMethod = new MethodDefinition($"add_{@event.Name}", methodAttributes, signature);

            addMethod.CilMethodBody = new CilMethodBody(addMethod)
            {
                Instructions = { new CilInstruction(CilOpCodes.Ret) }
            };

            // Define remove.
            var removeMethod = new MethodDefinition($"remove_{@event.Name}", methodAttributes, signature);

            removeMethod.CilMethodBody = new CilMethodBody(removeMethod)
            {
                Instructions = { new CilInstruction(CilOpCodes.Ret) }
            };

            // Add members.
            dummyType.Methods.Add(addMethod);
            dummyType.Methods.Add(removeMethod);

            @event.Semantics.Add(new MethodSemantics(addMethod, MethodSemanticsAttributes.AddOn));
            @event.Semantics.Add(new MethodSemantics(removeMethod, MethodSemanticsAttributes.RemoveOn));

            return(@event);
        }
Пример #21
0
        /// <summary>
        /// Do Proxy Signature.
        /// </summary>
        /// <param name="IsNewobj"> Ditermine If The Processed Instruction Is CilOpCodes.NewObj. </param>
        /// <param name="Method"> Method to Call. </param>
        /// <returns> Proxy Method Sig. </returns>
        private static MethodSignature GetSignature(bool IsNewobj, IMethodDescriptor Method)
        {
            // Get Return Type.
            var _returntype = IsNewobj
                              ? Method.DeclaringType.ToTypeSignature()
                              : Method.Signature.ReturnType;
            // Assign Params Type.
            IList <TypeSignature> _params = new List <TypeSignature>();

            /// Inserting TypeSigs From <param name="Method"/> Sig.
            foreach (var _tsig in Method.Signature.ParameterTypes)
            {
                _params.Add(_tsig);
            }
            // If Method Is HasThis Insert Object Sig.
            if (Method.Signature.HasThis && !IsNewobj)
            {
                _params.Insert(0, _importer.ImportTypeSignature(Method.Resolve().Parameters.ThisParameter.ParameterType));
            }
            // Finally Return Maded Sig.
            return(MethodSignature.CreateStatic(_returntype, _params));
        }