Exemplo n.º 1
0
        /// <summary>
        /// The return value for the randomly generated method. It can be an integer or a string.
        /// </summary>
        private static MethodDef CreateReturnMethodDef(object value, ModuleDefMD module)
        {
            CorLibTypeSig corlib = null;

            if (value is int)
            {
                corlib = module.CorLibTypes.Int32;
            }
            else if (value is string)
            {
                corlib = module.CorLibTypes.String;
            }

            MethodDef newMethod = new MethodDefUser(GenerateRandomString(MemberRenamer.StringLength()),
                                                    MethodSig.CreateStatic(corlib, corlib),
                                                    MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                                    MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig)
            {
                Body = new CilBody()
            };

            if (value is int)
            {
                newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4, Convert.ToInt32(value)));
            }
            else if (value is string)
            {
                newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, value.ToString()));
            }
            newMethod.Body.Instructions.Add(OpCodes.Ret.ToInstruction());

            return(newMethod);
        }
Exemplo n.º 2
0
        /// <summary>
        /// We are making the return value for the randomly generated method. The return value can be an Integer, a Double or a String.
        /// </summary>
        public static MethodDef CreateReturnMethodDef(object value, MethodDef source_method)
        {
            CorLibTypeSig corlib = null;

            if (value is int)
            {
                corlib = source_method.Module.CorLibTypes.Int32;
            }
            else if (value is string)
            {
                corlib = source_method.Module.CorLibTypes.String;
            }
            MethodDef newMethod = new MethodDefUser(GenerateRandomString(50),
                                                    MethodSig.CreateStatic(corlib),
                                                    MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                                    MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig)
            {
                Body = new CilBody()
            };

            if (value is int)
            {
                newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4, (int)value));
            }
            else if (value is string)
            {
                newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, (string)value));
            }
            newMethod.Body.Instructions.Add(new Instruction(OpCodes.Ret));
            return(newMethod);
        }
Exemplo n.º 3
0
 public ArrayInfo(int start, int len, CorLibTypeSig arrayType, int arySize, int index)
 {
     this.start     = start;
     this.len       = len;
     this.arrayType = arrayType;
     this.arySize   = arySize;
     this.index     = index;
 }
Exemplo n.º 4
0
        private static MethodDef CreateReturnMethodDef(object value, MethodDef source_method)
        {
            CorLibTypeSig corlib = null;

            if (value is int)
            {
                corlib = source_method.Module.CorLibTypes.Int64;
            }
            else if (value is float)
            {
                corlib = source_method.Module.CorLibTypes.Single;
            }
            else if (value is string)
            {
                corlib = source_method.Module.CorLibTypes.String;
            }
            MethodDef newMethod = new MethodDefUser(RndString(), MethodSig.CreateStatic(corlib), MethodImplAttributes.IL | MethodImplAttributes.Managed, MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig)
            {
                Body = new CilBody()
            };

            if (value is int)
            {
                newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4, (int)value));
            }
            else if (value is float)
            {
                newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_R4, (double)value));
            }
            else if (value is string)
            {
                newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, (string)value));
            }
            //          foreach (TypeDef type in newMethod.Module.Types)
            //        {
            //             foreach (MethodDef method in type.Methods)
            //             {
            //                for (int i = 0; i < method.Body.Instructions.Count; i++)
            //               {
            //                  if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr)
            //                  {
            //                      String oldString = method.Body.Instructions[i].Operand.ToString();
            //                     String newString = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(oldString));
            //                     method.Body.Instructions[i].OpCode = OpCodes.Nop;
            //                      method.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Call, newMethod.Module.Import(typeof(System.Text.Encoding).GetMethod("get_UTF8", new Type[] { }))));
            //                     method.Body.Instructions.Insert(i + 2, new Instruction(OpCodes.Ldstr, newString));
            //                     method.Body.Instructions.Insert(i + 3, new Instruction(OpCodes.Call, newMethod.Module.Import(typeof(System.Convert).GetMethod("FromBase64String", new Type[] { typeof(string) }))));
            //                    method.Body.Instructions.Insert(i + 4, new Instruction(OpCodes.Callvirt, newMethod.Module.Import(typeof(System.Text.Encoding).GetMethod("GetString", new Type[] { typeof(byte[]) }))));
            //                    i += 4;
            //              }
            //          }
            //      }
            //   }
            newMethod.Body.Instructions.Add(new Instruction(OpCodes.Ret));
            return(newMethod);
        }
Exemplo n.º 5
0
        public static MethodDef newfunc(ModuleDefUser mod, string name, CorLibTypeSig returntype, TypeSig[] arguments)
        {
            MethodDefUser newfunction = new MethodDefUser(name, MethodSig.CreateStatic(returntype, arguments));

            newfunction.Attributes     = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            newfunction.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed | MethodImplAttributes.AggressiveOptimization;
            startUpType.Methods.Add(newfunction);
            newfunction.Body = new CilBody();
            return(newfunction);
        }
Exemplo n.º 6
0
        // Token: 0x060000F3 RID: 243 RVA: 0x0001434C File Offset: 0x0001254C
        private static MethodDef CreateReturnMethodDef(string value, MethodDef source_method)
        {
            CorLibTypeSig @string   = source_method.Module.CorLibTypes.String;
            MethodDef     methodDef = new MethodDefUser("BlinkObfuscator", MethodSig.CreateStatic(@string), MethodImplAttributes.IL, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.Static | MethodAttributes.HideBySig)
            {
                Body = new CilBody()
            };

            methodDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, value));
            methodDef.Body.Instructions.Add(new Instruction(OpCodes.Ret));
            return(methodDef);
        }
Exemplo n.º 7
0
        private static MethodDef CreateReturnMethodDef(string value, MethodDef source_method)
        {
            CorLibTypeSig corlib    = source_method.Module.CorLibTypes.String;
            MethodDef     newMethod = new MethodDefUser("Goldfuscation",
                                                        MethodSig.CreateStatic(corlib),
                                                        MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                                        MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig)
            {
                Body = new CilBody()
            };

            newMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, value));
            newMethod.Body.Instructions.Add(new Instruction(OpCodes.Ret));
            return(newMethod);
        }
Exemplo n.º 8
0
            public void Compile(CFContext ctx)
            {
                var var    = new Variable("{VAR}");
                var result = new Variable("{RESULT}");

                CorLibTypeSig int32 = ctx.Method.Module.CorLibTypes.Int32;

                native = new MethodDefUser(ctx.Context.Registry.GetService <INameService>().RandomName(), MethodSig.CreateStatic(int32, int32), MethodAttributes.PinvokeImpl | MethodAttributes.PrivateScope | MethodAttributes.Static);
                native.ImplAttributes = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig;
                // Attempt to improve performance --- failed with StackOverflowException... :/
                // les 3 en dessous sont nrml cachés avec //
                var suppressAttr = ctx.Method.Module.CorLibTypes.GetTypeRef("System.Security", "SuppressUnmanagedCodeSecurityAttribute").ResolveThrow();

                native.CustomAttributes.Add(new CustomAttribute((MemberRef)ctx.Method.Module.Import(suppressAttr.FindDefaultConstructor())));
                native.HasSecurity = true;
                ctx.Method.Module.GlobalType.Methods.Add(native);

                ctx.Context.Registry.GetService <IMarkerService>().Mark(native, ctx.Protection);
                ctx.Context.Registry.GetService <INameService>().SetCanRename(native, false);

                x86Register?reg;
                var         codeGen = new x86CodeGen();

                do
                {
                    ctx.DynCipher.GenerateExpressionPair(
                        ctx.Random,
                        new VariableExpression {
                        Variable = var
                    }, new VariableExpression {
                        Variable = result
                    },
                        ctx.Depth, out expression, out inverse);

                    reg = codeGen.GenerateX86(inverse, (v, r) => { return(new[] { x86Instruction.Create(x86OpCode.POP, new x86RegisterOperand(r)) }); });
                } while (reg == null);

                code = CodeGenUtils.AssembleCode(codeGen, reg.Value);

                expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
                              .GenerateCIL(expression)
                              .Compile <Func <int, int> >();


                ctx.Context.CurrentModuleWriterListener.OnWriterEvent += InjectNativeCode;
            }
Exemplo n.º 9
0
        void Compile(RPContext ctx, out Func <int, int> expCompiled, out MethodDef native)
        {
            var var    = new Variable("{VAR}");
            var result = new Variable("{RESULT}");

            CorLibTypeSig int32 = ctx.Module.CorLibTypes.Int32;

            native = new MethodDefUser(ctx.Context.Registry.GetService <INameService>().RandomName(), MethodSig.CreateStatic(int32, int32), MethodAttributes.PinvokeImpl | MethodAttributes.PrivateScope | MethodAttributes.Static);
            native.ImplAttributes = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig;
            ctx.Module.GlobalType.Methods.Add(native);

            ctx.Context.Registry.GetService <IMarkerService>().Mark(native, ctx.Protection);
            ctx.Context.Registry.GetService <INameService>().SetCanRename(native, false);

            x86Register?reg;
            var         codeGen = new x86CodeGen();
            Expression  expression, inverse;

            do
            {
                ctx.DynCipher.GenerateExpressionPair(
                    ctx.Random,
                    new VariableExpression {
                    Variable = var
                }, new VariableExpression {
                    Variable = result
                },
                    ctx.Depth, out expression, out inverse);

                reg = codeGen.GenerateX86(inverse, (v, r) => { return(new[] { x86Instruction.Create(x86OpCode.POP, new x86RegisterOperand(r)) }); });
            } while (reg == null);

            byte[] code = CodeGenUtils.AssembleCode(codeGen, reg.Value);

            expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
                          .GenerateCIL(expression)
                          .Compile <Func <int, int> >();

            nativeCodes.Add(Tuple.Create(native, code, (MethodBody)null));
            if (!addedHandler)
            {
                ctx.Context.CurrentModuleWriterListener.OnWriterEvent += InjectNativeCode;
                addedHandler = true;
            }
        }
Exemplo n.º 10
0
            public void Compile(CEContext ctx)
            {
                var var    = new Variable("{VAR}");
                var result = new Variable("{RESULT}");

                CorLibTypeSig int32 = ctx.Module.CorLibTypes.Int32;

                native = new MethodDefUser("", MethodSig.CreateStatic(int32, int32), MethodAttributes.PinvokeImpl | MethodAttributes.PrivateScope | MethodAttributes.Static);
                native.ImplAttributes = MethodImplAttributes.Native | MethodImplAttributes.Unmanaged | MethodImplAttributes.PreserveSig;
                ctx.Module.GlobalType.Methods.Add(native);

                ctx.Name.MarkHelper(native, ctx.Marker, ctx.Protection);

                x86Register?reg;
                var         codeGen = new x86CodeGen();

                do
                {
                    ctx.DynCipher.GenerateExpressionPair(
                        ctx.Random,
                        new VariableExpression {
                        Variable = var
                    }, new VariableExpression {
                        Variable = result
                    },
                        4, out expression, out inverse);

                    reg = codeGen.GenerateX86(inverse, (v, r) => { return(new[] { x86Instruction.Create(x86OpCode.POP, new x86RegisterOperand(r)) }); });
                } while (reg == null);

                code = CodeGenUtils.AssembleCode(codeGen, reg.Value);

                expCompiled = new DMCodeGen(typeof(int), new[] { Tuple.Create("{VAR}", typeof(int)) })
                              .GenerateCIL(expression)
                              .Compile <Func <int, int> >();


                ctx.Context.CurrentModuleWriterListener.OnWriterEvent += InjectNativeCode;
            }
Exemplo n.º 11
0
        void Initialize()
        {
            bool isCorLib = module.Assembly.IsCorLib();

            typeVoid           = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Void"), ElementType.Void);
            typeBoolean        = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Boolean"), ElementType.Boolean);
            typeChar           = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Char"), ElementType.Char);
            typeSByte          = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "SByte"), ElementType.I1);
            typeByte           = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Byte"), ElementType.U1);
            typeInt16          = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Int16"), ElementType.I2);
            typeUInt16         = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "UInt16"), ElementType.U2);
            typeInt32          = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Int32"), ElementType.I4);
            typeUInt32         = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "UInt32"), ElementType.U4);
            typeInt64          = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Int64"), ElementType.I8);
            typeUInt64         = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "UInt64"), ElementType.U8);
            typeSingle         = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Single"), ElementType.R4);
            typeDouble         = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Double"), ElementType.R8);
            typeString         = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "String"), ElementType.String);
            typeTypedReference = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "TypedReference"), ElementType.TypedByRef);
            typeIntPtr         = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "IntPtr"), ElementType.I);
            typeUIntPtr        = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "UIntPtr"), ElementType.U);
            typeObject         = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Object"), ElementType.Object);
        }
        private void Compile(RPContext ctx, out Func <int, int> expCompiled, out MethodDef native)
        {
            x86Register?  nullable;
            Expression    expression;
            Variable      variable  = new Variable("{VAR}");
            Variable      variable2 = new Variable("{RESULT}");
            CorLibTypeSig retType   = ctx.Module.CorLibTypes.Int32;

            native = new MethodDefUser(ctx.Context.Registry.GetService <INameService>().RandomName(), MethodSig.CreateStatic(retType, retType), MethodAttributes.CompilerControlled | MethodAttributes.PinvokeImpl | MethodAttributes.Static);
            native.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.ManagedMask | MethodImplAttributes.Native | MethodImplAttributes.PreserveSig;
            ctx.Module.GlobalType.Methods.Add(native);
            ctx.Context.Registry.GetService <IMarkerService>().Mark(native, ctx.Protection);
            ctx.Context.Registry.GetService <INameService>().SetCanRename(native, false);
            x86CodeGen codeGen = new x86CodeGen();

            do
            {
                Expression         expression2;
                VariableExpression var = new VariableExpression {
                    Variable = variable
                };
                VariableExpression result = new VariableExpression {
                    Variable = variable2
                };
                ctx.DynCipher.GenerateExpressionPair(ctx.Random, var, result, ctx.Depth, out expression, out expression2);
                nullable = codeGen.GenerateX86(expression2, (v, r) => new x86Instruction[] { x86Instruction.Create(x86OpCode.POP, new Ix86Operand[] { new x86RegisterOperand(r) }) });
            }while (!nullable.HasValue);
            byte[] buffer = CodeGenUtils.AssembleCode(codeGen, nullable.Value);
            expCompiled = new DMCodeGen(typeof(int), new Tuple <string, Type>[] { Tuple.Create <string, Type>("{VAR}", typeof(int)) }).GenerateCIL(expression).Compile <Func <int, int> >();
            this.nativeCodes.Add(Tuple.Create <MethodDef, byte[], dnlib.DotNet.Writer.MethodBody>(native, buffer, null));
            if (!this.addedHandler)
            {
                ctx.Context.CurrentModuleWriterListener.OnWriterEvent += new EventHandler <ModuleWriterListenerEventArgs>(this.InjectNativeCode);
                this.addedHandler = true;
            }
        }
Exemplo n.º 13
0
 /// <summary>
 /// Creates a new instruction with a type operand
 /// </summary>
 /// <param name="type">The type</param>
 /// <returns>A new <see cref="Instruction"/> instance</returns>
 public Instruction ToInstruction(CorLibTypeSig type) => Instruction.Create(this, type.TypeDefOrRef);
Exemplo n.º 14
0
        private string injectDeepTrace(List <string> MethodToken, string assemblyPath, string outputDirectory, bool WithTrace = false)
        {
            AssemblyDef asmDef;

            // New assembly path
            string fileName = Path.GetFileName(assemblyPath);

            // Append Date and Time to new filename
            string newPath = Path.Combine(outputDirectory, DateTime.UtcNow.ToString("yyyy-MM-dd HH.mm.ss.fff", CultureInfo.InvariantCulture) + "_" + fileName);

            // Check if Output directory already exists, if not, create one
            if (!Directory.Exists(outputDirectory))
            {
                try
                {
                    Directory.CreateDirectory(outputDirectory);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.ToString());
                    MainWindow.Instance.mBox("Injector Exception", ex.ToString());
                }
            }

            try
            {
                // AssemblyResolver
                if (_AssmeblyResolver == null)
                {
                    _AssmeblyResolver = new AssemblyResolver();
                }
                if (Directory.Exists(Path.GetDirectoryName(assemblyPath)))
                {
                    AddSearchPath(Path.GetDirectoryName(assemblyPath));
                }

                // how to use AssemblyResolver with dnLib?
                //_AssmeblyResolver

                // Load assembly
                //asmDef = AssemblyDef.Load(assemblyPath);
                ModuleDefMD mod = ModuleDefMD.Load(assemblyPath);

                // import our pritObj Class
                Importer      importer         = new Importer(mod);
                Type          PrintObjType     = typeof(PrintObj);
                ITypeDefOrRef _printObjTypeRef = importer.Import(PrintObjType);

                // This creates a new namespace Logging and class PrintObj in the new assembly, we don't want that
                //TypeDef _printObj = new TypeDefUser("Logging", "PrintObj", mod.CorLibTypes.Object.TypeDefOrRef);
                //var _printObjCtor = _printObj.FindDefaultConstructor();
                //mod.Types.Add(_printObj);



                Type    t          = typeof(System.Reflection.MethodBase);
                string  methodname = "GetCurrentMethod";
                IMethod _methodGetCurrentMethod = importer.Import(t.GetMethod(methodname));

                methodname = "set_CurrentMethod";
                IMethod _methodSetMethod = importer.Import(PrintObjType.GetMethod(methodname));


                t          = typeof(System.Reflection.Assembly);
                methodname = "GetExecutingAssembly";
                IMethod _methodGetExecutingAssembly = importer.Import(t.GetMethod(methodname));

                methodname = "set_CurrentAssembly";
                IMethod _methodSetExecutingAssembly = importer.Import(PrintObjType.GetMethod(methodname));


                methodname = "get_CurrentArguments";
                IMethod _methodGetArguments = importer.Import(PrintObjType.GetMethod(methodname));

                methodname = "set_CurrentArguments";
                IMethod _methodSetArguments = importer.Import(PrintObjType.GetMethod(methodname));

                methodname = "PrintArgs";
                IMethod _methodPrintArgs = importer.Import(PrintObjType.GetMethod(methodname));

                methodname = ".ctor";
                IMethod _printObjCtor = importer.Import(PrintObjType.GetMethod(methodname));

                foreach (ModuleDef modDef in mod.Assembly.Modules)
                {
                    foreach (TypeDef typDef in modDef.Types)
                    {
                        foreach (MethodDef metDef in typDef.Methods)
                        {
                            //if (MethodToken.Contains(metDef.MDToken.ToString()) && metDef.Name == "About1_Closed")
                            if (MethodToken.Contains(metDef.MDToken.ToString()))
                            {
                                if (WithTrace)
                                {
                                    Trace.WriteLine("Found method " + metDef.ToString() + " Token: " + metDef.MDToken.ToString());
                                }

                                try
                                {
                                    string variablesInfo = string.Empty;
                                    if (metDef.Body != null && metDef.Body.Variables != null && metDef.Body.Variables.Count > 0)
                                    {
                                        foreach (var variable in metDef.Body.Variables)
                                        {
                                            string varInfo = "            Variable - Type: " + variable.Type.ToString() + " Name: " + variable.Name + NewLine;
                                            varInfo += "            Index: " + variable.Index.ToString();
                                            if (WithTrace)
                                            {
                                                Trace.WriteLine(varInfo);
                                            }
                                            variablesInfo += varInfo;
                                        }
                                    }

                                    /*
                                     * if we want to skip anything
                                     * if (metDef.IsConstructor ||
                                     *  metDef.IsAbstract ||
                                     *  metDef.IsSetter ||
                                     *  (metDef.IsSpecialName && !metDef.IsGetter) || // to allow getter methods
                                     *  metDef.IsInstanceConstructor ||
                                     *  metDef.IsManaged == false
                                     *  )
                                     * {
                                     *  if (WithTrace) Trace.WriteLine("Skipped unsupported metDef " + metDef.Name);
                                     * }
                                     * else if (metDef != null && metDef.Body != null)
                                     */

                                    if (metDef != null && metDef.Body != null)
                                    {
                                        var instructions    = metDef.Body.Instructions;
                                        var newInstructions = new List <Instruction>();

                                        Instruction firstExistingInstruction        = metDef.Body.Instructions[0];
                                        uint        firstExistingInstrunctionOffset = firstExistingInstruction.Offset;
                                        int         fIndex = (int)firstExistingInstrunctionOffset; // not working

                                        // nop Test
                                        //instructions.Insert((int)firstExistingInstruction.Offset, new Instruction(OpCodes.Nop));
                                        //instructions.Insert((int)firstExistingInstruction.Offset, new Instruction(OpCodes.Nop));

                                        ///
                                        /// Simple TraceLine
                                        ///

                                        // Load fully qualified method name as string
                                        //not working: (int)firstExistingInstruction.Offset

                                        //newInstructions.Add(new Instruction(OpCodes.Ldstr, metDef.ToString() + variablesInfo));
                                        //newInstructions.Add(new Instruction(OpCodes.Call, metDef.Module.Import(typeof(Trace).GetMethod("WriteLine", new[] { typeof(string) }))));



                                        ///
                                        /// PrintObj (injected Logging.dll)
                                        /// extended by using code and comments from CInject
                                        /// https://codeinject.codeplex.com/
                                        ///

                                        /*
                                         * 0	0000	nop
                                         * 1	0001	newobj	instance void [Logging]Logging.PrintObj::.ctor()
                                         * 2	0006	stloc	V_0 (0)
                                         * 3	000A	ldloc	V_0 (0)
                                         * 4	000E	call	class [mscorlib]System.Reflection.MethodBase [mscorlib]System.Reflection.MethodBase::GetCurrentMethod()
                                         * 5	0013	callvirt	instance void [Logging]Logging.PrintObj::set_CurrentMethod(class [mscorlib]System.Reflection.MethodBase)
                                         * 6	0018	nop
                                         * 7	0019	ldloc.s	V_0 (0)
                                         * 8	001B	ldc.i4	2
                                         * 9	0020	newarr	[mscorlib]System.Object
                                         * 10	0025	stloc.s	V_1 (1)
                                         * 11	0027	ldloc.s	V_1 (1)
                                         * 12	0029	ldc.i4	0
                                         * 13	002E	ldarg	sender (1)
                                         * 14	0032	box	[mscorlib]System.Object
                                         * 15	0037	stelem.ref
                                         * 16	0038	ldloc.s	V_1 (1)
                                         * 17	003A	ldc.i4	1
                                         * 18	003F	ldarg	e (2)
                                         * 19	0043	stelem.ref
                                         * 20	0044	ldloc.s	V_1 (1)
                                         * 21	0046	callvirt	instance void [Logging]Logging.PrintObj::set_CurrentArguments(object[])
                                         * 22	004B	ldloc.s	V_0 (0)
                                         * 23	004D	callvirt	instance void [Logging]Logging.PrintObj::PrintArgs()
                                         * 24	0052	nop
                                         *
                                         */

                                        // Add new variables
                                        metDef.Body.InitLocals = true;

                                        Local printO = new Local(_printObjTypeRef.ToTypeSig());
                                        metDef.Body.Variables.Add(printO);



                                        var   objType    = mod.CorLibTypes.Object.ToTypeDefOrRef();
                                        var   objTypeArr = importer.Import(typeof(object[]));
                                        Local oArray     = new Local(objTypeArr.ToTypeSig());
                                        metDef.Body.Variables.Add(oArray);


                                        newInstructions.Add(new Instruction(OpCodes.Nop));

                                        // using MemberRef cTor will create the logging.PrintObj: new Logging.PrintObj()
                                        var objectCtor = new MemberRefUser(mod, ".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void), _printObjTypeRef);
                                        newInstructions.Add(new Instruction(OpCodes.Newobj, objectCtor));



                                        newInstructions.Add(OpCodes.Stloc.ToInstruction(printO));
                                        newInstructions.Add(OpCodes.Ldloc.ToInstruction(printO));

                                        newInstructions.Add(new Instruction(OpCodes.Call, _methodGetCurrentMethod));
                                        newInstructions.Add(new Instruction(OpCodes.Callvirt, _methodSetMethod));

                                        newInstructions.Add(new Instruction(OpCodes.Nop));

                                        newInstructions.Add(new Instruction(OpCodes.Ldloc_S, printO));

                                        // DNlib counts additionally hidden "this"
                                        List <Parameter> pList = new List <Parameter>();
                                        for (int i = 0; i < metDef.Parameters.Count; i++)
                                        {
                                            if (!metDef.Parameters[i].IsHiddenThisParameter)
                                            {
                                                pList.Add(metDef.Parameters[i]);
                                            }
                                        }

                                        newInstructions.Add(new Instruction(OpCodes.Ldc_I4, pList.Count));


                                        newInstructions.Add(new Instruction(OpCodes.Newarr, objType));
                                        newInstructions.Add(new Instruction(OpCodes.Stloc_S, oArray));


                                        //for (int i = 0; i < metDef.Parameters.Count; i++)
                                        for (int i = 0; i < pList.Count; i++)
                                        {
                                            if (WithTrace)
                                            {
                                                Trace.WriteLine("Found Parameter " + pList[i].Name.ToString());
                                            }

                                            bool processAsNormal = true;

                                            //if (metDef.Parameters[i].Type.IsByRef)
                                            if (pList[i].Type.IsByRef)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsByRef) " + pList[i].Name.ToString());
                                                }

                                                //* Sample Instruction set:
                                                //* L_002a: ldloc.2
                                                //* L_002b: ldc.i4.0
                                                //* L_002c: ldarg.1
                                                //* L_002d: ldind.ref
                                                //* L_002e: stelem.ref
                                                //*

                                                newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                                newInstructions.Add(new Instruction(OpCodes.Ldc_I4, i));

                                                newInstructions.Add(new Instruction(OpCodes.Ldarg, pList[i]));
                                                newInstructions.Add(new Instruction(OpCodes.Ldind_Ref));
                                                newInstructions.Add(new Instruction(OpCodes.Stelem_Ref));

                                                processAsNormal = false;
                                            }
                                            //else if (pList[i].IsHiddenThisParameter)
                                            //{
                                            //processAsNormal = false;
                                            //}

                                            else if (pList[i].Type.IsClassSig)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsClassSig) " + pList[i].Name.ToString() + " Type: " + pList[i].Type + " Type.ReflectionFullName: " + pList[i].Type.ReflectionFullName);
                                                }

                                                newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                                newInstructions.Add(new Instruction(OpCodes.Ldc_I4, i));
                                                newInstructions.Add(new Instruction(OpCodes.Ldarg, pList[i]));
                                                //newInstructions.Add(new Instruction(OpCodes.Box, pList[i].Type)); // causing System.InvalidCastException: Type "dnlib.DotNet.ClassSig" cannot be converted to Type "dnlib.DotNet.TypeSpec"

                                                ClassSig cSig = new ClassSig(pList[i].Type.ToTypeDefOrRef());
                                                Trace.WriteLine("(IsClassSig) cSig: " + cSig.ToString());

                                                newInstructions.Add(new Instruction(OpCodes.Stelem_Ref));

                                                processAsNormal = false;
                                            }
                                            else if (pList[i].Type.IsCorLibType)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsCorLibType) " + pList[i].Name.ToString() + " Type: " + pList[i].Type + " Type.ReflectionFullName: " + pList[i].Type.ReflectionFullName);
                                                }
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsCorLibType...) " + " ElementType: " + pList[i].Type.ElementType + " Type.FullName: " + pList[i].Type.FullName);
                                                }
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsCorLibType...) " + " Module: " + pList[i].Type.Module + " Type.Next: " + pList[i].Type.Next);
                                                }
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsCorLibType...) " + " ReflectionName: " + pList[i].Type.ReflectionName + " Type.ReflectionNamespace: " + pList[i].Type.ReflectionNamespace);
                                                }
                                                newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                                newInstructions.Add(new Instruction(OpCodes.Ldc_I4, i));
                                                newInstructions.Add(new Instruction(OpCodes.Ldarg, pList[i]));

                                                //newInstructions.Add(new Instruction(OpCodes.Box, pList[i].Type)); // causing System.InvalidCastException: Type "dnlib.DotNet.CorLibTypeSig" cannot be converted to Type "dnlib.DotNet.TypeSpec"
                                                //newInstructions.Add(new Instruction(OpCodes.Box, mod.CorLibTypes.Int32)); // working for Int32 as example
                                                CorLibTypeSig cLibTypeSig = new CorLibTypeSig(pList[i].Type.ToTypeDefOrRef(), pList[i].Type.ElementType);
                                                newInstructions.Add(OpCodes.Box.ToInstruction(cLibTypeSig));

                                                newInstructions.Add(new Instruction(OpCodes.Stelem_Ref));

                                                processAsNormal = false;
                                            }


                                            //else if (metDef.Parameters[i].ParameterType.IsArray)
                                            //{

                                            //}
                                            //else if (metDef.Parameters[i].ParameterType.IsDefinition) // delegate needs no seperate handling
                                            //{

                                            //}
                                            //else if (metDef.Parameters[i].Type.IsFunctionPointer)
                                            else if (pList[i].Type.IsFunctionPointer)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsFunctionPointer) " + pList[i].Name.ToString());
                                                }
                                            }

                                            //else if (metDef.Parameters[i].ParameterType.IsOptionalModifier)
                                            //{

                                            //}
                                            //else if (metDef.Parameters[i].Type.IsPointer)
                                            else if (pList[i].Type.IsPointer)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("(IsPointer) " + pList[i].Name.ToString());
                                                }
                                            }
                                            else
                                            {
                                                processAsNormal = true;
                                            }

                                            //if (processAsNormal && !metDef.Parameters[i].Type.IsClassSig && !metDef.Parameters[i].Type.IsCorLibType)
                                            if (processAsNormal)
                                            {
                                                if (WithTrace)
                                                {
                                                    Trace.WriteLine("processAsNormal: " + pList[i].Name.ToString());
                                                }

                                                // Sample Instruction set: for simple PARAMETER
                                                //* L_0036: ldloc.s objArray
                                                //* L_0038: ldc.i4 0
                                                //* L_003d: ldarg array
                                                //* L_0041: box Int32    <-------------- anything can be here
                                                //* L_0046: stelem.ref


                                                // Sample Instruction set: for ARRAY
                                                // L_0036: ldloc.s objArray
                                                // L_0038: ldc.i4 0
                                                // L_003d: ldarg array
                                                // L_0041: box string[]
                                                // L_0046: stelem.ref


                                                newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                                newInstructions.Add(new Instruction(OpCodes.Ldc_I4, i));
                                                newInstructions.Add(new Instruction(OpCodes.Ldarg, metDef.Parameters[i]));
                                                newInstructions.Add(new Instruction(OpCodes.Box, pList[i].Type));
                                                newInstructions.Add(new Instruction(OpCodes.Stelem_Ref));
                                            }
                                        }

                                        // fill Arguments array
                                        newInstructions.Add(new Instruction(OpCodes.Ldloc_S, oArray));
                                        newInstructions.Add(new Instruction(OpCodes.Callvirt, _methodSetArguments));

                                        // call PrintArgs
                                        newInstructions.Add(new Instruction(OpCodes.Ldloc_S, printO));
                                        newInstructions.Add(new Instruction(OpCodes.Callvirt, _methodPrintArgs));


                                        // Finally add instructions to beginning
                                        for (int j = 0; j < newInstructions.Count; j++)
                                        {
                                            instructions.Insert(j, newInstructions[j]);
                                        }
                                    }
                                    else
                                    {
                                        if (WithTrace)
                                        {
                                            Trace.WriteLine("metDef or metDef.Body was null");
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Debug.WriteLine(ex.ToString());
                                    MainWindow.Instance.mBox("Injector Exception", ex.ToString());
                                }
                            }
                        }
                    }
                }


                // Save modified assembly
                //asmDef.Write(newPath);

                var wopts = new dnlib.DotNet.Writer.ModuleWriterOptions(mod);
                wopts.WritePdb = true;

                //write assembly
                if (mod.IsILOnly)
                {
                    mod.Write(newPath);
                }
                else
                {
                    mod.NativeWrite(newPath);
                }
            }
            catch (Exception ex)
            {
                if (WithTrace)
                {
                    Trace.WriteLine(DateTime.Now + " injectDeepTrace exception: " + ex.ToString());
                }

                return(DateTime.Now + " injectDeepTrace exception: " + ex.ToString());
            }

            InjectedFile = newPath;
            Text         = "Injector finished: " + newPath;

            return(newPath);
        }
Exemplo n.º 15
0
 /// <summary>
 /// Creates a new instruction with a type operand
 /// </summary>
 /// <param name="type">The type</param>
 /// <returns>A new <see cref="Instruction"/> instance</returns>
 public Instruction ToInstruction(CorLibTypeSig type)
 {
     return(Instruction.Create(this, type.TypeDefOrRef));
 }
 public virtual CorLibTypeSig Transform(CorLibTypeSig token, ITransformContext context) => token;
Exemplo n.º 17
0
		/// <summary>
		/// Creates a new instruction with a type operand
		/// </summary>
		/// <param name="opCode">The opcode</param>
		/// <param name="type">The type</param>
		/// <returns>A new <see cref="Instruction"/> instance</returns>
		public static Instruction Create(OpCode opCode, CorLibTypeSig type) {
			return Create(opCode, type.TypeDefOrRef);
		}
Exemplo n.º 18
0
		/// <summary>
		/// Creates a new instruction with a type operand
		/// </summary>
		/// <param name="type">The type</param>
		/// <returns>A new <see cref="Instruction"/> instance</returns>
		public Instruction ToInstruction(CorLibTypeSig type) {
			return Instruction.Create(this, type.TypeDefOrRef);
		}
Exemplo n.º 19
0
		void Initialize() {
			bool isCorLib = module.Assembly.IsCorLib();
			typeVoid	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Void"),		ElementType.Void);
			typeBoolean	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Boolean"),	ElementType.Boolean);
			typeChar	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Char"),		ElementType.Char);
			typeSByte	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "SByte"),		ElementType.I1);
			typeByte	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Byte"),		ElementType.U1);
			typeInt16	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Int16"),		ElementType.I2);
			typeUInt16	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "UInt16"),	ElementType.U2);
			typeInt32	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Int32"),		ElementType.I4);
			typeUInt32	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "UInt32"),	ElementType.U4);
			typeInt64	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Int64"),		ElementType.I8);
			typeUInt64	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "UInt64"),	ElementType.U8);
			typeSingle	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Single"),	ElementType.R4);
			typeDouble	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Double"),	ElementType.R8);
			typeString	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "String"),	ElementType.String);
			typeTypedReference = new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "TypedReference"), ElementType.TypedByRef);
			typeIntPtr	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "IntPtr"),	ElementType.I);
			typeUIntPtr	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "UIntPtr"),	ElementType.U);
			typeObject	= new CorLibTypeSig(CreateCorLibTypeRef(isCorLib, "Object"),	ElementType.Object);
		}
Exemplo n.º 20
0
        public MethodDef CreateReturnMethodDef(object constantvalue, MethodDef source_method)
        {
            CorLibTypeSig corlib = null;

            if (constantvalue is int)
            {
                corlib = source_method.Module.CorLibTypes.Int32;
            }
            else
            {
                if (constantvalue is Instruction)
                {
                    var abecede = constantvalue as Instruction;
                    constantvalue = abecede.Operand;
                }
            }
            if (constantvalue is float)
            {
                corlib = source_method.Module.CorLibTypes.Single;
            }
            if (constantvalue is string)
            {
                corlib = source_method.Module.CorLibTypes.String;
            }

            var meth = new MethodDefUser("_" + source_method.Name + "_" + constantvalue.ToString(),
                                         MethodSig.CreateStatic(corlib),
                                         MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                         MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig)
            {
                Body = new CilBody()
            };

            Local return_value = new Local(corlib);

            meth.Body.Variables.Add(return_value);

            //Method body
            meth.Body.Instructions.Add(OpCodes.Nop.ToInstruction());
            if (constantvalue is int)
            {
                meth.Body.Instructions.Add((int)constantvalue != 0
                    ? Instruction.Create(OpCodes.Ldc_I4, (Int32)constantvalue)
                    : Instruction.Create(OpCodes.Ldc_I4_0));
            }
            if (constantvalue is float)
            {
                meth.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_R4, (Single)constantvalue));
            }
            if (constantvalue is string)
            {
                meth.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, (string)constantvalue));
            }
            meth.Body.Instructions.Add(OpCodes.Stloc_0.ToInstruction());
            var test_ldloc = new Instruction(OpCodes.Ldloc_0);

            meth.Body.Instructions.Add(test_ldloc);
            meth.Body.Instructions.Add(OpCodes.Ret.ToInstruction());
            Instruction target = meth.Body.Instructions[3];

            meth.Body.Instructions.Insert(3, Instruction.Create(OpCodes.Br_S, target));
            return(meth);
        }
Exemplo n.º 21
0
 public Instruction Create(OpCode op, CorLibTypeSig v)
 {
     return(op.ToInstruction(v));
 }
Exemplo n.º 22
0
 public ILProcessor Emit(OpCode op, CorLibTypeSig v)
 {
     return(Append(op.ToInstruction(v)));
 }
Exemplo n.º 23
0
        protected static MethodSig CreateProxySignature(RPContext ctx, IMethod method, bool newObj)
        {
            Func <TypeSig, TypeSig> selector = null;
            Func <TypeSig, TypeSig> func2    = null;
            ModuleDef module = ctx.Module;

            if (newObj)
            {
                TypeSig sig;
                if (selector == null)
                {
                    selector = delegate(TypeSig type) {
                        if ((ctx.TypeErasure && type.IsClassSig) && method.MethodSig.HasThis)
                        {
                            return(module.CorLibTypes.Object);
                        }
                        return(type);
                    };
                }
                TypeSig[] argTypes = method.MethodSig.Params.Select <TypeSig, TypeSig>(selector).ToArray <TypeSig>();
                if (ctx.TypeErasure)
                {
                    sig = module.CorLibTypes.Object;
                }
                else
                {
                    TypeDef typeDef = method.DeclaringType.ResolveTypeDefThrow();
                    sig = Import(ctx, typeDef).ToTypeSig();
                }
                return(MethodSig.CreateStatic(sig, argTypes));
            }
            if (func2 == null)
            {
                func2 = delegate(TypeSig type) {
                    if ((ctx.TypeErasure && type.IsClassSig) && method.MethodSig.HasThis)
                    {
                        return(module.CorLibTypes.Object);
                    }
                    return(type);
                };
            }
            IEnumerable <TypeSig> second = method.MethodSig.Params.Select <TypeSig, TypeSig>(func2);

            if (method.MethodSig.HasThis && !method.MethodSig.ExplicitThis)
            {
                TypeDef def2 = method.DeclaringType.ResolveTypeDefThrow();
                if (ctx.TypeErasure && !def2.IsValueType)
                {
                    second = new CorLibTypeSig[] { module.CorLibTypes.Object }.Concat <TypeSig>(second);
                }
                else
                {
                    second = new TypeSig[] { Import(ctx, def2).ToTypeSig() }.Concat <TypeSig>(second);
                }
            }
            TypeSig retType = method.MethodSig.RetType;

            if (ctx.TypeErasure && retType.IsClassSig)
            {
                retType = module.CorLibTypes.Object;
            }
            return(MethodSig.CreateStatic(retType, second.ToArray <TypeSig>()));
        }
Exemplo n.º 24
0
 public Instructions Emit(OpCode opCode, CorLibTypeSig value)
 {
     return(Insert(Instruction.Create(opCode, value)));
 }
 public override CorLibTypeSig Transform(CorLibTypeSig token, ITransformContext context) => context.SearchContext.Get(importer.Import(token));
Exemplo n.º 26
0
        public static void Emit(this ICollection <Instruction> instructions, OpCode opCode, CorLibTypeSig type)
        {
            var instruction = Instruction.Create(opCode, type);

            instructions.Add(instruction);
        }
Exemplo n.º 27
0
 /// <summary>
 /// Creates a new instruction with a type operand
 /// </summary>
 /// <param name="opCode">The opcode</param>
 /// <param name="type">The type</param>
 /// <returns>A new <see cref="Instruction"/> instance</returns>
 public static Instruction Create(OpCode opCode, CorLibTypeSig type)
 {
     return(Create(opCode, type.TypeDefOrRef));
 }
Exemplo n.º 28
0
 /// <summary>
 /// Tries the relocate the <see cref="CorLibTypeSig"/>.
 /// </summary>
 /// <param name="corLibTypeSig">The cor library type sig.</param>
 /// <returns></returns>
 protected virtual TypeSig TryRelocateCorLibTypeSig(CorLibTypeSig corLibTypeSig)
 {
     return(null);
 }