コード例 #1
0
 /// <summary>
 /// Construct a CreateAliasEvent
 /// Construct a CreateAliasEvent
 /// </summary>
 /// <param name="methodSig">The signature of the createAlias method we're going to invoke when the event fires</param>
 /// <param name="associationPath">the association path of the alias we're creating</param>
 /// <param name="alias"> the name of the alias we're creating</param>
 /// <param name="joinType">the join type of the alias we're creating. Can be null</param>
 private CreateAliasEvent(MethodSig methodSig, string associationPath, string alias, JoinType joinType)
 {
     this.methodSig = methodSig;
     this.associationPath = associationPath;
     this.alias = alias;
     this.joinType = joinType;
 }
コード例 #2
0
ファイル: SetLockModeEvent.cs プロジェクト: spib/nhcontrib
        /**
         * Construct a SetLockModeEvent
         *
         * @param methodSig tells us which overload of setLockMode to use
         * @param lockMode the lock mode we'll set when the event fires
         * @param alias the alias for which we'll set the lcok mode when the event
         * fires.  Can be null.
         */
        private SetLockModeEvent(
			MethodSig methodSig,
			LockMode lockMode,
			/*@Nullable*/ string alias)
        {
            this.methodSig = methodSig;
            this.lockMode = lockMode;
            this.alias = alias;
        }
コード例 #3
0
        public static MemoryStream CreateSFXModuleEx(Dictionary <ModuleDefMD, string> inputModules, string mainExecutableModuleFN = null)
        {
            var         cube    = new NBytzCube.NBCube();            //Dummy to import assembl
            AssemblyDef cubeDll = AssemblyDef.Load("NBytzCube.dll"); //Load NBCube

            cubeDll.Name = "NBytzHypercube";
            ModuleDef nbCubeMod = cubeDll.Modules[0];

            nbCubeMod.Name = "NBytzProtector.Core";
            nbCubeMod.Kind = ModuleKind.Console; //convert to EXE
            Importer    importer = new Importer(nbCubeMod);
            string      mainExe;
            ModuleDefMD mainModule;

            if (mainExecutableModuleFN == null)
            {
                IEnumerable <ModuleDefMD> __mainModule = inputModules.Keys.Where(mod => mod.Kind == ModuleKind.Console || mod.Kind == ModuleKind.Windows);
                if (__mainModule.Count() != 1)
                {
                    throw new InvalidAssemblySetException("Invalid number of executable modules! Specify a main module if there are multiple executables.");
                }
                mainModule = __mainModule.ElementAt(0);
                mainExe    = inputModules[mainModule];
            }
            else
            {
                mainModule = ModuleDefMD.Load(mainExecutableModuleFN);
                mainExe    = mainExecutableModuleFN;
            }
            nbCubeMod.Kind = mainModule.Kind;
            string moduleContents = "";

            moduleContents += SquashFile(mainExe); //add exe module first
            inputModules.Remove(mainModule);
            foreach (string fileName in inputModules.Values)
            {
                moduleContents += "_" + SquashFile(fileName); //add module to mess
            }
            moduleContents = CompressString(moduleContents);  //compress
            GC.Collect();
            GC.WaitForPendingFinalizers();                    //Clean up the massive memory usage

            #region Create EntryPoint
            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser(namespaceName, "Startup", nbCubeMod.CorLibTypes.Object.TypeDefOrRef);
            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            nbCubeMod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Int32, new SZArraySig(nbCubeMod.CorLibTypes.String)));
            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            nbCubeMod.EntryPoint = entryPoint;
            #endregion

            #region TypeRefs
            // Create a TypeRef to System.Console
            TypeRef consoleRef = new TypeRefUser(nbCubeMod, "System", "Console", nbCubeMod.CorLibTypes.AssemblyRef);
            // Create a method ref to 'System.Void System.Console::WriteLine(System.String)'
            MemberRef consoleWrite1 = new MemberRefUser(nbCubeMod, "WriteLine",
                                                        MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String),
                                                        consoleRef);

            MemberRef consoleReadLine1 = new MemberRefUser(nbCubeMod, "ReadLine",
                                                           MethodSig.CreateStatic(nbCubeMod.CorLibTypes.String),
                                                           consoleRef);

            AssemblyRef powerAESLibRef = cubeDll.ToAssemblyRef();

            TypeRef powerAESRef = new TypeRefUser(nbCubeMod, "OmniBean.PowerCrypt4", "PowerAES",
                                                  powerAESLibRef);

            ITypeDefOrRef byteArrayRef = importer.Import(typeof(System.Byte[]));

            MemberRef decryptRef = new MemberRefUser(nbCubeMod, "Decrypt",
                                                     MethodSig.CreateStatic(nbCubeMod.CorLibTypes.String, nbCubeMod.CorLibTypes.String, nbCubeMod.CorLibTypes.String)
                                                     , powerAESRef);

            TypeRef byteConverterRef = new TypeRefUser(nbCubeMod, "OmniBean.PowerCrypt4.Utilities", "ByteConverter",
                                                       powerAESLibRef);

            MemberRef getBytesRef = new MemberRefUser(nbCubeMod, "GetBytes",
                                                      MethodSig.CreateStatic(byteArrayRef.ToTypeSig(), nbCubeMod.CorLibTypes.String)
                                                      , byteConverterRef);

            TypeRef nbCubeRef = new TypeRefUser(nbCubeMod, "NBytzCube", "NBCube",
                                                powerAESLibRef);

            MemberRef extractAndLaunchAsmRef = new MemberRefUser(nbCubeMod, "ExtractUnpackAndLaunchAssembly",
                                                                 MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String)
                                                                 , nbCubeRef);

            TypeRef fileRef = new TypeRefUser(nbCubeMod, "System.IO", "File",
                                              nbCubeMod.CorLibTypes.AssemblyRef);

            MemberRef writeBytesRef = new MemberRefUser(nbCubeMod, "WriteAllBytes",
                                                        MethodSig.CreateStatic(nbCubeMod.CorLibTypes.Void, nbCubeMod.CorLibTypes.String, byteArrayRef.ToTypeSig()),
                                                        fileRef);
            #endregion

            // Add a CIL method body to the entry point method
            CilBody epBody = new CilBody();
            entryPoint.Body = epBody;
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction("NetBytz Encrypted SFX - (c) 2016 0xFireball"));
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(consoleWrite1));
            epBody.Instructions.Add(OpCodes.Ldstr.ToInstruction(moduleContents));        //push encrypted text
            epBody.Instructions.Add(OpCodes.Call.ToInstruction(extractAndLaunchAsmRef)); //Helper Method Launch assembly
            epBody.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());                   //push 0
            epBody.Instructions.Add(OpCodes.Ret.ToInstruction());                        //Return/End
                                                                                         //write to stream
            var ms = new MemoryStream();
            nbCubeMod.Write(ms);
            return(ms);
        }
コード例 #4
0
ファイル: Fuzzer.cs プロジェクト: reijin90/sharpfuzz
        private static TypeDefUser GenerateTraceType(ModuleDefMD mod)
        {
            var traceType = new TypeDefUser(
                typeof(SharpFuzz.Common.Trace).FullName,
                mod.CorLibTypes.Object.TypeDefOrRef
                );

            traceType.Attributes = TypeAttributes.Public
                                   | TypeAttributes.Abstract
                                   | TypeAttributes.Sealed
                                   | TypeAttributes.BeforeFieldInit;

            var sharedMemField = new FieldDefUser(
                nameof(Common.Trace.SharedMem),
                new FieldSig(new PtrSig(mod.CorLibTypes.Byte)),
                FieldAttributes.Public | FieldAttributes.Static
                );

            var prevLocationField = new FieldDefUser(
                nameof(Common.Trace.PrevLocation),
                new FieldSig(mod.CorLibTypes.Int32),
                FieldAttributes.Public | FieldAttributes.Static
                );

            var onBranchField = new FieldDefUser(
                nameof(Common.Trace.OnBranch),
                new FieldSig(mod.ImportAsTypeSig(typeof(Action <int, string>))),
                FieldAttributes.Public | FieldAttributes.Static
                );

            traceType.Fields.Add(sharedMemField);
            traceType.Fields.Add(prevLocationField);
            traceType.Fields.Add(onBranchField);

            var cctorSig       = MethodSig.CreateStatic(mod.CorLibTypes.Void);
            var cctorImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed;

            var cctorFlags = MethodAttributes.Private
                             | MethodAttributes.HideBySig
                             | MethodAttributes.SpecialName
                             | MethodAttributes.RTSpecialName
                             | MethodAttributes.Static;

            var cctor = new MethodDefUser(".cctor", cctorSig, cctorImplFlags, cctorFlags);

            traceType.Methods.Add(cctor);

            var body = new CilBody {
                InitLocals = false, MaxStack = 1
            };

            cctor.Body = body;

            var local = new Local(mod.CorLibTypes.IntPtr);

            body.Variables.Add(local);

            var marshalType = mod.Types.Single(type => type.FullName == typeof(Marshal).FullName);
            var intPtrType  = mod.Types.Single(type => type.FullName == typeof(IntPtr).FullName);

            var allocHGlobal = marshalType.FindMethod(
                nameof(Marshal.AllocHGlobal),
                MethodSig.CreateStatic(mod.CorLibTypes.IntPtr,
                                       mod.CorLibTypes.Int32)
                );

            var toPointer = intPtrType.FindMethod(
                nameof(IntPtr.ToPointer),
                MethodSig.CreateInstance(new PtrSig(mod.CorLibTypes.Void))
                );

            body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(MapSize));
            body.Instructions.Add(OpCodes.Call.ToInstruction(allocHGlobal));
            body.Instructions.Add(OpCodes.Stloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldloca_S.ToInstruction(local));
            body.Instructions.Add(OpCodes.Call.ToInstruction(toPointer));
            body.Instructions.Add(OpCodes.Stsfld.ToInstruction(sharedMemField));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            return(traceType);
        }
コード例 #5
0
ファイル: OpCode.cs プロジェクト: petterlopes/ConfuserEx
 /// <summary>
 /// Creates a new instruction with a method signature operand
 /// </summary>
 /// <param name="methodSig">The method signature</param>
 /// <returns>A new <see cref="Instruction"/> instance</returns>
 public Instruction ToInstruction(MethodSig methodSig)
 {
     return(Instruction.Create(this, methodSig));
 }
コード例 #6
0
        public static void WriteTo(this MethodSig signature, IMethod method, ITextOutput writer)
        {
            if (signature.ExplicitThis)
            {
                writer.WriteKeyword("instance explicit ");
            }
            else if (signature.HasThis)
            {
                writer.WriteKeyword("instance ");
            }
            signature.RetType.WriteTo(writer, ILNameSyntax.SignatureNoNamedTypeParameters);
            writer.Write(' ');
            if (method != null && method.DeclaringType != null)
            {
                method.DeclaringType.WriteTo(writer, ILNameSyntax.TypeName);
                writer.Write("::");
            }
            MethodDef md = method as MethodDef;

            if (md != null && md.IsCompilerControlled)
            {
                writer.WriteReference(Escape(method.Name + "$PST" + method.MDToken.Raw.ToString("X8")), method);
            }
            else if (method != null)
            {
                writer.WriteReference(Escape(method.Name), method);
            }
            else
            {
                writer.Write("(*)");
            }
            MethodSpec methodSpec = method as MethodSpec;

            if (methodSpec != null)
            {
                writer.Write('<');
                var genArgs = methodSpec.GenericInstMethodSig.GenericArguments;
                for (int i = 0; i < genArgs.Count; i++)
                {
                    if (i > 0)
                    {
                        writer.Write(", ");
                    }
                    genArgs[i].WriteTo(writer);
                }
                writer.Write('>');
            }
            writer.Write("(");
            for (int i = 0; i < signature.Params.Count; ++i)
            {
                if (i > 0)
                {
                    writer.Write(", ");
                }
                signature.Params[i].WriteTo(writer, ILNameSyntax.SignatureNoNamedTypeParameters);
            }
            if (signature.ParamsAfterSentinel != null && signature.ParamsAfterSentinel.Count > 0)
            {
                if (signature.Params.Count > 0)
                {
                    writer.Write(", ");
                }

                writer.Write("...");
                for (int i = 0; i < signature.ParamsAfterSentinel.Count; ++i)
                {
                    if (i > 0)
                    {
                        writer.Write(", ");
                    }
                    signature.ParamsAfterSentinel[i].WriteTo(writer, ILNameSyntax.SignatureNoNamedTypeParameters);
                }
            }
            writer.Write(")");
        }
コード例 #7
0
        /// <summary>
        /// This Program is used to compile the Assembly-CSharp.
        ///
        /// For Instruction on how to use this Program please check the readme of this Project.
        /// </summary>
        public static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Missing File Argument");
                return;
            }

            var module = ModuleDefMD.Load(args[0]);

            if (module == null)
            {
                Console.WriteLine("File Not Found");
                return;
            }

            module.IsILOnly              = true;
            module.VTableFixups          = null;
            module.Assembly.PublicKey    = null;
            module.Assembly.HasPublicKey = false;

            var opts = new ModuleWriterOptions(module);

            Console.WriteLine($"Synapse: Loaded {module.Name}");
            Console.WriteLine("Synapse-Assemble: Resolving Ref..");

            var modCtx      = ModuleDef.CreateModuleContext();
            var asmResolver = (AssemblyResolver)modCtx.AssemblyResolver;

            module.Context = modCtx;

            ((AssemblyResolver)module.Context.AssemblyResolver).AddToCache(module);
            Console.WriteLine("Synapse-Injection: Injection of ModLoader");

            var modLoader = ModuleDefMD.Load("SynapseModLoader.dll");

            Console.WriteLine($"Synapse-Inject: Loaded {modLoader.Name}");

            var modClass = modLoader.Types[0];

            foreach (var type in modLoader.Types)
            {
                if (type.Name != "ModLoader")
                {
                    continue;
                }
                modClass = type;
                Console.WriteLine($"Synapse-Inject: Hooked to: {type.Namespace}.{type.Name}");
            }

            var modRefType = modClass;

            modLoader.Types.Remove(modClass);
            modRefType.DeclaringType = null;
            module.Types.Add(modRefType);

            var call = FindMethod(modRefType, "LoadModSystem");

            if (call == null)
            {
                Console.WriteLine("Failed to get 'LoadModSystem'. Perm Err?");
                return;
            }

            Console.WriteLine("Synapse-Inject: Injected!");
            Console.WriteLine("Synapse: Patching...");

            var def = FindType(module.Assembly, "ServerConsoleSender");

            // ReSharper disable once IdentifierTypo
            MethodDef bctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void),
                                                MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            if (FindMethod(def, ".ctor") != null)
            {
                bctor = FindMethod(def, ".ctor");
                Console.WriteLine("Synapse: Re-using constructor.");
            }
            else
            {
                def.Methods.Add(bctor);
            }

            CilBody body;

            bctor.Body = body = new CilBody();

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

            module.Write("Assembly-CSharp-Synapse.dll");

            Console.WriteLine("Synapse: Patch Complete!");

            var publicModule = ModuleDefMD.Load("Assembly-CSharp-Synapse.dll");

            Console.WriteLine("Synapse-Public: Creating Publicized DLL");

            var allTypes   = GetAllTypes(publicModule.Assembly.ManifestModule);
            var typeDefs   = allTypes.ToList();
            var allMethods = typeDefs.SelectMany(t => t.Methods);
            var allFields  = typeDefs.SelectMany(t => t.Fields);

            #region Publiczing

            foreach (var type in typeDefs.Where(type => !type?.IsPublic ?? false))
            {
                type.Attributes = type.IsNested ? TypeAttributes.NestedPublic : TypeAttributes.Public;
            }

            foreach (var method in allMethods)
            {
                if (!method?.IsPublic ?? false)
                {
                    method.Access = MethodAttributes.Public;
                }
            }


            foreach (var field in allFields)
            {
                if (!field?.IsPublic ?? false)
                {
                    field.Access = FieldAttributes.Public;
                }
            }

            #endregion

            publicModule.Write("Assembly-CSharp-Synapse_publicised.dll");

            Console.WriteLine("Synapse-Public: Created Publicised DLL");

            Thread.Sleep(1000000000);
        }
コード例 #8
0
        public void Watermark()
        {
            Console.WriteLine("Watermarking...");
            TypeRef attrRef  = Module.CorLibTypes.GetTypeRef("System", "Attribute");
            var     attrType = new TypeDefUser("", "AsStrongAsFuckAttribute", attrRef);

            Module.Types.Add(attrType);
            var ctor = new MethodDefUser(
                ".ctor",
                MethodSig.CreateInstance(Module.CorLibTypes.Void, Module.CorLibTypes.String),
                dnlib.DotNet.MethodImplAttributes.Managed,
                dnlib.DotNet.MethodAttributes.HideBySig | dnlib.DotNet.MethodAttributes.Public | dnlib.DotNet.MethodAttributes.SpecialName | dnlib.DotNet.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(Module, ".ctor", MethodSig.CreateInstance(Module.CorLibTypes.Void), attrRef)));
            ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction());
            attrType.Methods.Add(ctor);
            var attr = new CustomAttribute(ctor);

            attr.ConstructorArguments.Add(new CAArgument(Module.CorLibTypes.String, "AsStrongAsFuck obfuscator by Charter(vk.com/violent_0). " + Code));
            Module.CustomAttributes.Add(attr);
        }
コード例 #9
0
 /**
  * Construct a SubcriteriaFactoryImpl
  *
  * @param methodSig used to tell us which overload of createCriteria to invoke
  * @param association the association we'll pass to createCriteria
  * @param joinType the join type we'll pass to createCriteria.  Can be null.
  * @param alias the alias we'll pass to createCriteria.  Can be null.
  */
 private SubcriteriaFactoryImpl(MethodSig methodSig, string association, JoinType joinType, string alias)
 {
     this.methodSig = methodSig;
     this.association = association;
     this.joinType = joinType;
     this.alias = alias;
 }
コード例 #10
0
            protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
            {
                var rt = context.Registry.GetService <IRuntimeService>();

                foreach (ModuleDef module in parameters.Targets.OfType <ModuleDef>())
                {
                    var     marker  = context.Registry.GetService <IMarkerService>();
                    var     name    = context.Registry.GetService <INameService>();
                    TypeDef typeDef = rt.GetRuntimeType("Confuser.Runtime.CalliInj");
                    IEnumerable <IDnlibDef> members = InjectHelper.Inject(typeDef, module.GlobalType, module);
                    var init = (MethodDef)members.Single(methodddd => methodddd.Name == "ResolveToken");
                    foreach (IDnlibDef member in members)
                    {
                        name.MarkHelper(member, marker, (Protection)Parent);
                    }
                    foreach (TypeDef type in module.Types.ToArray())
                    {
                        foreach (MethodDef method in type.Methods.ToArray())
                        {
                            if (method.Equals(init))
                            {
                            }
                            else if (method.Equals(module.EntryPoint))
                            {
                            }

                            else
                            {
                                if (method.HasBody)
                                {
                                    if (method.Body.HasInstructions)
                                    {
                                        for (int i = 0; i < method.Body.Instructions.Count - 1; i++)
                                        {
                                            try
                                            {
                                                if (method.Body.Instructions[i].OpCode == OpCodes.Call || method.Body.Instructions[i].OpCode == OpCodes.Callvirt /* || method.Body.Instructions[i].OpCode == OpCodes.Ldloc_S*/)
                                                {
                                                    Console.WriteLine(method.Body.Instructions[i].Operand.ToString());
                                                    if (!method.Body.Instructions[i].Operand.ToString().Contains("System.Type"))
                                                    {
                                                        if (!method.Body.Instructions[i].Operand.ToString().Contains("MessageBoxButtons"))
                                                        {
                                                            try
                                                            {
                                                                MemberRef membertocalli = (MemberRef)method.Body.Instructions[i].Operand;
                                                                tokentocalli = membertocalli.MDToken.ToInt32();
                                                                if (CanObfuscate(membertocalli, method.Body.Instructions[i]))
                                                                {
                                                                    listmember.Add(membertocalli);
                                                                    listtoken.Add(tokentocalli);
                                                                    if (!membertocalli.ToString().Contains("ResolveToken"))

                                                                    {
                                                                        if (!membertocalli.HasThis)
                                                                        {
                                                                            if (listmember.Contains(membertocalli))
                                                                            {
                                                                                method.Body.Instructions[i].OpCode  = OpCodes.Calli;
                                                                                method.Body.Instructions[i].Operand = listmember[listmember.IndexOf(membertocalli)].MethodSig;
                                                                                method.Body.Instructions.Insert(i, Instruction.Create(OpCodes.Call, init));
                                                                                method.Body.Instructions.Insert(i, Instruction.Create(OpCodes.Ldc_I4, (listtoken[listmember.IndexOf(membertocalli)])));
                                                                            }
                                                                            else
                                                                            {
                                                                                MethodSig MethodSign = membertocalli.MethodSig;
                                                                                method.Body.Instructions[i].OpCode  = OpCodes.Calli;
                                                                                method.Body.Instructions[i].Operand = MethodSign;
                                                                                method.Body.Instructions.Insert(i, Instruction.Create(OpCodes.Call, init));
                                                                                method.Body.Instructions.Insert(i, Instruction.CreateLdcI4(tokentocalli));
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                string str = ex.Message;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            catch
                                            {
                                            }
                                        }
                                    }
                                    else
                                    {
                                    }
                                }
                            }
                        }
                        foreach (MethodDef md in module.GlobalType.Methods)
                        {
                            if (md.Name == ".ctor")
                            {
                                module.GlobalType.Remove(md);
                                break;
                            }
                        }
                    }
                }
            }
コード例 #11
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, null);

            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;
            }
        }
コード例 #12
0
ファイル: Junk.cs プロジェクト: v4nyl/SkiDzEX
            protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
            {
                foreach (ModuleDef moduleDef in parameters.Targets.OfType <ModuleDef>())
                {
                    var             name   = context.Registry.GetService <INameService>();
                    var             marker = context.Registry.GetService <IMarkerService>();
                    RandomGenerator r      = context.Registry.GetService <IRandomService>().GetRandomGenerator(Parent.FullId);

                    foreach (ModuleDef module in parameters.Targets.OfType <ModuleDef>())
                    {
                        InterfaceImpl moduleImpl = new InterfaceImplUser(module.GlobalType);

                        for (int i = 0; i < r.NextInt32(20, 50); i++)
                        {
                            TypeDefUser type = new TypeDefUser(module.GlobalType.Namespace,
                                                               name.RandomName(),
                                                               module.CorLibTypes.GetTypeRef("System", "Attribute"))
                            {
                                Attributes = TypeAttributes.Public
                            };
                            type.Interfaces.Add(moduleImpl);

                            for (int j = 0; j < r.NextInt32(20, 25); j++)
                            {
                                MethodDefUser method = new MethodDefUser(name.RandomName(RenameMode.Unicode),
                                                                         MethodSig.CreateInstance(module.CorLibTypes.Void),
                                                                         MethodImplAttributes.Managed,
                                                                         MethodAttributes.Public | MethodAttributes.Static);
                                method.Body = new CilBody();
                                method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
                                type.Methods.Add(method);
                            }

                            module.Types.Add(type);

                            marker.Mark(type, Parent);
                            name.SetCanRename(type, false);
                            foreach (MethodDef method in type.Methods)
                            {
                                marker.Mark(method, Parent);
                                name.SetCanRename(method, false);
                            }
                        }
                    }
                    ModuleDefMD moduleDefMD = (ModuleDefMD)moduleDef;
                    if (moduleDefMD.FullName.Contains(".exe"))
                    {
                        moduleDefMD.Name          = "";
                        moduleDefMD.Assembly.Name = "";
                        int num = context.Modules.Count - 1;
                        for (int i = 0; i <= num; i++)
                        {
                            for (int j = 0; j <= 50; j++)
                            {
                                Random rnd = new Random();
                                new TypeDefUser(Random(15) + "", Random(rnd.Next(1, 20)) + "<Module>", moduleDefMD.CorLibTypes.Object.TypeDefOrRef).Attributes = TypeAttributes.SpecialName;
                                TypeDef item = new TypeDefUser(Random(rnd.Next(1, 25)) + "<Module>", Random(rnd.Next(1, 15)) + "", moduleDefMD.CorLibTypes.Object.TypeDefOrRef)
                                {
                                    Attributes = TypeAttributes.ReservedMask
                                };
                                TypeDef item2 = new TypeDefUser(Random(rnd.Next(1, 20)) + "", Random(rnd.Next(1, 15)) + "<Module>", moduleDefMD.CorLibTypes.Object.TypeDefOrRef)
                                {
                                    Attributes = TypeAttributes.ReservedMask
                                };
                                moduleDefMD.Types.Add(item);
                                moduleDefMD.Types.Add(item2);
                            }
                            Random rnd1 = new Random();
                            moduleDefMD.EntryPoint.Name = Random(rnd1.Next(1, 10)) + "" + Random(300) + "" + Random(rnd1.Next(1, 10));
                        }
                    }
                    else
                    {
                        context.Logger.Warn("Junk Cannot be used on a dll");
                    }
                }
            }
コード例 #13
0
        public void mango()
        {
            TypeRef attrRef1  = publicmodule.CorLibTypes.GetTypeRef("System", "Attribute");
            var     attrType1 = new TypeDefUser("", "();\u0009", 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;
            ctor1.Body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            ctor1.Body.Instructions.Add(OpCodes.Call.ToInstruction(new MemberRefUser(publicmodule, ".ctor", MethodSig.CreateInstance(publicmodule.CorLibTypes.Void), attrRef1)));
            ctor1.Body.Instructions.Add(OpCodes.Ret.ToInstruction());
            attrType1.Methods.Add(ctor1);
        }
コード例 #14
0
ファイル: Instruction.cs プロジェクト: EmilZhou/dnlib
		/// <summary>
		/// Returns an argument type
		/// </summary>
		/// <param name="methodSig">Method signature</param>
		/// <param name="declaringType">Declaring type (only needed if it's an instance method)</param>
		/// <returns>The type or <c>null</c> if it doesn't exist</returns>
		public TypeSig GetArgumentType(MethodSig methodSig, ITypeDefOrRef declaringType) {
			if (methodSig == null)
				return null;
			int index = GetParameterIndex();
			if (index == 0 && methodSig.ImplicitThis)
				return declaringType.ToTypeSig();	//TODO: Should be ByRef if value type
			if (methodSig.ImplicitThis)
				index--;
			return methodSig.Params.Get(index, null);
		}
コード例 #15
0
ファイル: Program.cs プロジェクト: SuperMartas/iw5
        static void Main(string[] args)
        {
            // Create assembly and main module
            var assembly = new AssemblyDefUser("HelloWorld");
            var module   = new ModuleDefUser("HelloWorld.dll", null, new AssemblyRefUser("System.Runtime", new Version(4, 2, 2, 0)));

            module.RuntimeVersion = dnlib.DotNet.MD.MDHeaderRuntimeVersion.MS_CLR_40;

            // Create type Program
            var type = new TypeDefUser(
                @namespace: "HelloWorld",
                name: "Program",
                baseType: module.CorLibTypes.Object.TypeDefOrRef);

            // Set class attributes
            type.Attributes = TypeAttributes.Public | TypeAttributes.Class;

            // Create method Main
            var method = new MethodDefUser(
                name: "Main",
                methodSig: MethodSig.CreateStatic(
                    retType: module.CorLibTypes.Void,
                    argType1: new SZArraySig(module.CorLibTypes.String)));

            // Name parameter
            method.ParamDefs.Add(new ParamDefUser("args", 1));
            // Set method attributes
            method.Attributes = MethodAttributes.Public | MethodAttributes.Static;
            // Set attributes for method's implementation
            method.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;



            #region IMPLEMENTATION
            // Create reference to System.Console
            var consoleRef = new TypeRefUser(module, "System", "Console", new AssemblyRefUser("System.Console"));
            // Create reference to System.Console::WriteLine(string)
            var writeLineRef = new MemberRefUser(module, "WriteLine",
                                                 MethodSig.CreateStatic(
                                                     retType: module.CorLibTypes.Void,
                                                     argType1: module.CorLibTypes.String),
                                                 consoleRef);

            // Implement body of the Program::Main(string[]) method
            var body = new CilBody();
            body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, "Hello World!"));
            body.Instructions.Add(Instruction.Create(OpCodes.Call, writeLineRef));
            body.Instructions.Add(Instruction.Create(OpCodes.Br, body.Instructions.First()));
            body.Instructions.Add(Instruction.Create(OpCodes.Ret));

            method.Body = body;
            #endregion



            #region ASSEMBLE
            // Wire-it up!
            assembly.Modules.Add(module);
            module.Types.Add(type);
            type.Methods.Add(method);

            // Set entrypoint
            module.EntryPoint = method;

            // Store assembly
            module.Write(Path.Combine("Generated", "HelloWorld.dll"), new dnlib.DotNet.Writer.ModuleWriterOptions(module));
            #endregion
        }
コード例 #16
0
        private MosaType Load(TypeSig typeSig)
        {
            if (typeSig is LeafSig)
            {
                if (typeSig is TypeDefOrRefSig)
                {
                    throw new AssemblyLoadException();                      // Should have been loaded in MetadataLoader
                }
                else if (typeSig is GenericInstSig)
                {
                    return(LoadGenericTypeInstanceSig((GenericInstSig)typeSig));
                }
                else if (typeSig is GenericSig)
                {
                    return(LoadGenericParam((GenericSig)typeSig));
                }
                else if (typeSig is FnPtrSig)
                {
                    MethodSig            fnPtr      = ((FnPtrSig)typeSig).MethodSig;
                    MosaType             returnType = GetType(fnPtr.RetType);
                    List <MosaParameter> pars       = new List <MosaParameter>();
                    for (int i = 0; i < fnPtr.Params.Count; i++)
                    {
                        var parameter = metadata.Controller.CreateParameter();

                        using (var mosaParameter = metadata.Controller.MutateParameter(parameter))
                        {
                            mosaParameter.Name = "A_" + i;
                            mosaParameter.ParameterAttributes = MosaParameterAttributes.In;
                            mosaParameter.ParameterType       = GetType(fnPtr.Params[i]);
                        }

                        pars.Add(parameter);
                    }
                    return(metadata.TypeSystem.ToFnPtr(new MosaMethodSignature(returnType, pars)));
                }
                else
                {
                    throw new NotSupportedException();
                }
            }
            else                // Non-leaf signature
            {
                MosaType elementType = GetType(typeSig.Next);
                MosaType result;
                switch (typeSig.ElementType)
                {
                case ElementType.Ptr:
                    result = elementType.ToUnmanagedPointer();
                    using (var ptrType = metadata.Controller.MutateType(result))
                        ptrType.UnderlyingObject = elementType.GetUnderlyingObject <UnitDesc <TypeDef, TypeSig> >().Clone(typeSig);
                    break;

                case ElementType.ByRef:
                    result = elementType.ToManagedPointer();
                    using (var ptrType = metadata.Controller.MutateType(result))
                        ptrType.UnderlyingObject = elementType.GetUnderlyingObject <UnitDesc <TypeDef, TypeSig> >().Clone(typeSig);
                    break;

                case ElementType.CModReqd:
                case ElementType.CModOpt:
                    result = metadata.Controller.CreateType(elementType);
                    using (var modType = metadata.Controller.MutateType(result))
                    {
                        modType.Modifier         = GetType(((ModifierSig)typeSig).Modifier.ToTypeSig());
                        modType.UnderlyingObject = elementType.GetUnderlyingObject <UnitDesc <TypeDef, TypeSig> >().Clone(typeSig);
                        modType.ElementType      = elementType;
                    }
                    break;

                case ElementType.Pinned:
                    result = elementType;                                // Pinned types are indicated in MosaLocal
                    return(result);                                      // Don't add again to controller

                case ElementType.SZArray:
                    result = elementType.ToSZArray();
                    using (var arrayType = metadata.Controller.MutateType(result))
                    {
                        arrayType.UnderlyingObject = elementType.GetUnderlyingObject <UnitDesc <TypeDef, TypeSig> >().Clone(typeSig);

                        if (!typeSig.Next.HasOpenGenericParameter())
                        {
                            var typeDesc = elementType.GetUnderlyingObject <UnitDesc <TypeDef, TypeSig> >();
                            GetType(new GenericInstSig(szHelperEnumeratorSig, typeSig.Next));
                            GetType(new GenericInstSig(iListSig, typeSig.Next));
                            foreach (var method in szHelperMethods)
                            {
                                var methodSpec = new MethodSpecUser(method.Definition, new GenericInstMethodSig(typeDesc.Signature));
                                LoadGenericMethodInstance(methodSpec, new GenericArgumentResolver());
                            }
                        }
                    }

                    if (!typeSig.Next.HasOpenGenericParameter())
                    {
                        metadata.Resolver.EnqueueForArrayResolve(result);
                    }
                    return(result);

                case ElementType.Array:
                    ArraySig      array     = (ArraySig)typeSig;
                    MosaArrayInfo arrayInfo = new MosaArrayInfo(array.LowerBounds, array.Rank, array.Sizes);
                    result = elementType.ToArray(arrayInfo);
                    using (var arrayType = metadata.Controller.MutateType(result))
                        arrayType.UnderlyingObject = elementType.GetUnderlyingObject <UnitDesc <TypeDef, TypeSig> >().Clone(typeSig);
                    break;

                default:
                    throw new AssemblyLoadException();
                }
                metadata.Controller.AddType(result);
                return(result);
            }
        }
コード例 #17
0
ファイル: OpCode.cs プロジェクト: EmilZhou/dnlib
		/// <summary>
		/// Creates a new instruction with a method signature operand
		/// </summary>
		/// <param name="methodSig">The method signature</param>
		/// <returns>A new <see cref="Instruction"/> instance</returns>
		public Instruction ToInstruction(MethodSig methodSig) {
			return Instruction.Create(this, methodSig);
		}
コード例 #18
0
        private MethodDef WriteDelegateProceeder(MethodDef innerMethod, string methodName, MethodParameters parametersList, ModuleDef module)
        {
            if (innerMethod == null)
            {
                return(null);
            }
            // currently, this is unsupported
            // (since I have no idea how it works)
            if (innerMethod.DeclaringType.HasGenericParameters || innerMethod.HasGenericParameters)
            {
                return(null);
            }

            var proceederMethodSignature = new MethodSig(CallingConvention.Default, 0, module.CorLibTypes.Object,
                                                         new TypeSig[] { module.CorLibTypes.Object, new SZArraySig(module.CorLibTypes.Object) });
            var proceederMethodAttributes = MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig;
            var proceederMethod           = new MethodDefUser(GetDelegateProceederName(methodName, innerMethod.DeclaringType),
                                                              proceederMethodSignature, proceederMethodAttributes);

            proceederMethod.Body = new CilBody();
            proceederMethod.GenericParameters.AddRange(innerMethod.GenericParameters.Select(p => p.Clone(innerMethod)));

            // object, object[] -> this, arguments
            var instructions = new Instructions(proceederMethod.Body.Instructions, module);

            var declaringType = innerMethod.DeclaringType.ToTypeSig();

            if (innerMethod.DeclaringType.HasGenericParameters)
            {
                var genericTypeArgs = new List <TypeSig>();
                for (int genericTypeParameterIndex = 0;
                     genericTypeParameterIndex < innerMethod.DeclaringType.GenericParameters.Count;
                     genericTypeParameterIndex++)
                {
                    genericTypeArgs.Add(new GenericVar(genericTypeParameterIndex, innerMethod.DeclaringType));
                }
                declaringType = new GenericInstSig((ClassOrValueTypeSig)innerMethod.DeclaringType.ToTypeSig(), genericTypeArgs);
                //instructions.Emit(OpCodes.Castclass, innerMethod.DeclaringType.ToTypeSig()); // arg.0 --> (target type) arg.0
            }

            if (!innerMethod.IsStatic)
            {
                instructions.Emit(OpCodes.Ldarg_0);
                if (declaringType.IsValueType)
                {
                    instructions.Emit(OpCodes.Unbox, declaringType); // arg.0 --> (target type) arg.0
                }
                else
                {
                    instructions.Emit(OpCodes.Castclass, declaringType); // arg.0 --> (target type) arg.0
                }
            }
            //instructions.Emit(OpCodes.Ldnull);

            var localVariables = new Local[innerMethod.Parameters.Count];

            for (int parameterIndex = 0; parameterIndex < parametersList.Count; parameterIndex++)
            {
                var parameter = parametersList[parameterIndex];

                if (parameter.ParamDef == null)
                {
                    parameter.CreateParamDef();
                }

                var   parameterType = parameter.Type;
                Local local         = null;
                // the local type for references is the dereferenced type
                if (parameterType is ByRefSig)
                {
                    parameterType = parameterType.Next;
                    localVariables[parameterIndex] = local = new Local(parameterType);
                    proceederMethod.Body.Variables.Add(local);
                }

                // on pure out values we don't care
                if (!parameter.ParamDef.IsOut)
                {
                    instructions.Emit(OpCodes.Ldarg_1);    // arguments[]
                    instructions.EmitLdc(parameterIndex);  // index
                    instructions.Emit(OpCodes.Ldelem_Ref); // get array object
                    instructions.EmitUnboxOrCastIfNecessary(parameterType);

                    // when there is a local, use it (because we're going to pass the reference)
                    if (local != null)
                    {
                        instructions.EmitStloc(local);
                    }
                }
                // in all cases, if there is a local, it means we use it
                if (local != null)
                {
                    instructions.Emit(OpCodes.Ldloca_S, local);
                }
            }

            if (proceederMethod.HasGenericParameters)
            {
                var genericArgs = new List <TypeSig>();
                for (int genericParameterIndex = 0; genericParameterIndex < proceederMethod.GenericParameters.Count; genericParameterIndex++)
                {
                    genericArgs.Add(new GenericMVar(genericParameterIndex, innerMethod));
                }
                var genericInnerMethod = new MethodSpecUser(innerMethod, new GenericInstMethodSig(genericArgs));
                instructions.Emit(OpCodes.Call, genericInnerMethod);
            }
            else
            {
                instructions.Emit(OpCodes.Call, innerMethod);
            }

            // collect ref/output parameters, if any
            for (int parameterIndex = 0; parameterIndex < innerMethod.Parameters.Count; parameterIndex++)
            {
                // when there is a local variable, it was either a ref or an out, so we need to box it again to array
                var localVariable = localVariables[parameterIndex];
                if (localVariable == null)
                {
                    continue;
                }
                instructions.Emit(OpCodes.Ldarg_1);                  // array[...]
                instructions.EmitLdc(parameterIndex);                // index
                instructions.EmitLdloc(localVariable);               // result
                instructions.EmitBoxIfNecessary(localVariable.Type); // box
                instructions.Emit(OpCodes.Stelem_Ref);               // and store
            }

            if (innerMethod.ReturnType.SafeEquivalent(module.CorLibTypes.Void))
            {
                instructions.Emit(OpCodes.Ldnull);
            }
            else
            {
                instructions.EmitBoxIfNecessary(innerMethod.ReturnType);
            }

            instructions.Emit(OpCodes.Ret);

            innerMethod.DeclaringType.Methods.Add(proceederMethod);
            return(proceederMethod);
        }
コード例 #19
0
ファイル: Instruction.cs プロジェクト: EmilZhou/dnlib
		/// <summary>
		/// Creates a new instruction with a method signature operand
		/// </summary>
		/// <param name="opCode">The opcode</param>
		/// <param name="methodSig">The method signature</param>
		/// <returns>A new <see cref="Instruction"/> instance</returns>
		public static Instruction Create(OpCode opCode, MethodSig methodSig) {
			if (opCode.OperandType != OperandType.InlineSig)
				throw new ArgumentException("Opcode does not have a method sig operand", "opCode");
			return new Instruction(opCode, methodSig);
		}
コード例 #20
0
        private IMethod CreateProceedMethod(InvocationArgument[] arguments, ModuleDef module, WeavingContext context)
        {
            // get the class from shortcuts
            var shortcutType = context.ShortcutClass;

            if (shortcutType == null)
            {
                shortcutType = new TypeDefUser("ArxOne.MrAdvice", "\u26A1Invocation")
                {
                    BaseType = module.Import(module.CorLibTypes.Object).ToTypeDefOrRef(),
                    // Abstract + Sealed is Static class
                    Attributes = TypeAttributes.NotPublic | TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.Sealed
                };
                module.Types.Add(shortcutType);
                context.ShortcutClass = shortcutType;
            }

            // create the method
            var nameBuilder   = new StringBuilder("ProceedAspect");
            var argumentIndex = 0;
            var methodSig     = new MethodSig {
                RetType = module.CorLibTypes.Object, HasThis = false
            };
            var defaultProceedMethod = GetDefaultProceedMethod(module, context);

            foreach (var argument in arguments)
            {
                if (argument.HasValue)
                {
                    methodSig.Params.Add(defaultProceedMethod.MethodSig.Params[argumentIndex]);
                }
                // One day if there are arguments collision risks (IE optional arguments with same type), overload name
                argumentIndex++;
            }
            var method = new MethodDefUser(nameBuilder.ToString(), methodSig)
            {
                Body       = new CilBody(),
                Attributes = MethodAttributes.Public | MethodAttributes.Static
            };

            shortcutType.Methods.Add(method);
            var instructions = new Instructions(method.Body.Instructions, module);

            // now, either get value from given arguments or from default
            argumentIndex = 0;
            var usedArgumentIndex = 0;

            foreach (var argument in arguments)
            {
                if (argument.HasValue) // a given argument
                {
                    instructions.EmitLdarg(method.Parameters[usedArgumentIndex++]);
                }
                else
                {
                    arguments[argumentIndex].EmitDefault(instructions);
                }
                argumentIndex++;
            }

            instructions.Emit(OpCodes.Tailcall); // because target method returns object and this method also returns an object
            instructions.Emit(OpCodes.Call, defaultProceedMethod);
            instructions.Emit(OpCodes.Ret);

            return(method);
        }
コード例 #21
0
        public void HandleInject(AntiTamperProtection parent, ConfuserContext context, ProtectionParameters parameters)
        {
            this.context = context;
            random       = context.Registry.GetService <IRandomService>().GetRandomGenerator(parent.FullId);
            z            = random.NextUInt32();
            x            = random.NextUInt32();
            c            = random.NextUInt32();
            v            = random.NextUInt32();
            name1        = random.NextUInt32() & 0x7f7f7f7f;
            name2        = random.NextUInt32() & 0x7f7f7f7f;
            key          = random.NextUInt32();

            fieldLayout = new byte[6];
            for (int i = 0; i < 6; i++)
            {
                int index = random.NextInt32(0, 6);
                while (fieldLayout[index] != 0)
                {
                    index = random.NextInt32(0, 6);
                }
                fieldLayout[index] = (byte)i;
            }

            switch (parameters.GetParameter(context, context.CurrentModule, "key", Mode.Normal))
            {
            case Mode.Normal:
                deriver = new NormalDeriver();
                break;

            case Mode.Dynamic:
                deriver = new DynamicDeriver();
                break;

            default:
                throw new UnreachableException();
            }
            deriver.Init(context, random);

            var     rt                   = context.Registry.GetService <IRuntimeService>();
            TypeDef initType             = rt.GetRuntimeType("Confuser.Runtime.AntiTamperJIT");
            IEnumerable <IDnlibDef> defs = InjectHelper.Inject(initType, context.CurrentModule.GlobalType, context.CurrentModule);

            initMethod = defs.OfType <MethodDef>().Single(method => method.Name == "Initialize");

            initMethod.Body.SimplifyMacros(initMethod.Parameters);
            List <Instruction> instrs = initMethod.Body.Instructions.ToList();

            for (int i = 0; i < instrs.Count; i++)
            {
                Instruction instr = instrs[i];
                if (instr.OpCode == OpCodes.Ldtoken)
                {
                    instr.Operand = context.CurrentModule.GlobalType;
                }
                else if (instr.OpCode == OpCodes.Call)
                {
                    var method = (IMethod)instr.Operand;
                    if (method.DeclaringType.Name == "Mutation" &&
                        method.Name == "Crypt")
                    {
                        Instruction ldDst = instrs[i - 2];
                        Instruction ldSrc = instrs[i - 1];
                        Debug.Assert(ldDst.OpCode == OpCodes.Ldloc && ldSrc.OpCode == OpCodes.Ldloc);
                        instrs.RemoveAt(i);
                        instrs.RemoveAt(i - 1);
                        instrs.RemoveAt(i - 2);
                        instrs.InsertRange(i - 2, deriver.EmitDerivation(initMethod, context, (Local)ldDst.Operand, (Local)ldSrc.Operand));
                    }
                }
            }
            initMethod.Body.Instructions.Clear();
            foreach (Instruction instr in instrs)
            {
                initMethod.Body.Instructions.Add(instr);
            }

            MutationHelper.InjectKeys(initMethod,
                                      new[] { 0, 1, 2, 3, 4 },
                                      new[] { (int)(name1 * name2), (int)z, (int)x, (int)c, (int)v });

            var name   = context.Registry.GetService <INameService>();
            var marker = context.Registry.GetService <IMarkerService>();

            cctor = context.CurrentModule.GlobalType.FindStaticConstructor();

            cctorRepl          = new MethodDefUser(name.RandomName(), MethodSig.CreateStatic(context.CurrentModule.CorLibTypes.Void));
            cctorRepl.IsStatic = true;
            cctorRepl.Access   = MethodAttributes.CompilerControlled;
            cctorRepl.Body     = new CilBody();
            cctorRepl.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
            context.CurrentModule.GlobalType.Methods.Add(cctorRepl);
            name.MarkHelper(cctorRepl, marker, parent);

            MutationHelper.InjectKeys(defs.OfType <MethodDef>().Single(method => method.Name == "HookHandler"),
                                      new[] { 0 }, new[] { (int)key });
            foreach (IDnlibDef def in defs)
            {
                if (def.Name == "MethodData")
                {
                    var        dataType = (TypeDef)def;
                    FieldDef[] fields   = dataType.Fields.ToArray();
                    var        layout   = fieldLayout.Clone() as byte[];
                    Array.Sort(layout, fields);
                    for (byte j = 0; j < 6; j++)
                    {
                        layout[j] = j;
                    }
                    Array.Sort(fieldLayout, layout);
                    fieldLayout = layout;
                    dataType.Fields.Clear();
                    foreach (FieldDef f in fields)
                    {
                        dataType.Fields.Add(f);
                    }
                }
                name.MarkHelper(def, marker, parent);
                if (def is MethodDef method)
                {
                    parent.ExcludeMethod(context, method);
                }
            }
            parent.ExcludeMethod(context, cctor);
        }
コード例 #22
0
ファイル: HostPatch.cs プロジェクト: swordlegend/uberstrok
        public override void Apply(UberStrike uberStrike)
        {
            var ApplicationDataManager_Type  = uberStrike.AssemblyCSharp.Find("ApplicationDataManager", true);
            var ApplicationDataManager_CCtor = ApplicationDataManager_Type.FindStaticConstructor();
            var ilBody = ApplicationDataManager_CCtor.Body;

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

            var endOfPatch = ilBody.Instructions[4];

            /* UnityEngine.Application */
            var Application_TypeRef = new TypeRefUser(uberStrike.AssemblyCSharp, "UnityEngine", "Application", uberStrike.UnityEngine.Assembly.ToAssemblyRef());
            /* UnityEngine.Application.get_dataPath */
            var Application_get_dataPath = new MemberRefUser(
                uberStrike.AssemblyCSharp,
                "get_dataPath",
                MethodSig.CreateStatic(uberStrike.AssemblyCSharp.CorLibTypes.String),
                Application_TypeRef
                );

            /* Calls Application.dataPath */
            ilBody.Instructions.Insert(0, OpCodes.Call.ToInstruction(Application_get_dataPath));
            /* Loads ".uberstrok" onto the stack. */
            ilBody.Instructions.Insert(1, OpCodes.Ldstr.ToInstruction(".uberstrok"));

            /* System.IO.Path */
            var Path_TypeRef = new TypeRefUser(uberStrike.AssemblyCSharp, "System.IO", "Path", uberStrike.AssemblyCSharp.CorLibTypes.AssemblyRef);
            /* System.IO.Path.Combine(string, string) */
            var Path_Combine_MethodRef = new MemberRefUser(
                uberStrike.AssemblyCSharp,
                "Combine",
                MethodSig.CreateStatic(
                    uberStrike.AssemblyCSharp.CorLibTypes.String,
                    uberStrike.AssemblyCSharp.CorLibTypes.String,
                    uberStrike.AssemblyCSharp.CorLibTypes.String
                    ),
                Path_TypeRef
                );

            /* Calls Path.Combine(Application.dataPath, ".uberstrok") */
            ilBody.Instructions.Insert(2, OpCodes.Call.ToInstruction(Path_Combine_MethodRef));

            /* System.IO.File */
            var File_TypeRef = new TypeRefUser(uberStrike.AssemblyCSharp, "System.IO", "File", uberStrike.AssemblyCSharp.CorLibTypes.AssemblyRef);
            /* System.IO.Path.ReadAllText(string) */
            var File_ReadAllText_MethodRef = new MemberRefUser(
                uberStrike.AssemblyCSharp,
                "ReadAllText",
                MethodSig.CreateStatic(
                    uberStrike.AssemblyCSharp.CorLibTypes.String,
                    uberStrike.AssemblyCSharp.CorLibTypes.String
                    ),
                File_TypeRef
                );

            /* Calls File.ReadAllText(Path.Combine(Application.dataPath, ".uberstrok")) */
            ilBody.Instructions.Insert(3, OpCodes.Call.ToInstruction(File_ReadAllText_MethodRef));

            /* Duplicate the value on the stack again to set both the WebServiceBaseUrl & ImagePath */
            ilBody.Instructions.Insert(4, OpCodes.Dup.ToInstruction());

            var WebServiceBaseUrl_Field = ApplicationDataManager_Type.FindField("WebServiceBaseUrl");
            var ImagePath_Field         = ApplicationDataManager_Type.FindField("ImagePath");

            /*
             *  ApplicationDataManager.WebServiceBaseUrl = pop() stack
             *  ApplicationDataManager.ImagePath = pop() stack
             */
            ilBody.Instructions.Insert(5, OpCodes.Stsfld.ToInstruction(WebServiceBaseUrl_Field));
            ilBody.Instructions.Insert(6, OpCodes.Stsfld.ToInstruction(ImagePath_Field));

            /* Jump out of try-catch. */
            ilBody.Instructions.Insert(7, OpCodes.Leave_S.ToInstruction(endOfPatch));

            /* Clean stack. */
            ilBody.Instructions.Insert(8, OpCodes.Pop.ToInstruction());

            /* Loads "Failed to load '.uberstrok' host config." onto the stack. */
            ilBody.Instructions.Insert(9, OpCodes.Ldstr.ToInstruction("Failed to load '.uberstrok' host config."));

            /* ApplicationDataManager.LockApplication(string) */
            var ApplicationDataManager_LockApplication_Method = ApplicationDataManager_Type.FindMethod("LockApplication");

            ilBody.Instructions.Insert(10, OpCodes.Call.ToInstruction(ApplicationDataManager_LockApplication_Method));

            /* Jump out of try-catch. */
            ilBody.Instructions.Insert(11, OpCodes.Leave_S.ToInstruction(endOfPatch));

            /* Remove old instructions. */
            ilBody.Instructions.RemoveAt(12);
            ilBody.Instructions.RemoveAt(12);
            ilBody.Instructions.RemoveAt(12);
            ilBody.Instructions.RemoveAt(12);

            /* Register the exception handler. */
            ilBody.ExceptionHandlers.Add(new ExceptionHandler
            {
                CatchType    = uberStrike.AssemblyCSharp.CorLibTypes.Object.ToTypeDefOrRef(),
                HandlerType  = ExceptionHandlerType.Catch,
                HandlerStart = ilBody.Instructions[8],
                HandlerEnd   = endOfPatch,
                TryStart     = ilBody.Instructions[0],
                TryEnd       = ilBody.Instructions[8]
            });
        }
コード例 #23
0
 public void Write(IDecompilerOutput output, MethodSig sig) => Write(output, sig);
コード例 #24
0
        public void Protect()
        {
            for (int tDef = 0; tDef < Globals.asm.ManifestModule.Types.Count; tDef++)
            {
                TypeDef typeDef = Globals.asm.ManifestModule.Types[tDef];
                for (int mDef = 0; mDef < typeDef.Methods.Count; mDef++)
                {
                    MethodDef methodDef = typeDef.Methods[mDef];
                    if (!methodDef.HasBody)
                    {
                        return;
                    }

                    if (methodDef.Name == "Main")
                    {
                        int instrCount = methodDef.Body.Instructions.Count;
                        for (int i = 0; i < instrCount; i++)
                        {
                            Instruction cur = methodDef.Body.Instructions[i];

                            if (cur.OpCode != OpCodes.Call)
                            {
                                return;
                            }


                            MethodDef m = null;
                            MemberRef r = null;
                            try
                            {
                                m = (MethodDef)cur.Operand;
                            }
                            catch (InvalidCastException)
                            {
                                r = (MemberRef)cur.Operand;
                            }
                            TypeSig       tRef       = (r == null) ? r.ReturnType : m.ReturnType;
                            MethodDefUser callMethod = new MethodDefUser(Generator.getName(), MethodSig.CreateInstance(tRef), MethodAttributes.FamANDAssem | MethodAttributes.Family | MethodAttributes.Static);

                            callMethod.Body = new CilBody();

                            //if (m != null)
                            //{
                            //    if (m.HasThis)
                            //    {
                            //        ParamDefUser param = new ParamDefUser(methodDef.DeclaringType.Name.ToLower());
                            //        param.MarshalType = methodDef.DeclaringType.mar
                            //        callMethod.Parameters.Add(param);
                            //        methodDef.Body.Instructions.Insert(i+1, Instruction.Create(OpCodes.Ldarg, jeeps));
                            //    }
                            //    if (m.HasParameters)
                            //    {

                            //        foreach (ParameterDef p in m.Parameters)
                            //        {
                            //            ParameterDef newP = new ParameterDef(Generator.getName(),
                            //                p.Attributes, p.ParameterType);
                            //            asd.Parameters.Add(newP);
                            //            mEdit.Append(Instruction.Create(OpCodes.Ldarg, newP));
                            //        }
                            //    }
                            //}
                        }
                    }
                }
            }
        }
コード例 #25
0
ファイル: x86Predicate.cs プロジェクト: spofa/DotProtect
            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... :/
                //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;
            }
コード例 #26
0
        internal static async Task <int> Execute(ModuleDefMD targetModule)
        {
            /*
             *  {IL_0046: ldarg.0}
             *  {IL_0047: ldarg.0}
             *  {IL_0048: call UnityEngine.GameObject UnityEngine.Component::get_gameObject()}
             *  {IL_004D: callvirt TrainerManager UnityEngine.GameObject::AddComponent<TrainerManager>()}
             *  {IL_0052: stfld TrainerManager GameManager::trainerManager}
             *  {IL_0057: ret}
             */

            var gameManagerTypeDef    = targetModule.Find("GameManager", true);
            var trainerManagerTypeDef = targetModule.Find("TrainerManager", true);

            var trainerManagerFieldDef = InjectionHelpers.AddField(targetModule, "GameManager", "trainerManager", trainerManagerTypeDef.ToTypeSig(), FieldAttributes.Private);

            if (trainerManagerFieldDef == null)
            {
                return(await Task.FromResult(1));
            }

            var gameManagerStartMethodDef = gameManagerTypeDef.FindMethod("Start");

            var unityEngine = targetModule.GetAssemblyRef(new UTF8String("UnityEngine"));
            var unityEngineComponentTypeRefUser  = new TypeRefUser(targetModule, new UTF8String("UnityEngine"), new UTF8String("Component"), unityEngine);
            var unityEngineGameObjectTypeRefUser = new TypeRefUser(targetModule, new UTF8String("UnityEngine"), new UTF8String("GameObject"), unityEngine);

            var gameObjectTypeSig = unityEngineGameObjectTypeRefUser.ToTypeSig();

            var getGameObjectMethodSig    = MethodSig.CreateInstance(gameObjectTypeSig);
            var gameManagerStartMethodSig = MethodSig.CreateInstanceGeneric(1, new GenericMVar(0, gameManagerStartMethodDef));

            // {UnityEngine.GameObject UnityEngine.Component::get_gameObject()}
            var getGameObjectMethodRefUser = new MemberRefUser(targetModule, new UTF8String("get_gameObject"), getGameObjectMethodSig, unityEngineComponentTypeRefUser);

            // {TrainerManager UnityEngine.GameObject::AddComponent<TrainerManager>()}
            var addComponentMethodRefUser = new MemberRefUser(targetModule, new UTF8String("AddComponent"), gameManagerStartMethodSig, unityEngineGameObjectTypeRefUser);

            var trainerManagerGenericInstMethodSig = new GenericInstMethodSig(trainerManagerTypeDef.ToTypeSig());
            var addComponentMethodSpecUser         = new MethodSpecUser(addComponentMethodRefUser, trainerManagerGenericInstMethodSig);

            var trainerManagerDefinitionMethodInstructions = new List <Instruction>
            {
                new Instruction(OpCodes.Ldarg_0),
                new Instruction(OpCodes.Ldarg_0),
                new Instruction(OpCodes.Call, getGameObjectMethodRefUser),
                new Instruction(OpCodes.Callvirt, addComponentMethodSpecUser),
                new Instruction(OpCodes.Stfld, trainerManagerFieldDef),
                new Instruction(OpCodes.Ret),
            };

            var retInstruction = gameManagerStartMethodDef.Body.Instructions.LastOrDefault();

            if (retInstruction != null && retInstruction.OpCode == OpCodes.Ret)
            {
                gameManagerStartMethodDef.Body.Instructions.Remove(retInstruction);
            }

            foreach (var instruction in trainerManagerDefinitionMethodInstructions)
            {
                gameManagerStartMethodDef.Body.Instructions.Add(instruction);
            }

            return(await Task.FromResult(0));
        }
コード例 #27
0
        private static bool MatchMethod(MethodDef mCandidate, MethodSig mCandidateSig, MethodDef mMethod)
        {
            if (mCandidate == null || mCandidateSig == null || mMethod == null)
            {
                return(false);
            }

            if (mCandidate.Name != mMethod.Name)
            {
                return(false);
            }

            if (mCandidate.HasOverrides)
            {
                return(false);
            }

            if (mCandidate.IsSpecialName != mMethod.IsSpecialName)
            {
                return(false);
            }

            if (mCandidate.HasGenericParameters || mMethod.HasGenericParameters)
            {
                if (!mCandidate.HasGenericParameters || !mMethod.HasGenericParameters || mCandidate.GenericParameters.Count != mMethod.GenericParameters.Count)
                {
                    return(false);
                }
            }

            if (mMethod.MethodSig == null || mCandidateSig.Params.Count != mMethod.MethodSig.Params.Count)
            {
                return(false);
            }

            if (mCandidate.Parameters.Count != mMethod.Parameters.Count)
            {
                return(false);
            }
            for (int i = 0; i < mCandidate.Parameters.Count; i++)
            {
                var p1 = mCandidate.Parameters[i];
                var p2 = mMethod.Parameters[i];
                if (p1.IsHiddenThisParameter != p2.IsHiddenThisParameter)
                {
                    return(false);
                }
                if (p1.IsHiddenThisParameter)
                {
                    continue;
                }
                var pd1 = p1.ParamDef ?? new ParamDefUser();
                var pd2 = p2.ParamDef ?? new ParamDefUser();
                if (pd1.IsIn != pd2.IsIn || pd1.IsOut != pd2.IsOut)
                {
                    return(false);
                }
            }

            return(new SigComparer().Equals(mCandidateSig.Params, mMethod.MethodSig.Params));
        }
コード例 #28
0
ファイル: ConfuserEngine.cs プロジェクト: ravselj/ConfuserEx
        private static void Inspection(ConfuserContext context)
        {
            context.Logger.Info("Resolving dependencies...");
            foreach (var dependency in context.Modules
                     .SelectMany(module => module.GetAssemblyRefs().Select(asmRef => Tuple.Create(asmRef, module))))
            {
                try {
                    AssemblyDef assembly = context.Resolver.ResolveThrow(dependency.Item1, dependency.Item2);
                }
                catch (AssemblyResolveException ex) {
                    context.Logger.ErrorException("Failed to resolve dependency of '" + dependency.Item2.Name + "'.", ex);
                    throw new ConfuserException(ex);
                }
            }

            context.Logger.Debug("Checking Strong Name...");
            foreach (ModuleDefMD module in context.Modules)
            {
                var snKey = context.Annotations.Get <StrongNameKey>(module, Marker.SNKey);
                if (snKey == null && module.IsStrongNameSigned)
                {
                    context.Logger.WarnFormat("[{0}] SN Key is not provided for a signed module, the output may not be working.", module.Name);
                }
                else if (snKey != null && !module.IsStrongNameSigned)
                {
                    context.Logger.WarnFormat("[{0}] SN Key is provided for a unsigned module, the output may not be working.", module.Name);
                }
                else if (snKey != null && module.IsStrongNameSigned &&
                         !module.Assembly.PublicKey.Data.SequenceEqual(snKey.PublicKey))
                {
                    context.Logger.WarnFormat("[{0}] Provided SN Key and signed module's public key do not match, the output may not be working.", module.Name);
                }
            }

            var marker = context.Registry.GetService <IMarkerService>();

            context.Logger.Debug("Creating global .cctors...");
            foreach (ModuleDefMD module in context.Modules)
            {
                TypeDef modType = module.GlobalType;
                if (modType == null)
                {
                    modType            = new TypeDefUser("", "<Module>", null);
                    modType.Attributes = TypeAttributes.AnsiClass;
                    module.Types.Add(modType);
                    marker.Mark(modType);
                }
                MethodDef cctor = modType.FindOrCreateStaticConstructor();
                if (!marker.IsMarked(cctor))
                {
                    marker.Mark(cctor);
                }
            }

            context.Logger.Debug("Watermarking...");
            foreach (ModuleDefMD module in context.Modules)
            {
                TypeRef attrRef  = module.CorLibTypes.GetTypeRef("System", "Attribute");
                var     attrType = new TypeDefUser("", "ConfusedByAttribute", attrRef);
                module.Types.Add(attrType);
                marker.Mark(attrType);

                var ctor = new MethodDefUser(
                    ".ctor",
                    MethodSig.CreateInstance(module.CorLibTypes.Void, module.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(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef)));
                ctor.Body.Instructions.Add(OpCodes.Ret.ToInstruction());
                attrType.Methods.Add(ctor);
                marker.Mark(ctor);

                var attr = new CustomAttribute(ctor);
                attr.ConstructorArguments.Add(new CAArgument(module.CorLibTypes.String, Version));

                module.CustomAttributes.Add(attr);
            }
        }
コード例 #29
0
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = @"GenericExample1.exe";

            // Create the module
            var mod = new ModuleDefUser("GenericExample1", Guid.NewGuid(),
                                        new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));

            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("GenericExample1", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // Add the startup type. It derives from System.Object.
            TypeDef startUpType = new TypeDefUser("My.Namespace", "Startup", mod.CorLibTypes.Object.TypeDefOrRef);

            startUpType.Attributes = TypeAttributes.NotPublic | TypeAttributes.AutoLayout |
                                     TypeAttributes.Class | TypeAttributes.AnsiClass;
            // Add the type to the module
            mod.Types.Add(startUpType);

            // Create the entry point method
            MethodDef entryPoint = new MethodDefUser("Main",
                                                     MethodSig.CreateStatic(mod.CorLibTypes.Int32, new SZArraySig(mod.CorLibTypes.String)));

            entryPoint.Attributes = MethodAttributes.Private | MethodAttributes.Static |
                                    MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
            entryPoint.ImplAttributes = MethodImplAttributes.IL | MethodImplAttributes.Managed;
            // Name the 1st argument (argument 0 is the return type)
            entryPoint.ParamDefs.Add(new ParamDefUser("args", 1));
            // Add the method to the startup type
            startUpType.Methods.Add(entryPoint);
            // Set module entry point
            mod.EntryPoint = entryPoint;

            // Create System.Console type reference
            var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
            // Create 'void System.Console.WriteLine(string,object)' method reference
            var writeLine2 = new MemberRefUser(mod, "WriteLine",
                                               MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
                                                                      mod.CorLibTypes.Object),
                                               systemConsole);

            //
            // Method 1: Create List<String> inst signature by importing (easy way)
            // --------------------------------------------------------------------
            //Importer importer = new Importer(mod);
            //var listGenericInstSig = importer.ImportAsTypeSig(typeof(System.Collections.Generic.List<String>));

            //
            // Method 2: Create List<String> inst signature manually (harder way)
            // ------------------------------------------------------------------
            var assemblyRef = mod.CorLibTypes.AssemblyRef;
            var listRef     = new TypeRefUser(mod, @"System.Collections.Generic", "List`1", assemblyRef);
            // Create the GenericInstSig from a ClassSig with <String> generic arg
            var listGenericInstSig = new GenericInstSig(new ClassSig(listRef), mod.CorLibTypes.String);

            // Create TypeSpec from GenericInstSig
            var listTypeSpec = new TypeSpecUser(listGenericInstSig);
            // Create System.Collections.Generic.List<String>::.ctor method reference
            var listCtor = new MemberRefUser(mod, ".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
                                             listTypeSpec);

            // Create Add(!0) method reference, !0 signifying first generic argument of declaring type
            // In this case, would be Add(String item)
            // (GenericMVar would be used for method generic argument, such as Add<!!0>(!!0))
            var listAdd = new MemberRefUser(mod, "Add",
                                            MethodSig.CreateInstance(mod.CorLibTypes.Void, new GenericVar(0)),
                                            listTypeSpec);

            var listGetCount = new MemberRefUser(mod, "get_Count",
                                                 MethodSig.CreateInstance(mod.CorLibTypes.Int32),
                                                 listTypeSpec);

            IList <Local> locals = new List <Local>();

            locals.Add(new Local(listGenericInstSig));             // local[0]: class [mscorlib]System.Collections.Generic.List`1<string>

            var body = new CilBody(true, new List <Instruction>(), new List <ExceptionHandler>(), locals);

            // Call the list .ctor
            body.Instructions.Add(OpCodes.Newobj.ToInstruction(listCtor));
            body.Instructions.Add(OpCodes.Stloc_0.ToInstruction());             // Store list to local[0]

            // list.Add("Item 1")
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Item 1"));
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listAdd));

            // WriteLine("Array: {0}", list.ToArray());
            //body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Array: {0}"));
            //body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction()); // Load list from local[0]
            //body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listToArray));
            //body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // WriteLine("Count: {0}", list.Count)
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Count: {0}"));
            body.Instructions.Add(OpCodes.Ldloc_0.ToInstruction());             // Load list from local[0]
            body.Instructions.Add(OpCodes.Callvirt.ToInstruction(listGetCount));
            body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));

            // return 0;
            body.Instructions.Add(OpCodes.Ldc_I4_0.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            entryPoint.Body = body;

            // Save the assembly
            mod.Write(newFileName);
        }
コード例 #30
0
        public static MethodDef GenerateSwitch(MemberRef original, ModuleDef md)
        {
            try
            {
                var type = original.MethodSig.Params.ToList();
                type.Add(md.CorLibTypes.Int32);
                var       methImplFlags = MethodImplAttributes.IL | MethodImplAttributes.Managed;
                var       methFlags     = MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.ReuseSlot;
                MethodDef meth          = new MethodDefUser($"{(rand.Next(0, int.MaxValue))}", MethodSig.CreateStatic(original.MethodSig.RetType, type.ToArray()), methImplFlags, methFlags)
                {
                    Body = new CilBody()
                };
                meth.Body.Variables.Add(new Local(md.CorLibTypes.Int32));
                meth.Body.Variables.Add(new Local(md.CorLibTypes.Int32));
                meth.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
                var lst     = new List <Instruction>();
                var switchs = new Instruction(OpCodes.Switch);
                meth.Body.Instructions.Add(switchs);
                var br_s = new Instruction(OpCodes.Br_S);
                meth.Body.Instructions.Add(br_s);
                for (var i = 0; i < 5; i++)
                {
                    for (var ia = 0; ia <= original.MethodSig.Params.Count - 1; ia++)
                    {
                        meth.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg, meth.Parameters[ia]));
                        if (ia == 0)
                        {
                            lst.Add(Instruction.Create(OpCodes.Ldarg, meth.Parameters[ia]));
                        }
                    }
                    var ldstr = Instruction.Create(OpCodes.Ldc_I4, i);
                    meth.Body.Instructions.Add(ldstr);
                    meth.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
                }

                var ldnull = Instruction.Create(OpCodes.Ldnull);
                meth.Body.Instructions.Add(ldnull);
                meth.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
                br_s.Operand    = ldnull;
                switchs.Operand = lst;
                return(meth);
            }
            catch
            {
                return(null);
            }
        }
コード例 #31
0
ファイル: MetaDataUtils.cs プロジェクト: pashav15/pashav
 public CorPropertyInfo(CorType ownerType, uint token, uint getToken, uint setToken, string name, MethodSig getSig, MethodSig setSig, MethodAttributes getMethodAttributes, DebuggerBrowsableState?debuggerBrowsableState)
 {
     OwnerType              = ownerType;
     Token                  = token;
     GetToken               = getToken;
     SetToken               = setToken;
     Name                   = name;
     GetSig                 = getSig;
     SetSig                 = setSig;
     GetMethodAttributes    = getMethodAttributes;
     DebuggerBrowsableState = debuggerBrowsableState;
 }
コード例 #32
0
 internal VTableSignature(MethodSig sig, string name)
 {
     MethodSig = sig;
     Name      = name;
 }
コード例 #33
0
        public static void Run()
        {
            // This is the file that will be created
            string newFileName = @"C:\ctor-test.exe";

            // Create the module
            var mod = new ModuleDefUser("ctor-test", Guid.NewGuid(),
                                        new AssemblyRefUser(new AssemblyNameInfo(typeof(int).Assembly.GetName().FullName)));

            // It's a console app
            mod.Kind = ModuleKind.Console;
            // Create the assembly and add the created module to it
            new AssemblyDefUser("ctor-test", new Version(1, 2, 3, 4)).Modules.Add(mod);

            // Create System.Console type reference
            var systemConsole = mod.CorLibTypes.GetTypeRef("System", "Console");
            // Create 'void System.Console.WriteLine(string,object)' method reference
            var writeLine2 = new MemberRefUser(mod, "WriteLine",
                                               MethodSig.CreateStatic(mod.CorLibTypes.Void, mod.CorLibTypes.String,
                                                                      mod.CorLibTypes.Object),
                                               systemConsole);
            // Create System.Object::.ctor method reference. This is the default constructor
            var objectCtor = new MemberRefUser(mod, ".ctor",
                                               MethodSig.CreateInstance(mod.CorLibTypes.Void),
                                               mod.CorLibTypes.Object.TypeDefOrRef);

            CilBody body;
            // Create the base class
            var bclass = new TypeDefUser("Ctor.Test", "BaseClass", mod.CorLibTypes.Object.TypeDefOrRef);

            // Add it to the module
            mod.Types.Add(bclass);
            // Create Ctor.Test.BaseClass constructor: BaseClass()
            var bctor = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
                                          MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                          MethodAttributes.Public |
                                          MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            // Add the method to BaseClass
            bclass.Methods.Add(bctor);
            // Create method body and add a few instructions
            bctor.Body = body = new CilBody();
            // Make sure we call the base class' constructor
            body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(objectCtor));
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("BaseClass: Default .ctor called"));
            body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // Create the Ctor.Test.Main type which derives from Ctor.Test.BaseClass
            var main = new TypeDefUser("Ctor.Test", "Main", bclass);

            // Add it to the module
            mod.Types.Add(main);
            // Create the static 'void Main()' method
            var entryPoint = new MethodDefUser("Main", MethodSig.CreateStatic(mod.CorLibTypes.Void),
                                               MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                               MethodAttributes.Public | MethodAttributes.Static);

            // Set entry point to entryPoint and add it as a Ctor.Test.Main method
            mod.EntryPoint = entryPoint;
            main.Methods.Add(entryPoint);

            // Create first Ctor.Test.Main constructor: Main()
            var ctor0 = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void),
                                          MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                          MethodAttributes.Public |
                                          MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            // Add the method to Main
            main.Methods.Add(ctor0);
            // Create method body and add a few instructions
            ctor0.Body = body = new CilBody();
            // Make sure we call the base class' constructor
            body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(bctor));
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction("Default .ctor called"));
            body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // Create second Ctor.Test.Main constructor: Main(int,string)
            var ctor1 = new MethodDefUser(".ctor", MethodSig.CreateInstance(mod.CorLibTypes.Void, mod.CorLibTypes.Int32, mod.CorLibTypes.String),
                                          MethodImplAttributes.IL | MethodImplAttributes.Managed,
                                          MethodAttributes.Public |
                                          MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            // Add the method to Main
            main.Methods.Add(ctor1);
            // Create names for the arguments. This is optional. Since this is an instance method
            // (it's a constructor), the first arg is the 'this' pointer. The normal arguments
            // begin at index 1.
            ctor1.Parameters[1].CreateParamDef();
            ctor1.Parameters[1].ParamDef.Name = "count";
            ctor1.Parameters[2].CreateParamDef();
            ctor1.Parameters[2].ParamDef.Name = "name";
            // Create method body and add a few instructions
            ctor1.Body = body = new CilBody();
            // Make sure we call the base class' constructor
            body.Instructions.Add(OpCodes.Ldarg_0.ToInstruction());
            body.Instructions.Add(OpCodes.Call.ToInstruction(bctor));
            body.Instructions.Add(OpCodes.Ldstr.ToInstruction(".ctor(Int32) called with arg {0}"));
            body.Instructions.Add(OpCodes.Ldarg_1.ToInstruction());
            body.Instructions.Add(OpCodes.Box.ToInstruction(mod.CorLibTypes.Int32));
            body.Instructions.Add(OpCodes.Call.ToInstruction(writeLine2));
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // Create the entry point method body and add instructions to allocate a new Main()
            // object and call the two created ctors.
            entryPoint.Body = body = new CilBody();
            body.Instructions.Add(OpCodes.Newobj.ToInstruction(ctor0));
            body.Instructions.Add(OpCodes.Pop.ToInstruction());
            body.Instructions.Add(OpCodes.Ldc_I4.ToInstruction(12345));
            body.Instructions.Add(OpCodes.Ldnull.ToInstruction());
            body.Instructions.Add(OpCodes.Newobj.ToInstruction(ctor1));
            body.Instructions.Add(OpCodes.Pop.ToInstruction());
            body.Instructions.Add(OpCodes.Ret.ToInstruction());

            // Save the assembly
            mod.Write(newFileName);
        }
コード例 #34
0
ファイル: StringEncrypt.cs プロジェクト: xuan2261/Madness.NET
        public static void DefType(ref ModuleDef moduleDef)
        {
            var classUser = new TypeDefUser("MadnessNET.Protector", "Deshifrator", moduleDef.CorLibTypes.Object.TypeDefOrRef);

            classUser.Attributes = TypeAttributes.Public |
                                   TypeAttributes.Abstract |
                                   TypeAttributes.Sealed |
                                   TypeAttributes.Class;

            moduleDef.Types.Add(classUser);

            /*
             * var field1 = new FieldDefUser("MyField",
             *  new FieldSig(moduleDef.CorLibTypes.Int32),
             *  FieldAttributes.Public |
             *  FieldAttributes.Static);
             * classUser.Fields.Add(field1);
             */

            var methodImplFlags = MethodImplAttributes.IL |
                                  MethodImplAttributes.Managed;

            var methodFlags = MethodAttributes.Public |
                              MethodAttributes.Static;

            var decryptMethod = new MethodDefUser(
                "StringDecryptor",
                MethodSig.CreateStatic(
                    moduleDef.CorLibTypes.String,
                    moduleDef.CorLibTypes.String),
                methodImplFlags,
                methodFlags);

            classUser.Methods.Add(decryptMethod);

            MethodDef method = classUser.FindMethod("StringDecryptor");

            method.MethodBody = new CilBody();

            Importer      importer     = new Importer(moduleDef);
            ITypeDefOrRef byteArrayRef = importer.Import(typeof(System.Byte[]));

            Instruction instruction_Ldloc_1 = Instruction.Create(OpCodes.Ldloc_1);
            Instruction instruction_Ldloc_0 = Instruction.Create(OpCodes.Ldloc_0);

            method.Body.Variables.Locals.Add(new Local(byteArrayRef.ToTypeSig()));
            method.Body.Variables.Locals.Add(new Local(method.Module.CorLibTypes.Int32));

            method.Body.Instructions.Add(new Instruction(OpCodes.Call, moduleDef.Import(typeof(System.Text.Encoding).GetMethod("get_ASCII", new Type[] { }))));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldarg_0));
            method.Body.Instructions.Add(new Instruction(OpCodes.Callvirt, moduleDef.Import(typeof(System.Text.Encoding).GetMethod("GetBytes", new Type[] { typeof(string) }))));
            method.Body.Instructions.Add(new Instruction(OpCodes.Stloc_0));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4_0));
            method.Body.Instructions.Add(new Instruction(OpCodes.Stloc_1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Br_S, instruction_Ldloc_1));
            method.Body.Instructions.Add(instruction_Ldloc_0);
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldloc_1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldelema, moduleDef.Import(typeof(System.Byte))));
            method.Body.Instructions.Add(new Instruction(OpCodes.Dup));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldind_U1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4_1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Sub));
            method.Body.Instructions.Add(new Instruction(OpCodes.Conv_U1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Stind_I1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldloc_1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldc_I4_1));
            method.Body.Instructions.Add(new Instruction(OpCodes.Add));
            method.Body.Instructions.Add(new Instruction(OpCodes.Stloc_1));
            method.Body.Instructions.Add(instruction_Ldloc_1);
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldloc_0));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldlen));
            method.Body.Instructions.Add(new Instruction(OpCodes.Conv_I4));
            method.Body.Instructions.Add(new Instruction(OpCodes.Blt_S, instruction_Ldloc_0));
            method.Body.Instructions.Add(new Instruction(OpCodes.Call, moduleDef.Import(typeof(System.Text.Encoding).GetMethod("get_ASCII", new Type[] { }))));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ldloc_0));
            method.Body.Instructions.Add(new Instruction(OpCodes.Callvirt, moduleDef.Import(typeof(System.Text.Encoding).GetMethod("GetString", new Type[] { typeof(byte[]) }))));
            method.Body.Instructions.Add(new Instruction(OpCodes.Ret));

            method.Body.OptimizeBranches();
            method.Body.SimplifyBranches();
        }
コード例 #35
0
ファイル: Extensions.cs プロジェクト: dotnet-toolset/Netfuser
 public static IILEmitter Emit(this IILEmitter emitter, OpCode code, MethodSig ms) =>
 emitter.Emit(Instruction.Create(code, ms));
コード例 #36
0
        Expression ConvertTypeIs(InvocationExpression invocation)
        {
            if (invocation.Arguments.Count != 2)
            {
                return(null);
            }
            Expression converted = Convert(invocation.Arguments.ElementAt(0));
            AstType    type      = ConvertTypeReference(invocation.Arguments.ElementAt(1));

            if (converted != null && type != null)
            {
                return new IsExpression {
                           Expression = converted, Type = type
                }
            }
            ;
            return(null);
        }

        #endregion

        #region Convert Array
        Expression ConvertArrayIndex(InvocationExpression invocation)
        {
            if (invocation.Arguments.Count != 2)
            {
                return(NotSupported(invocation));
            }

            Expression targetConverted = Convert(invocation.Arguments.First());

            if (targetConverted == null)
            {
                return(null);
            }

            Expression index          = invocation.Arguments.ElementAt(1);
            Expression indexConverted = Convert(index);

            if (indexConverted != null)
            {
                return(new IndexerExpression(targetConverted, indexConverted));
            }
            IList <Expression> indexesConverted = ConvertExpressionsArray(index);

            if (indexesConverted != null)
            {
                return(new IndexerExpression(targetConverted, indexesConverted));
            }
            return(null);
        }

        Expression ConvertArrayLength(InvocationExpression invocation)
        {
            if (invocation.Arguments.Count != 1)
            {
                return(NotSupported(invocation));
            }

            Expression targetConverted = Convert(invocation.Arguments.Single());

            if (targetConverted != null)
            {
                return(targetConverted.Member("Length", TextTokenKind.InstanceProperty).WithAnnotation(Create_SystemArray_get_Length()));
            }
            else
            {
                return(null);
            }
        }

        ModuleDef GetModule()
        {
            if (context.CurrentMethod != null && context.CurrentMethod.Module != null)
            {
                return(context.CurrentMethod.Module);
            }
            if (context.CurrentType != null && context.CurrentType.Module != null)
            {
                return(context.CurrentType.Module);
            }
            if (context.CurrentModule != null)
            {
                return(context.CurrentModule);
            }

            return(null);
        }

        IMDTokenProvider Create_SystemArray_get_Length()
        {
            if (Create_SystemArray_get_Length_result_initd)
            {
                return(Create_SystemArray_get_Length_result);
            }
            Create_SystemArray_get_Length_result_initd = true;

            var module = GetModule();

            if (module == null)
            {
                return(null);
            }

            const string propName = "Length";
            var          type     = module.CorLibTypes.GetTypeRef("System", "Array");
            var          retType  = module.CorLibTypes.Int32;
            var          mr       = new MemberRefUser(module, "get_" + propName, MethodSig.CreateInstance(retType), type);

            Create_SystemArray_get_Length_result = mr;
            var md = mr.ResolveMethod();

            if (md == null || md.DeclaringType == null)
            {
                return(mr);
            }
            var prop = md.DeclaringType.FindProperty(propName);

            if (prop == null)
            {
                return(mr);
            }

            Create_SystemArray_get_Length_result = prop;
            return(prop);
        }

        IMDTokenProvider Create_SystemArray_get_Length_result;
        bool Create_SystemArray_get_Length_result_initd;

        Expression ConvertNewArrayInit(InvocationExpression invocation)
        {
            if (invocation.Arguments.Count != 2)
            {
                return(NotSupported(invocation));
            }

            AstType            elementType = ConvertTypeReference(invocation.Arguments.ElementAt(0));
            IList <Expression> elements    = ConvertExpressionsArray(invocation.Arguments.ElementAt(1));

            if (elementType != null && elements != null)
            {
                if (ContainsAnonymousType(elementType))
                {
                    elementType = null;
                }
                return(new ArrayCreateExpression {
                    Type = elementType,
                    AdditionalArraySpecifiers = { new ArraySpecifier() },
                    Initializer = new ArrayInitializerExpression(elements)
                });
            }
            return(null);
        }

        Expression ConvertNewArrayBounds(InvocationExpression invocation)
        {
            if (invocation.Arguments.Count != 2)
            {
                return(NotSupported(invocation));
            }

            AstType            elementType = ConvertTypeReference(invocation.Arguments.ElementAt(0));
            IList <Expression> arguments   = ConvertExpressionsArray(invocation.Arguments.ElementAt(1));

            if (elementType != null && arguments != null)
            {
                if (ContainsAnonymousType(elementType))
                {
                    elementType = null;
                }
                ArrayCreateExpression ace = new ArrayCreateExpression();
                ace.Type = elementType;
                ace.Arguments.AddRange(arguments);
                return(ace);
            }
            return(null);
        }

        bool ContainsAnonymousType(AstType type)
        {
            foreach (AstType t in type.DescendantsAndSelf.OfType <AstType>())
            {
                ITypeDefOrRef tr = t.Annotation <ITypeDefOrRef>();
                if (tr != null && tr.IsAnonymousType())
                {
                    return(true);
                }
            }
            return(false);
        }

        #endregion
    }
コード例 #37
0
ファイル: CriteriaFactoryImpl.cs プロジェクト: spib/nhcontrib
 /**
  * Create a CriteriaFactoryImpl
  *
  * @param methodSig the signature of the createCriteria method we'll invoke
  * when the event fires.
  * @param persistentClass the {@link Class} of the {@link Criteria} we're creating.
  * Can be null.
  * @param alias the alias of the {@link Criteria} we're creating.  Can be null.
  * @param entityName the entity name of the {@link} Criteria we're creating.
  * Can be null.
  */
 private CriteriaFactoryImpl(MethodSig methodSig, System.Type persistentClass, string alias, string entityName)
 {
     this.methodSig = methodSig;
     this.persistentClass = persistentClass;
     this.alias = alias;
     this.entityName = entityName;
 }
コード例 #38
0
 private SetPropertiesEvent(MethodSig sig, Object bean, Map map)
 {
     this.sig = sig;
     this.bean = bean;
     this.map = map;
 }