コード例 #1
0
        public static void CreateMethodRestore(MethodDef target, MethodDef newMethod, ModuleDefMD module)
        {
            AssemblyRef dnlib          = module.GetAssemblyRef(new UTF8String("dnlib"));
            TypeRefUser Instruction    = new TypeRefUser(module, new UTF8String("dnlib"), new UTF8String("Instruction"), dnlib);
            TypeSig     instructionSig = Instruction.ToTypeSig();

            var assemblyRef = module.CorLibTypes.AssemblyRef;

            var listRef            = new TypeRefUser(module, @"System.Collections.Generic", "List`1", assemblyRef);
            var listGenericInstSig = new GenericInstSig(new ClassSig(listRef), instructionSig);

            var listTypeSpec = new TypeSpecUser(listGenericInstSig);

            var listCtor         = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), listTypeSpec);
            var instruictionCtor = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), instructionSig.TryGetTypeSpec());

            var listAdd = new MemberRefUser(module, "Add", MethodSig.CreateInstance(module.CorLibTypes.Void, new GenericVar(0)), listTypeSpec);

            // sdsd

            newMethod.Body.Instructions.Add(OpCodes.Newobj.ToInstruction(listCtor));
            newMethod.Body.Instructions.Add(OpCodes.Stloc_0.ToInstruction()); // Store list to local[0]

            /*
             * newMethod.Body.Instructions.Add(new Instruction(OpCodes.Dup));
             * newMethod.Body.Instructions.Add(new Instruction(OpCodes.Ldsfld, OpCodes.Add));
             * newMethod.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4_S, 0x37));
             * newMethod.Body.Instructions.Add(new Instruction(OpCodes.Box, module.CorLibTypes.Int32));
             * newMethod.Body.Instructions.Add(new Instruction(OpCodes.Newobj, instruictionCtor));
             * newMethod.Body.Instructions.Add(new Instruction(OpCodes.Callvirt, listAdd));
             */
        }
コード例 #2
0
        protected TypeDef CreateDelegateType(MethodSig sig)
        {
            TypeDef ret = new TypeDefUser("AsStrongAsFuck" + Runtime.GetRandomName(), Runtime.GetRandomName() + Runtime.GetChineseString(20), Module.CorLibTypes.GetTypeRef("System", "MulticastDelegate"));

            ret.Attributes = TypeAttributes.Public | TypeAttributes.Sealed;

            var ctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(Module.CorLibTypes.Void, Module.CorLibTypes.Object, Module.CorLibTypes.IntPtr));

            ctor.Attributes     = MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName;
            ctor.ImplAttributes = MethodImplAttributes.Runtime;
            ret.Methods.Add(ctor);

            var clone = sig.Clone();

            if (clone.HasThis && clone.ExplicitThis)
            {
                if (clone.Params.Count > 0)
                {
                    clone.Params.RemoveAt(0);
                }
            }


            var invoke = new MethodDefUser("Invoke", clone);

            invoke.MethodSig.HasThis = true;
            invoke.Attributes        = MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot;
            invoke.ImplAttributes    = MethodImplAttributes.Runtime;
            ret.Methods.Add(invoke);
            Module.Types.Add(ret);

            return(ret);
        }
コード例 #3
0
ファイル: RPMode.cs プロジェクト: naderr1ua/DarksProtector
        protected static TypeDef GetDelegateType(RPContext ctx, MethodSig sig)
        {
            TypeDef def;

            if (!ctx.Delegates.TryGetValue(sig, out def))
            {
                def = new TypeDefUser(ctx.Name.RandomName(), ctx.Name.RandomName(), ctx.Module.CorLibTypes.GetTypeRef("System", "MulticastDelegate"))
                {
                    Attributes = TypeAttributes.AnsiClass | TypeAttributes.Sealed
                };
                MethodDefUser item = new MethodDefUser(".ctor", MethodSig.CreateInstance(ctx.Module.CorLibTypes.Void, ctx.Module.CorLibTypes.Object, ctx.Module.CorLibTypes.IntPtr))
                {
                    Attributes     = MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName,
                    ImplAttributes = MethodImplAttributes.CodeTypeMask
                };
                def.Methods.Add(item);
                MethodDefUser user2 = new MethodDefUser("Invoke", sig.Clone())
                {
                    MethodSig      = { HasThis = true },
                    Attributes     = MethodAttributes.Assembly | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual,
                    ImplAttributes = MethodImplAttributes.CodeTypeMask
                };
                def.Methods.Add(user2);
                ctx.Module.Types.Add(def);
                foreach (IDnlibDef def2 in def.FindDefinitions())
                {
                    ctx.Marker.Mark(def2, ctx.Protection);
                    ctx.Name.SetCanRename(def2, false);
                }
                ctx.Delegates[sig] = def;
            }
            return(def);
        }
コード例 #4
0
        public void InitializePatch(ModuleDefMD module)
        {
            var importer = new Importer(module);

            // Import and store the patching methods
            var performSaveMethod      = importer.Import(typeof(SaveHelper).GetMethod("PerformSave"));
            var startSaveInvokerMethod = importer.Import(typeof(SaveHelper).GetMethod("StartSaveInvoker"));

            var playerType = module.Find("Player", false);

            var autoSaveMethod = new MethodDefUser(
                "Autosave",
                MethodSig.CreateInstance(module.CorLibTypes.Void),
                MethodImplAttributes.IL | MethodImplAttributes.Managed,
                MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.ReuseSlot
                );

            playerType.Methods.Add(autoSaveMethod);

            var body = autoSaveMethod.Body = new CilBody();

            body.Instructions.Add(OpCodes.Call.ToInstruction(performSaveMethod));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());


            var awakeMethod  = playerType.FindMethod("Awake");
            var instructions = awakeMethod.Body.Instructions;

            instructions.Insert(instructions.Count - 1, OpCodes.Ldarg_0.ToInstruction());
            instructions.Insert(instructions.Count - 1, OpCodes.Call.ToInstruction(startSaveInvokerMethod));
        }
コード例 #5
0
        MethodDef CreateMethodDef(SR.MethodBase delMethod)
        {
            bool isStatic = true;
            var  method   = new MethodDefUser();

            var retType = GetReturnType(delMethod);
            var pms     = GetParameters(delMethod);

            if (isStatic)
            {
                method.Signature = MethodSig.CreateStatic(retType, pms.ToArray());
            }
            else
            {
                method.Signature = MethodSig.CreateInstance(retType, pms.ToArray());
            }

            method.ImplAttributes = MethodImplAttributes.IL;
            method.Attributes     = MethodAttributes.PrivateScope;
            if (isStatic)
            {
                method.Attributes |= MethodAttributes.Static;
            }

            return(module.UpdateRowId(method));
        }
コード例 #6
0
        public void ProtectionPhase(Context krawk)
        {
            TypeRef attrRef  = krawk.ManifestModule.CorLibTypes.GetTypeRef("System", "Attribute");
            var     attrType = new TypeDefUser("", "Protected", attrRef);

            krawk.ManifestModule.Types.Add(attrType);
            var ctor = new MethodDefUser(
                ".ctor",
                MethodSig.CreateInstance(krawk.ManifestModule.CorLibTypes.Void, krawk.ManifestModule.CorLibTypes.String),
                MethodImplAttributes.Managed,
                MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            ctor.Body          = new CilBody();
            ctor.Body.MaxStack = 1;
            ctor.Body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            ctor.Body.Instructions.Add(OpCodes.Call.ToInstruction(new MemberRefUser(krawk.ManifestModule, ".ctor", MethodSig.CreateInstance(krawk.ManifestModule.CorLibTypes.Void), attrRef)));
            ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction());

            attrType.Methods.Add(ctor);

            var attr = new CustomAttribute(ctor);

            attr.ConstructorArguments.Add(new CAArgument(krawk.ManifestModule.CorLibTypes.String, "Krawk Protector v" + System.Reflection.Assembly.GetEntryAssembly().GetName().Version));

            krawk.ManifestModule.CustomAttributes.Add(attr);
        }
コード例 #7
0
        /// <summary>
        /// Create the DevirtualizedAttribute TypeDef, with a "default .ctor" that
        /// calls the base type's .ctor (System.Attribute).
        /// </summary>
        /// <returns>TypeDef</returns>
        TypeDef CreateDevirtualizedAttribute()
        {
            var importer         = new Importer(this.Module);
            var attributeRef     = this.Module.CorLibTypes.GetTypeRef("System", "Attribute");
            var attributeCtorRef = importer.Import(attributeRef.ResolveTypeDefThrow().FindMethod(".ctor"));

            var devirtualizedAttr = new TypeDefUser(
                "eazdevirt.Injected", "DevirtualizedAttribute", attributeRef);
            //devirtualizedAttr.Attributes = TypeAttributes.Public | TypeAttributes.AutoLayout
            //	| TypeAttributes.Class | TypeAttributes.AnsiClass;

            var emptyCtor = new MethodDefUser(".ctor", MethodSig.CreateInstance(this.Module.CorLibTypes.Void),
                                              MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                              MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName |
                                              MethodAttributes.ReuseSlot | MethodAttributes.HideBySig);

            var instructions = new List <Instruction>();

            instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            instructions.Add(OpCodes.Call.ToInstruction(attributeCtorRef));             // Call the constructor .ctor
            instructions.Add(OpCodes.Ret.ToInstruction());
            emptyCtor.Body = new CilBody(false, instructions, new List <ExceptionHandler>(), new List <Local>());

            devirtualizedAttr.Methods.Add(emptyCtor);

            return(devirtualizedAttr);
        }
コード例 #8
0
ファイル: Anti_ILDasm.cs プロジェクト: Jomtek/koala
        // Token: 0x06000056 RID: 86 RVA: 0x00005A5C File Offset: 0x00003C5C
        public static void Anti(ModuleDef md)
        {
            ModuleDef       manifestModule = md.Assembly.ManifestModule;
            TypeRef         typeRef        = manifestModule.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "SuppressIldasmAttribute");
            MemberRefUser   ctor           = new MemberRefUser(manifestModule, ".ctor", MethodSig.CreateInstance(manifestModule.CorLibTypes.Void), typeRef);
            CustomAttribute item           = new CustomAttribute(ctor);

            manifestModule.CustomAttributes.Add(item);
            TypeRef         typeRef2 = manifestModule.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "UnsafeValueTypeAttribute");
            MemberRefUser   ctor2    = new MemberRefUser(manifestModule, ".ctor", MethodSig.CreateInstance(manifestModule.CorLibTypes.Void), typeRef2);
            CustomAttribute item2    = new CustomAttribute(ctor2);

            manifestModule.CustomAttributes.Add(item2);
            TypeRef         typeRef3 = manifestModule.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "RuntimeWrappedException");
            MemberRefUser   ctor3    = new MemberRefUser(manifestModule, ".ctor", MethodSig.CreateInstance(manifestModule.CorLibTypes.Void), typeRef3);
            CustomAttribute item3    = new CustomAttribute(ctor3);

            manifestModule.CustomAttributes.Add(item3);
            TypeRef         typeRef4 = manifestModule.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "UnverifiableCodeAttribute");
            MemberRefUser   ctor4    = new MemberRefUser(manifestModule, ".ctor", MethodSig.CreateInstance(manifestModule.CorLibTypes.Void), typeRef4);
            CustomAttribute item4    = new CustomAttribute(ctor4);

            manifestModule.CustomAttributes.Add(item4);
            TypeRef         typeRef5 = manifestModule.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "SuppressUnmanagedCodeSecurity");
            MemberRefUser   ctor5    = new MemberRefUser(manifestModule, ".ctor", MethodSig.CreateInstance(manifestModule.CorLibTypes.Void), typeRef5);
            CustomAttribute item5    = new CustomAttribute(ctor5);

            manifestModule.CustomAttributes.Add(item5);
        }
コード例 #9
0
        private MethodDef CreateMethodDef(MethodBase delMethod)
        {
            bool           flag          = true;
            MethodDefUser  methodDefUser = new MethodDefUser();
            TypeSig        returnType    = this.GetReturnType(delMethod);
            List <TypeSig> parameters    = this.GetParameters(delMethod);
            bool           flag2         = flag;
            bool           flag3         = flag2;

            if (flag3)
            {
                methodDefUser.Signature = MethodSig.CreateStatic(returnType, parameters.ToArray());
            }
            else
            {
                methodDefUser.Signature = MethodSig.CreateInstance(returnType, parameters.ToArray());
            }
            methodDefUser.Parameters.UpdateParameterTypes();
            methodDefUser.ImplAttributes = dnlib.DotNet.MethodImplAttributes.IL;
            methodDefUser.Attributes     = dnlib.DotNet.MethodAttributes.PrivateScope;
            bool flag4 = flag;
            bool flag5 = flag4;

            if (flag5)
            {
                methodDefUser.Attributes |= dnlib.DotNet.MethodAttributes.Static;
            }
            return(this.module.UpdateRowId <MethodDefUser>(methodDefUser));
        }
コード例 #10
0
        /// <summary>
        /// Emits codes to add translations for existing ModTranslation instances.
        /// </summary>
        /// <param name="method">The target method.</param>
        /// <param name="propertyName">The property name of ModTranslation instance.</param>
        /// <param name="content">The translation content.</param>
        public void Emit(MethodDef method, string propertyName, string content)
        {
            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            if (method.Module != Module)
            {
                throw new ArgumentOutOfRangeException(nameof(method));
            }

            var instructions = method.Body.Instructions;

            var translationPropertyGetter = new MemberRefUser(Module, "get_" + propertyName,
                                                              MethodSig.CreateInstance(new ClassSig(_modTranslationType)),
                                                              method.DeclaringType.BaseType);

            instructions.AppendLast(new[]
            {
                OpCodes.Ldarg_0.ToInstruction(),
                OpCodes.Call.ToInstruction(translationPropertyGetter),
                OpCodes.Ldsfld.ToInstruction(_gameCultureField),
                OpCodes.Ldstr.ToInstruction(content),
                OpCodes.Callvirt.ToInstruction(_modTranslationAddTranslationMethod)
            });

            method.Body.SimplifyBranches();
            method.Body.OptimizeBranches();
        }
コード例 #11
0
ファイル: Watermark.cs プロジェクト: xuan2261/LoGiC.NET
        public static void AddAttribute()
        {
            TypeRef     attrRef  = Program.Module.CorLibTypes.GetTypeRef("System", "Attribute");
            TypeDefUser attrType = new TypeDefUser(string.Empty, "LoGiCdotNetAttribute", attrRef);

            Program.Module.Types.Add(attrType);
            MethodDefUser ctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(Program.Module
                                                                                     .CorLibTypes.Void, Program.Module.CorLibTypes.String), MethodImplAttributes.Managed,
                                                   MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName |
                                                   MethodAttributes.RTSpecialName)
            {
                Body = new CilBody {
                    MaxStack = 1
                }
            };

            ctor.Body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            ctor.Body.Instructions.Add(OpCodes.Call.ToInstruction(new MemberRefUser(Program.Module, ".ctor",
                                                                                    MethodSig.CreateInstance(Program.Module.CorLibTypes.Void), attrRef)));
            ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction());
            attrType.Methods.Add(ctor);

            CustomAttribute attr = new CustomAttribute(ctor);

            attr.ConstructorArguments.Add(new CAArgument(Program.Module.CorLibTypes.String, $"Obfuscated" +
                                                         $" with {Reference.Name} version {Reference.Version}."));
            Program.Module.CustomAttributes.Add(attr);
        }
コード例 #12
0
ファイル: AntiILDasmProtection.cs プロジェクト: v4nyl/SkiDzEX
            protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
            {
                foreach (ModuleDef module in parameters.Targets.OfType <ModuleDef>())
                {
                    TypeRef attrRef = module.CorLibTypes.GetTypeRef("", "Abarcy");
                    var     ctorRef = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef);

                    TypeRef attrRefx = module.CorLibTypes.GetTypeRef("", "AbarcyᅠProtector");
                    var     ctorRefx = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRefx);

                    TypeRef attrRefxx = module.CorLibTypes.GetTypeRef("", "ᅠᅠᅠᅠᅠᅠᅠᅠᅠᅠ");
                    var     ctorRefxx = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRefxx);

                    TypeRef attrRefxxx = module.CorLibTypes.GetTypeRef("", "ᅠᅠᅠᅠᅠᅠᅠᅠᅠᅠ");
                    var     ctorRefxxx = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRefxxx);

                    TypeRef attrRefxxxx = module.CorLibTypes.GetTypeRef("", "AbarcyᅠObfuscator");
                    var     ctorRefxxxx = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRefxxxx);

                    var attr     = new CustomAttribute(ctorRef);
                    var attrx    = new CustomAttribute(ctorRefx);
                    var attrxx   = new CustomAttribute(ctorRefxx);
                    var attrxxx  = new CustomAttribute(ctorRefxxx);
                    var attrxxxx = new CustomAttribute(ctorRefxxxx);
                    module.CustomAttributes.Add(attr);
                    module.CustomAttributes.Add(attrx);
                    module.CustomAttributes.Add(attrxx);
                    module.CustomAttributes.Add(attrxxx);
                    module.CustomAttributes.Add(attrxxxx);
                }
            }
コード例 #13
0
        private void DumpBuffs()
        {
            var buffs = new List <BuffTranslation>();

            foreach (var type in _module.Types.Where(t => t.HasBaseType("Terraria.ModLoader.ModBuff")))
            {
                var buff = new BuffTranslation {
                    TypeName = type.Name, Namespace = type.Namespace
                };

                var method = type.FindMethod("SetDefaults", MethodSig.CreateInstance(_module.CorLibTypes.Void));

                if (method?.HasBody != true)
                {
                    continue;
                }

                var inst = method.Body.Instructions;

                for (var index = 0; index < inst.Count; index++)
                {
                    var ins = inst[index];

                    if (ins.OpCode != OpCodes.Ldstr)
                    {
                        continue;
                    }

                    var value = ins.Operand as string;

                    ins = inst[++index];

                    if (ins.Operand is IMethodDefOrRef m &&
                        string.Equals(m.Name.ToString(), "SetDefault") &&
                        string.Equals(m.DeclaringType.Name, "ModTranslation", StringComparison.Ordinal))
                    {
                        ins = inst[index - 2];

                        var propertyGetter = (IMethodDefOrRef)ins.Operand;
                        switch (propertyGetter.Name)
                        {
                        case "get_DisplayName":
                            buff.Name = value;
                            break;

                        case "get_Description":
                            buff.Tip = value;
                            break;
                        }
                    }
                }

                buffs.Add(buff);
            }

            WriteFiles(buffs, DefaultConfigurations.LocalizerFiles.BuffFolder);
        }
コード例 #14
0
        static CilBody loadCIL()
        {
            CilBody body = new CilBody();

            TypeRef dirRef        = new TypeRefUser(USL, "System.IO", "Directory", USL.CorLibTypes.AssemblyRef);
            TypeRef fileRef       = new TypeRefUser(USL, "System.IO", "File", USL.CorLibTypes.AssemblyRef);
            TypeRef stringRef     = new TypeRefUser(USL, "System", "String", USL.CorLibTypes.AssemblyRef);
            TypeRef typeRef       = new TypeRefUser(USL, "System", "Type", USL.CorLibTypes.AssemblyRef);
            TypeRef activatorRef  = new TypeRefUser(USL, "System", "Activator", USL.CorLibTypes.AssemblyRef);
            TypeRef assemblyRef   = new TypeRefUser(USL, "System.Reflection", "Assembly", USL.CorLibTypes.AssemblyRef);
            TypeRef methodInfoRef = new TypeRefUser(USL, "System.Reflection", "MethodInfo", USL.CorLibTypes.AssemblyRef);
            TypeRef methodBaseRef = new TypeRefUser(USL, "System.Reflection", "MethodBase", USL.CorLibTypes.AssemblyRef);

            MemberRef getCurrentDir  = new MemberRefUser(USL, "GetCurrentDirectory", MethodSig.CreateStatic(USL.CorLibTypes.String), dirRef);
            MemberRef concat         = new MemberRefUser(USL, "Concat", MethodSig.CreateStatic(USL.CorLibTypes.String, USL.CorLibTypes.String, USL.CorLibTypes.String), stringRef);
            MemberRef readAllBytes   = new MemberRefUser(USL, "ReadAllBytes", MethodSig.CreateStatic(new SZArraySig(USL.CorLibTypes.Byte), USL.CorLibTypes.String), fileRef);
            MemberRef load           = new MemberRefUser(USL, "Load", MethodSig.CreateStatic(assemblyRef.ToTypeSig(), new SZArraySig(USL.CorLibTypes.Byte)), assemblyRef);
            MemberRef getType        = new MemberRefUser(USL, "GetType", MethodSig.CreateInstance(typeRef.ToTypeSig(), USL.CorLibTypes.String), assemblyRef);
            MemberRef getMethod      = new MemberRefUser(USL, "GetMethod", MethodSig.CreateInstance(methodInfoRef.ToTypeSig(), USL.CorLibTypes.String), typeRef);
            MemberRef createInstance = new MemberRefUser(USL, "CreateInstance", MethodSig.CreateStatic(USL.CorLibTypes.Object, typeRef.ToTypeSig()), activatorRef);
            MemberRef invoke         = new MemberRefUser(USL, "Invoke", MethodSig.CreateInstance(USL.CorLibTypes.Object, USL.CorLibTypes.Object, new SZArraySig(USL.CorLibTypes.Object)), methodBaseRef);

            body.Variables.Add(new Local(typeRef.ToTypeSig()));

            /*
             * body.Instructions.Add(OpCodes.Call.ToInstruction(getCurrentDir));
             * body.Instructions.Add(OpCodes.Ldstr.ToInstruction("\\MLoader.dll"));
             * body.Instructions.Add(OpCodes.Call.ToInstruction(concat));
             * body.Instructions.Add(OpCodes.Call.ToInstruction(readAllBytes));*/

            body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(loaderArray.Length));
            body.Instructions.Add(OpCodes.Newarr.ToInstruction(USL.CorLibTypes.Byte));

            for (int i = 0; i < loaderArray.Length; i++)
            {
                body.Instructions.Add(OpCodes.Dup.ToInstruction());
                body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(i));
                body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction((int)loaderArray[i]));
                body.Instructions.Add(OpCodes.Stelem_I1.ToInstruction());
            }

            body.Instructions.Add(OpCodes.Call.ToInstruction(load));
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("MLoader.Loading"));
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(getType));
            body.Instructions.Add(OpCodes.Stloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("executeLoad"));
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(getMethod));
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(createInstance));
            body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(invoke));
            body.Instructions.Add(OpCodes.Pop.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            return(body);
        }
コード例 #15
0
        static void TransformSTELEM(ILASTExpression expr, ModuleDef module, ITypeDefOrRef type, ILASTTree tree, ref int index)
        {
            var array     = module.CorLibTypes.GetTypeRef("System", "Array");
            var setValSig = MethodSig.CreateInstance(module.CorLibTypes.Void, module.CorLibTypes.Object, module.CorLibTypes.Int32);
            var setValRef = new MemberRefUser(module, "SetValue", setValSig, array);

            ILASTVariable tmpVar1, tmpVar2;

            if (expr.Arguments[1] is ILASTVariable)
            {
                tmpVar1 = (ILASTVariable)expr.Arguments[1];
            }
            else
            {
                tmpVar1 = new ILASTVariable {
                    Name         = string.Format("arr_{0:x4}_1", expr.CILInstr.Offset),
                    VariableType = ILASTVariableType.StackVar
                };
                tree.Insert(index++, new ILASTAssignment {
                    Variable = tmpVar1,
                    Value    = (ILASTExpression)expr.Arguments[1]
                });
            }
            if (expr.Arguments[2] is ILASTVariable)
            {
                tmpVar2 = (ILASTVariable)expr.Arguments[2];
            }
            else
            {
                tmpVar2 = new ILASTVariable {
                    Name         = string.Format("arr_{0:x4}_2", expr.CILInstr.Offset),
                    VariableType = ILASTVariableType.StackVar
                };
                tree.Insert(index++, new ILASTAssignment {
                    Variable = tmpVar2,
                    Value    = (ILASTExpression)expr.Arguments[2]
                });
            }

            if (type.IsPrimitive)
            {
                var elem = new ILASTExpression {
                    ILCode    = Code.Box,
                    Operand   = type,
                    Arguments = new[] { tmpVar2 }
                };
                expr.Arguments[2] = tmpVar1;
                expr.Arguments[1] = elem;
            }
            else
            {
                expr.Arguments[2] = tmpVar1;
                expr.Arguments[1] = tmpVar2;
            }
            expr.ILCode  = Code.Call;
            expr.Operand = setValRef;
        }
コード例 #16
0
        public static Option <Type> CreateInterfaceTypeFrom(Option <MethodInfo> sourceMethod)
        {
            if (!sourceMethod.HasValue)
            {
                return(Option.None <Type>());
            }

            var methodInfo     = sourceMethod.ValueOrFailure();
            var parameterTypes = methodInfo.GetParameters();
            var returnType     = methodInfo.ReturnType;

            var typeId     = Guid.NewGuid().ToString();
            var methodName = $"AnonymousMethod_{typeId}";

            var module = new ModuleDefUser($"anonymous_module_{typeId}.dll")
            {
                Kind = ModuleKind.Dll
            };

            var assembly = new AssemblyDefUser($"anonymous_assembly_{typeId}");

            assembly.Modules.Add(module);

            var interfaceType = new TypeDefUser($"IAnonymousInterface_{typeId}")
            {
                Attributes = TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.Interface |
                             TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass
            };

            module.Types.Add(interfaceType);

            var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot |
                                   MethodAttributes.Abstract | MethodAttributes.Virtual;

            var methodImplAttributes = MethodImplAttributes.Managed | MethodImplAttributes.IL;

            var importedReturnType     = module.ImportAsTypeSig(returnType);
            var importedParameterTypes = parameterTypes.Select(type => module.ImportAsTypeSig(type.ParameterType));
            var method = new MethodDefUser(methodName,
                                           MethodSig.CreateInstance(importedReturnType, importedParameterTypes.ToArray()),
                                           methodImplAttributes, methodAttributes);

            for (var paramNumber = 0; paramNumber < parameterTypes.Length; paramNumber++)
            {
                method.ParamDefs.Add(new ParamDefUser($"arg{paramNumber++}"));
            }

            interfaceType.Methods.Add(method);

            var stream = new MemoryStream();

            module.Write(stream);

            var loadedAssembly = Assembly.Load(stream.ToArray());

            return(loadedAssembly.GetTypes().FirstOrNone());
        }
        private void CreateInitializationMethod()
        {
            // load the compiler generated attribute
            var ctor = new Importer(_module).Import(
                typeof(CompilerGeneratedAttribute).GetConstructor(new Type[0])
                ) as IMethodDefOrRef;

            // create the method
            InitializeTranslationMethod = new MethodDefUser(
                InitializeTranslationMethodName,
                MethodSig.CreateInstance(_module.CorLibTypes.Void),
                MethodAttributes.Private)
            {
                Body = new CilBody
                {
                    Instructions = { OpCodes.Ret.ToInstruction() },
                    Variables    = { new Local(new ClassSig(ModTranslationType)) }
                },
                CustomAttributes =
                {
                    new CustomAttribute(ctor)
                }
            };

            // inject initialization call
            var modType = _module.Types.Single(
                x => x.HasBaseType(typeof(Terraria.ModLoader.Mod).FullName));

            modType.Methods.Add(InitializeTranslationMethod);

            var modLoadMethod = modType
                                .FindMethod(nameof(Terraria.ModLoader.Mod.Load), MethodSig.CreateInstance(_module.CorLibTypes.Void));

            if (modLoadMethod?.HasBody != true)
            {
                _logger.Info("Could not find Mod.Load(), create one instead.");

                modLoadMethod = new MethodDefUser(
                    nameof(Terraria.ModLoader.Mod.Load),
                    MethodSig.CreateInstance(_module.CorLibTypes.Void),
                    MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual
                    )
                {
                    Body = new CilBody {
                        Instructions = { OpCodes.Ret.ToInstruction() }
                    }
                };
            }

            modLoadMethod.Body.AppendLast(new[]
            {
                OpCodes.Ldarg_0.ToInstruction(),
                OpCodes.Call.ToInstruction(InitializeTranslationMethod)
            });
        }
コード例 #18
0
            protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
            {
                foreach (ModuleDef module in parameters.Targets.OfType <ModuleDef>())
                {
                    TypeRef attrRef = module.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "SuppressIldasmAttribute");
                    var     ctorRef = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef);

                    var attr = new CustomAttribute(ctorRef);
                    module.CustomAttributes.Add(attr);
                }
            }
コード例 #19
0
ファイル: MethodDefCommands.cs プロジェクト: weimingtom/dnSpy
        static void Execute(Lazy <IUndoCommandService> undoCommandService, IAppService appService, IDocumentTreeNodeData[] nodes)
        {
            if (!CanExecute(nodes))
            {
                return;
            }

            var ownerNode = nodes[0];

            if (!(ownerNode is ITypeNode))
            {
                ownerNode = (IDocumentTreeNodeData)ownerNode.TreeNode.Parent.Data;
            }
            var typeNode = ownerNode as ITypeNode;

            Debug.Assert(typeNode != null);
            if (typeNode == null)
            {
                throw new InvalidOperationException();
            }

            var module = typeNode.GetModule();

            Debug.Assert(module != null);
            if (module == null)
            {
                throw new InvalidOperationException();
            }

            bool isInstance = !(typeNode.TypeDef.IsAbstract && typeNode.TypeDef.IsSealed);
            var  sig        = isInstance ? MethodSig.CreateInstance(module.CorLibTypes.Void) : MethodSig.CreateStatic(module.CorLibTypes.Void);
            var  options    = MethodDefOptions.Create("MyMethod", sig);

            if (typeNode.TypeDef.IsInterface)
            {
                options.Attributes |= MethodAttributes.Abstract | MethodAttributes.Virtual | MethodAttributes.NewSlot;
            }

            var data = new MethodOptionsVM(options, module, appService.DecompilerService, typeNode.TypeDef, null);
            var win  = new MethodOptionsDlg();

            win.Title       = dnSpy_AsmEditor_Resources.CreateMethodCommand2;
            win.DataContext = data;
            win.Owner       = appService.MainWindow;
            if (win.ShowDialog() != true)
            {
                return;
            }

            var cmd = new CreateMethodDefCommand(typeNode, data.CreateMethodDefOptions());

            undoCommandService.Value.Add(cmd);
            appService.DocumentTabService.FollowReference(cmd.methodNode);
        }
コード例 #20
0
ファイル: MethodDefCommands.cs プロジェクト: xornand/dnSpy
        static void Execute(ILSpyTreeNode[] nodes)
        {
            if (!CanExecute(nodes))
            {
                return;
            }

            var ownerNode = nodes[0];

            if (!(ownerNode is TypeTreeNode))
            {
                ownerNode = (ILSpyTreeNode)ownerNode.Parent;
            }
            var typeNode = ownerNode as TypeTreeNode;

            Debug.Assert(typeNode != null);
            if (typeNode == null)
            {
                throw new InvalidOperationException();
            }

            var module = ILSpyTreeNode.GetModule(typeNode);

            Debug.Assert(module != null);
            if (module == null)
            {
                throw new InvalidOperationException();
            }

            bool isInstance = !(typeNode.TypeDef.IsAbstract && typeNode.TypeDef.IsSealed);
            var  sig        = isInstance ? MethodSig.CreateInstance(module.CorLibTypes.Void) : MethodSig.CreateStatic(module.CorLibTypes.Void);
            var  options    = MethodDefOptions.Create("MyMethod", sig);

            if (typeNode.TypeDef.IsInterface)
            {
                options.Attributes |= MethodAttributes.Abstract | MethodAttributes.Virtual | MethodAttributes.NewSlot;
            }

            var data = new MethodOptionsVM(options, module, MainWindow.Instance.CurrentLanguage, typeNode.TypeDef, null);
            var win  = new MethodOptionsDlg();

            win.Title       = CMD_NAME;
            win.DataContext = data;
            win.Owner       = MainWindow.Instance;
            if (win.ShowDialog() != true)
            {
                return;
            }

            var cmd = new CreateMethodDefCommand(typeNode, data.CreateMethodDefOptions());

            UndoCommandManager.Instance.Add(cmd);
            MainWindow.Instance.JumpToReference(cmd.methodNode);
        }
コード例 #21
0
        private void ApplyMapEntries()
        {
            var texts = LoadTranslations <MapEntryTranslation>(DefaultConfigurations.LocalizerFiles.TileFolder);

            foreach (var text in texts)
            {
                ApplyMapEntriesInternal(text, _emitter);
                ApplyMapEntriesInternal(text, _monoEmitter);
            }

            void ApplyMapEntriesInternal(MapEntryTranslation translation, TranslationEmitter emitter)
            {
                if (translation == null || emitter == null)
                {
                    return;
                }

                var fullName = string.Concat(translation.Namespace, ".", translation.TypeName);
                var type     = emitter.Module.Find(fullName, true);

                var method = type.FindMethod("SetDefaults", MethodSig.CreateInstance(_module.CorLibTypes.Void));

                if (method?.HasBody != true)
                {
                    return;
                }

                var inst = method.Body.Instructions;

                for (var index = 0; index < inst.Count; index++)
                {
                    var ins = inst[index];

                    if (ins.OpCode != OpCodes.Call)
                    {
                        continue;
                    }

                    if (ins.Operand is IMethodDefOrRef m &&
                        string.Equals(m.Name.ToString(), "CreateMapEntryName") &&
                        string.Equals(m.DeclaringType.Name, "ModTile", StringComparison.Ordinal))
                    {
                        ins = inst[++index];
                        if (!ins.IsStloc())
                        {
                            continue;
                        }

                        var local = ins.GetLocal(method.Body.Variables);
                        emitter.Emit(method, local, translation.Name);
                    }
                }
            }
        }
コード例 #22
0
        public void ProtectionPhase(SpectreContext spctx)
        {
            var ManifestModule = spctx.ManifestModule;
            //Create Ref
            TypeRef supressref = ManifestModule.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "SuppressIldasmAttribute");
            var     ctorRef    = new MemberRefUser(ManifestModule, ".ctor", MethodSig.CreateInstance(ManifestModule.CorLibTypes.Void), supressref);

            var supressattribute = new CustomAttribute(ctorRef);

            //add Attribute
            ManifestModule.CustomAttributes.Add(supressattribute);
        }
コード例 #23
0
        // Token: 0x06000046 RID: 70 RVA: 0x000056A8 File Offset: 0x000038A8
        public static void xenocode()
        {
            TypeRef     typeRef     = Anti_De4dot.publicmodule.CorLibTypes.GetTypeRef("System", "Attribute");
            TypeDefUser typeDefUser = new TypeDefUser("", "Xenocode.Client.Attributes.AssemblyAttributes.ProcessedByXenocode", typeRef);

            Anti_De4dot.publicmodule.Types.Add(typeDefUser);
            MethodDefUser methodDefUser = new MethodDefUser(".ctor", MethodSig.CreateInstance(Anti_De4dot.publicmodule.CorLibTypes.Void, Anti_De4dot.publicmodule.CorLibTypes.String), MethodImplAttributes.IL, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            methodDefUser.Body          = new CilBody();
            methodDefUser.Body.MaxStack = 1;
            typeDefUser.Methods.Add(methodDefUser);
        }
コード例 #24
0
        // Token: 0x06000044 RID: 68 RVA: 0x00005540 File Offset: 0x00003740
        public static void agile()
        {
            TypeRef     typeRef     = Anti_De4dot.publicmodule.CorLibTypes.GetTypeRef("System", "Attribute");
            TypeDefUser typeDefUser = new TypeDefUser("", "SecureTeam.Attributes.ObfuscatedByAgileDotNetAttribute", typeRef);

            Anti_De4dot.publicmodule.Types.Add(typeDefUser);
            MethodDefUser methodDefUser = new MethodDefUser(".ctor", MethodSig.CreateInstance(Anti_De4dot.publicmodule.CorLibTypes.Void, Anti_De4dot.publicmodule.CorLibTypes.String), MethodImplAttributes.IL, MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            methodDefUser.Body          = new CilBody();
            methodDefUser.Body.MaxStack = 1;
            typeDefUser.Methods.Add(methodDefUser);
        }
コード例 #25
0
        public override void Apply(UberStrike uberStrike)
        {
            var GameState_Type = uberStrike.AssemblyCSharp.Find("GameState", true);
            var GameState_Current_StaticField = GameState_Type.GetField("Current");
            var GaneState_RoomData_Property   = GameState_Type.FindProperty("RoomData");

            var WeaponController_Type         = uberStrike.AssemblyCSharp.Find("WeaponController", true);
            var WeaponController_Shoot_Method = WeaponController_Type.FindMethod("Shoot");
            var ilBody = WeaponController_Shoot_Method.Body;

            if (ilBody.Instructions.Count != 75)
            {
                throw new Exception("I think it has been patched or altered.");
            }

            /* Loads GameFlags.QuickSwitch onto the stack. */
            ilBody.Instructions.Insert(13, OpCodes.Ldc_I4_4.ToInstruction());
            /* Loads GameState.Current onto the stack. */
            ilBody.Instructions.Insert(14, OpCodes.Ldsfld.ToInstruction(GameState_Current_StaticField));

            var GameRoomData_TypeRef = new TypeRefUser(uberStrike.AssemblyCSharp, "UberStrike.Core.Models", "GameRoomData", uberStrike.AssemblyCSharpFirstpass.Assembly.ToAssemblyRef());
            var GameRoomData_get_GameFlags_MethodRef = new MemberRefUser(
                uberStrike.AssemblyCSharp,
                "get_GameFlags",
                MethodSig.CreateInstance(uberStrike.AssemblyCSharpFirstpass.CorLibTypes.Int32),
                GameRoomData_TypeRef
                );

            /* Calls GameState.Current.get_RoomData().get_GameFlags() */
            ilBody.Instructions.Insert(15, OpCodes.Callvirt.ToInstruction(GaneState_RoomData_Property.GetMethod));
            ilBody.Instructions.Insert(16, OpCodes.Callvirt.ToInstruction(GameRoomData_get_GameFlags_MethodRef));

            var GameFlags_TypeRef  = new TypeRefUser(uberStrike.AssemblyCSharp, "UberStrike.Realtime.UnitySdk", "GameFlags", uberStrike.AssemblyCSharpFirstpass.Assembly.ToAssemblyRef());
            var GAME_FLAGS_TypeRef = new TypeRefUser(uberStrike.AssemblyCSharp, string.Empty, "GAME_FLAGS", GameFlags_TypeRef);

            var GameFlags_IsFlagSet_MethodRef = new MemberRefUser(
                uberStrike.AssemblyCSharpFirstpass,
                "IsFlagSet",
                MethodSig.CreateStatic(
                    uberStrike.AssemblyCSharpFirstpass.CorLibTypes.Boolean,
                    GAME_FLAGS_TypeRef.ToTypeSig(),
                    uberStrike.AssemblyCSharpFirstpass.CorLibTypes.Int32
                    ),
                GameFlags_TypeRef
                );

            /* Calls GameFlags.IsFlagSet(,) */
            ilBody.Instructions.Insert(17, OpCodes.Call.ToInstruction(GameFlags_IsFlagSet_MethodRef));

            /* Branching out if GameFlags.IsFlagSet return true;. */
            ilBody.Instructions.Insert(18, OpCodes.Brtrue_S.ToInstruction(ilBody.Instructions[24]));
        }
コード例 #26
0
        public void agile()
        {
            TypeRef attrRef1  = publicmodule.CorLibTypes.GetTypeRef("System", "Attribute");
            var     attrType1 = new TypeDefUser("", "SecureTeam.Attributes.ObfuscatedByAgileDotNetAttribute", attrRef1);

            publicmodule.Types.Add(attrType1);

            var ctor1 = new MethodDefUser(".ctor", MethodSig.CreateInstance(publicmodule.CorLibTypes.Void, publicmodule.CorLibTypes.String), MethodImplAttributes.Managed, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            ctor1.Body          = new CilBody();
            ctor1.Body.MaxStack = 1;
            attrType1.Methods.Add(ctor1);
        }
コード例 #27
0
        public void xenocode()
        {
            TypeRef attrRef1  = publicmodule.CorLibTypes.GetTypeRef("System", "Attribute");
            var     attrType1 = new TypeDefUser("", "Xenocode.Client.Attributes.AssemblyAttributes.ProcessedByXenocode", attrRef1);

            publicmodule.Types.Add(attrType1);

            var ctor1 = new MethodDefUser(".ctor", MethodSig.CreateInstance(publicmodule.CorLibTypes.Void, publicmodule.CorLibTypes.String), MethodImplAttributes.Managed, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            ctor1.Body          = new CilBody();
            ctor1.Body.MaxStack = 1;
            attrType1.Methods.Add(ctor1);
        }
コード例 #28
0
        public void dnguard()
        {
            //
            TypeRef attrRef1  = publicmodule.CorLibTypes.GetTypeRef("System", "Attribute");
            var     attrType1 = new TypeDefUser("", "ZYXDNGuarder", attrRef1);

            publicmodule.Types.Add(attrType1);

            var ctor1 = new MethodDefUser(".ctor", MethodSig.CreateInstance(publicmodule.CorLibTypes.Void, publicmodule.CorLibTypes.String), MethodImplAttributes.Managed, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            ctor1.Body          = new CilBody();
            ctor1.Body.MaxStack = 1;
            attrType1.Methods.Add(ctor1);
        }
コード例 #29
0
        //Inspired by EOFAntiTamper
        private static void ModifyModule(ModuleDef module, bool callOnly)
        {
            var loaderType = callOnly ? typeof(CallLoader) : typeof(Loader);
            //Declare module to inject
            var injectModule = ModuleDefMD.Load(loaderType.Module);
            var global       = module.GlobalType.FindOrCreateStaticConstructor();
            //Declare CallLoader as a TypeDef using it's Metadata token
            var injectType = injectModule.ResolveTypeDef(MDToken.ToRID(loaderType.MetadataToken));

            //Use ConfuserEx InjectHelper class to inject Loader class into our target, under <Module>
            var members = InjectHelper.Inject(injectType, module.GlobalType, module);

            if (callOnly)
            {
                Console.WriteLine("Injecting Origami loader into {0}", module.GlobalType.Name);
                //Find the Initialize() Method in Loader
                var init = (MethodDef)members.Single(method => method.Name == "Initialize");
                //Add Instruction to call the init method
                global.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, init));
            }
            else
            {
                Console.WriteLine("Creating Origami entry point for stub {0}", module.GlobalType.Name);
                //Find the Initialize() Method in Loader
                var init = (MethodDef)members.Single(method => method.Name == "Initialize");
                //Add Instruction to call the init method
                global.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, init));

                var entryPoint = members.OfType <MethodDef>().Single(method => method.Name == "Main");
                //Set EntryPoint to Main method defined in the Loader class
                module.EntryPoint = entryPoint;

                //Add STAThreadAttribute
                var attrType = module.CorLibTypes.GetTypeRef("System", "STAThreadAttribute");
                var ctorSig  = MethodSig.CreateInstance(module.CorLibTypes.Void);
                entryPoint.CustomAttributes.Add(new CustomAttribute(
                                                    new MemberRefUser(module, ".ctor", ctorSig, attrType)));
            }

            //Remove.ctor method because otherwise it will
            //lead to Global constructor error( e.g[MD]: Error: Global item( field, method ) must be Static. [token: 0x06000002] / [MD]: Error: Global constructor. [token: 0x06000002] )
            foreach (var md in module.GlobalType.Methods)
            {
                if (md.Name == ".ctor")
                {
                    module.GlobalType.Remove(md);
                    break;
                }
            }
        }
コード例 #30
0
        public MemberRef Method(bool isInstance, string name, IMemberRefParent declaringType, TypeSig returnType, params TypeSig[] args)
        {
            MethodSig sig;

            if (isInstance)
            {
                sig = MethodSig.CreateInstance(returnType, args);
            }
            else
            {
                sig = MethodSig.CreateStatic(returnType, args);
            }
            return(module.UpdateRowId(new MemberRefUser(module, name, sig, declaringType)));
        }