コード例 #1
0
		public void SetBody(MethodBodyReader mbr) {
			Flags2 = mbr.Flags2;
			MaxStack = mbr.MaxStack;
			Locals = mbr.Locals;
			Instructions = mbr.Instructions;
			ExceptionHandlers = mbr.ExceptionHandlers;
		}
コード例 #2
0
        /// <summary>
        /// Declare the local variables used in the new method.
        /// </summary>
        private void DeclareLocalVariableTypes(ILGenerator generator, MethodBodyReader reader)
        {
            List <Type> locals = reader.GetLocalTypes();

            // Declare all the local variable types.
            foreach (Type type in locals)
            {
                generator.DeclareLocal(type);
            }
        }
コード例 #3
0
        public static List <ILInstruction> GetInstructions(MethodBase method)
        {
            var dummy = new DynamicMethod("Dummy", typeof(void), new Type[] { });

            if (method.GetMethodBody() is null)
            {
                return(null);
            }
            return(MethodBodyReader.GetInstructions(dummy.GetILGenerator(), method));
        }
コード例 #4
0
        public MethodBody GetMethodBody(uint rid, RVA rva, IList <Parameter> parameters)
        {
            var dm = GetDumpedMethod(rid);

            if (dm == null)
            {
                return(null);
            }
            return(MethodBodyReader.CreateCilBody(module, dm.code, dm.extraSections, parameters, dm.mhFlags, dm.mhMaxStack, dm.mhCodeSize, dm.mhLocalVarSigTok));
        }
コード例 #5
0
        internal static MethodBase TargetMethod()
        {
            var shwGetter = ReflectionHelper.Settings.GetProperty("ShowHaxchiWarning").GetGetMethod();

            return((from method in ReflectionHelper.NusGrabberForm.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
                    where method.GetParameters().Length == 1 &&
                    method.GetParameters()[0].ParameterType.IsAbstract
                    let instructions = MethodBodyReader.GetInstructions(null, method)
                                       where instructions.Any(i => i.opcode == OpCodes.Callvirt && ((MethodInfo)i.operand) == shwGetter)
                                       select method).FirstOrDefault());
        }
コード例 #6
0
        public bool GetMethodBody(uint rid, RVA rva, IList <Parameter> parameters, GenericParamContext gpContext, out MethodBody methodBody)
        {
            var dm = GetDumpedMethod(rid);

            if (dm == null)
            {
                methodBody = null;
                return(false);
            }
            methodBody = MethodBodyReader.CreateCilBody(module, dm.code, dm.extraSections, parameters, dm.mhFlags, dm.mhMaxStack, dm.mhCodeSize, dm.mhLocalVarSigTok, gpContext);
            return(true);
        }
コード例 #7
0
        public static HashSet <int> ComputeLabels(MethodBase definition)
        {
            var labels = new HashSet <int>();
            var body   = definition.GetMethodBody();

            if (body == null)
            {
                return(labels);
            }
            var instructions = MethodBodyReader.GetInstructions(definition);

            foreach (var instruction in instructions)
            {
                var opcodeStr = instruction.OpCode.Value;
                switch (opcodeStr)
                {
                case ObcodeIntValues.Beq:
                case ObcodeIntValues.BeqS:
                case ObcodeIntValues.Bne:
                case ObcodeIntValues.BneS:
                case ObcodeIntValues.Bge:
                case ObcodeIntValues.BgeS:
                case ObcodeIntValues.Bgt:
                case ObcodeIntValues.BgtS:
                case ObcodeIntValues.BrTrueS:
                case ObcodeIntValues.BrTrue:
                case ObcodeIntValues.BrZero:
                case ObcodeIntValues.BrZeroS:
                case ObcodeIntValues.Blt:
                case ObcodeIntValues.BltS:
                case ObcodeIntValues.BrS:
                case ObcodeIntValues.Br:
                case ObcodeIntValues.Leave:
                case ObcodeIntValues.LeaveS:
                {
                    var offset = ((Instruction)instruction.Operand).Offset;
                    AddLabelIfDoesntExist(offset, labels);
                }
                break;

                case ObcodeIntValues.Switch:
                {
                    var offsets = (Instruction[])instruction.Operand;
                    foreach (var offset in offsets)
                    {
                        AddLabelIfDoesntExist(offset.Offset, labels);
                    }
                }
                break;
                }
            }
            return(labels);
        }
コード例 #8
0
        private void ParseInstructions(MethodInfo mi, string fromId)
        {
            MethodBodyReader mr = GetMethodBodyReader(mi);

            if (mr == null)
            {
                return;
            }
            if (mr.instructions == null)
            {
                return;
            }

            foreach (ILInstruction instruction in mr.instructions)
            {
                if (CheckWorker())
                {
                    break;
                }
                if (instruction.Operand == null)
                {
                    continue;
                }
                if (instruction.Code.OperandType != OperandType.InlineMethod)
                {
                    continue;
                }

                Type   declType;
                string name, calledId;
                GetInstrDetails(instruction, out name, out declType, out calledId);
                if (name == null)
                {
                    continue;
                }


                calledId = declType.FullName;
                BaseItem calledItem = _projectBrowser.Lookup(calledId);

                if (calledItem == null)
                {
                    continue;
                }
                // Or external types - optional?

                if (_addedNodes.ContainsKey(calledId))
                {
                    AddEdge(fromId, calledId, EdgeStyle.NormalArrow);
                }
            }
        }
コード例 #9
0
        public static IEnumerable <CodeInstruction> TranspileStart(IEnumerable <CodeInstruction> instructions)
        {
            MethodBase             ReplacementMethod             = typeof(CheckPlantGrowthStageActionPatch).GetMethod("Start");
            List <ILInstruction>   MethodILInstructions          = MethodBodyReader.GetInstructions(ReplacementMethod);
            List <CodeInstruction> ReplacementMethodInstructions = new List <CodeInstruction>();

            foreach (ILInstruction MethodILInstruction in MethodILInstructions)
            {
                ReplacementMethodInstructions.Add(MethodILInstruction.GetCodeInstruction());
            }

            return(ReplacementMethodInstructions);
        }
コード例 #10
0
ファイル: PatchTestHelper.cs プロジェクト: x0n1c/Nitrox
        public static List <CodeInstruction> GetInstructionsFromMethod(MethodInfo targetMethod)
        {
            Validate.NotNull(targetMethod);

            List <CodeInstruction> instructions = new List <CodeInstruction>();

            foreach (ILInstruction instruction in MethodBodyReader.GetInstructions(targetMethod))
            {
                instructions.Add(instruction.GetCodeInstruction());
            }

            return(instructions);
        }
コード例 #11
0
 private void lbAvailableMethodsList_SelectedValueChanged(object sender, EventArgs e)
 {
     try
     {
         MethodInfo mi = methods[lbAvailableMethodsList.SelectedIndex];
         SDILReader.MethodBodyReader mr = new MethodBodyReader(mi);
         rchMethodBodyCode.Clear();
         rchMethodBodyCode.Text = mr.GetBodyCode();
     }
     catch
     {
     }
 }
コード例 #12
0
 protected MethodBodyReader GetMethodBodyReader(MethodInfo mi)
 {
     SDILReader.MethodBodyReader mr = null;
     try
     {
         mr = new MethodBodyReader(mi);
     }
     catch (System.IO.FileNotFoundException)
     {
         // We will already have been warned about missing files during the load.
     }
     return(mr);
 }
コード例 #13
0
        private void ParseInstructions(string methodNodeId, MethodInfo mi)
        {
            MethodBodyReader mr = GetMethodBodyReader(mi);

            if (mr == null)
            {
                return;
            }
            if (mr.instructions == null)
            {
                return;
            }

            foreach (ILInstruction instruction in mr.instructions)
            {
                if (CheckWorker())
                {
                    break;
                }
                if (instruction.Operand == null)
                {
                    continue;
                }
                if (instruction.Code.OperandType != OperandType.InlineMethod)
                {
                    continue;
                }

                Type   declType;
                string name, calledId;
                GetInstrDetails(instruction, out name, out declType, out calledId);
                if (name == null)
                {
                    continue;
                }

                if (declType != null)
                {
                    if (declType == (_activeItem as TypeItem).TypeRef)
                    {
                        // Only link to nodes we've added. This may or may not include
                        // property get set methods, depending on the setting.
                        if (_addedNodes.ContainsKey(calledId))
                        {
                            AddEdge(methodNodeId, calledId, EdgeStyle.NormalArrow);
                        }
                    }
                }
            }
        }
コード例 #14
0
        public void GetCalledMethodsTest()
        {
            MethodBase       method = MethodBase.GetCurrentMethod();
            MethodBodyReader reader = new MethodBodyReader(method);

            IList <MethodBase> calledMethods = reader.GetCalledMethods(false, false);

            foreach (MethodBase calledMethod in calledMethods)
            {
                Console.WriteLine("     {0}.{1}", calledMethod.ReflectedType, calledMethod.Name);
            }

            Assert.IsTrue(calledMethods.Count > 3);
        }
コード例 #15
0
        internal static IEnumerable <CodeInstruction> LoadDefinitionsTranspiler(
            IEnumerable <CodeInstruction> instructions)
        {
            var replacementMethod             = AccessTools.Method(typeof(TileDatabasePatches), nameof(LoadDefinitionsInit));
            var methodIlInstructions          = MethodBodyReader.GetInstructions(new DynamicMethod(Guid.NewGuid().ToString(), typeof(object), new Type[0]).GetILGenerator(), replacementMethod);
            var replacementMethodInstructions = new List <CodeInstruction>();

            foreach (var methodIlInstruction in methodIlInstructions)
            {
                replacementMethodInstructions.Add(methodIlInstruction.GetCodeInstruction());
            }

            return(replacementMethodInstructions);
        }
コード例 #16
0
    public static byte[] changeCode(byte[] Before, object Me, aops A, List <object> O)
    {
        List <Type>          Tnew      = O.Select(x => x.GetType());
        List <byte>          Q         = new List <byte>(Before);
        var                  N         = new MethodBodyReader(Addition.module, Before);
        List <ILInstruction> CastClass = N.instructions.FindAll(x => x.Code == OpCodes.Castclass);

        if (CastClass.Count > Tnew.Count)
        {
            CastClass.RemoveRange(Tnew.Count, CastClass.Count - Tnew.Count);
        }
        var Told = CastClass.Select(x => (Type)x.Operand);
        Dictionary <Type, List <Type> > Compare = new Dictionary <Type, List <Type> >();
        List <Type> L;

        for (int i = 0; i < Tnew.Count; i++)
        {
            if (Compare.TryGetValue(Tnew[i], out L))
            {
                if (!L.Contains(Told[i]))
                {
                    L.Add(Told[i]);
                }
            }
            else
            {
                Compare.Add(Tnew[i], new List <Type>());
                Compare[Tnew[i]].Add(Told[i]);
            }
        }

        Predicate <OpCode> M = (x) => ((x == OpCodes.Call) || (x == OpCodes.Calli) || (x == OpCodes.Callvirt));
        Predicate <OpCode> C = (x) => (x == OpCodes.Newobj);
        Predicate <OpCode> F = (x) => ((x == OpCodes.Stsfld) || (x == OpCodes.Stfld) || (x == OpCodes.Ldsfld) ||
                                       (x == OpCodes.Ldfld) || (x == OpCodes.Ldsflda) || (x == OpCodes.Ldflda));

        for (int i = 0; i < Tnew.Count; i++)
        {
            changeEntities <MethodInfo>(N, M, Compare, Tnew, i, Q);
            changeEntities <ConstructorInfo>(N, C, Compare, Tnew, i, Q);
            changeEntities <FieldInfo>(N, F, Compare, Tnew, i, Q);
            changeEntity <Type>(Q, CastClass[i], Tnew[i]);
        }

        /* var I = new MethodBodyReader(Addition.module, Q.ToArray());
         * MessageBox.Show(N.GetBodyCode(Before) + I.GetBodyCode(Q.ToArray()));*/
        return(Q.ToArray());
    }
コード例 #17
0
        public static ILMethodInfo Disassemble(MethodInfo method)
        {
            if (method == null)
            {
                return(null);
            }

            var reader = new MethodBodyReader(method);
            var ilCode = reader.GetBodyCode();

            if (string.IsNullOrWhiteSpace(ilCode))
            {
                return(null);
            }

            var localVariables = new List <LocalVariableInfo>();

            if (reader.LocalVariables != null)
            {
                localVariables.AddRange(reader.LocalVariables);
            }

            var lines = ilCode?.Split('\n').ToList();

            lines.RemoveAll(string.IsNullOrWhiteSpace);
            var ilCodeLines = lines.ToArray();

            var ilLinesInfos = new OpCodeInfo[ilCodeLines?.Length ?? 0];

            if (reader.instructions == null)
            {
                return(null);
            }
            for (var index = 0; index < reader.instructions.Count && index < ilLinesInfos.Length; index++)
            {
                var instruction = reader.instructions[index];
                var d           = ILNavigator.TryGetOpCodeDescription(instruction.Code);
                if (d == null)
                {
                    continue;
                }
                ilLinesInfos[index] = d;
            }

            var instructions = FindBlocks(ilCodeLines, reader.instructions, ilLinesInfos);

            return(new ILMethodInfo(localVariables, instructions));
        }
コード例 #18
0
        public static DissectResult Dissect(MethodBase mb)
        {
            MethodBodyReader mbr = new MethodBodyReader(mb);
            WaitDissector    wd  = new WaitDissector(mbr.instructions);

            wd.Dissect();
            EnsureNotInitBehavior(mbr.instructions, wd.DissectionPoints[0], mb.Name);
            List <MethodCode> states = new List <MethodCode>();
            HashSet <int>     exits  = new HashSet <int>(wd.DissectionPoints);

            foreach (int ilIndex in wd.DissectionPoints)
            {
                MethodCode mc = MethodCode.Create(mb, ilIndex + 1, exits);
                states.Add(mc);
            }
            return(new DissectResult(states, wd.DissectionPoints));
        }
コード例 #19
0
        private static void ScanMethodsForLocalizerInvocations(IReflect callerType, IDictionary <string, List <string> > translations)
        {
            foreach (var callerMethod in callerType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic |
                                                               BindingFlags.Static | BindingFlags.Instance |
                                                               BindingFlags.CreateInstance))
            {
                if (GetStringMethods.Contains(callerMethod))
                {
                    continue; // skip calling self
                }
                var callerBody = callerMethod.GetMethodBody();
                if (callerBody == null)
                {
                    continue; // no body
                }
                var instructions = MethodBodyReader.GetInstructions(callerMethod);

                foreach (Instruction instruction in instructions)
                {
                    if (instruction.Operand is MethodInfo methodInfo && GetStringMethods.Contains(methodInfo) &&
                        instruction.Previous.Operand is string value)
                    {
                        string scope;
                        if (instruction.Previous.Previous != null &&
                            instruction.Previous.Previous.Operand is FieldInfo field)
                        {
                            scope = field.DeclaringType != null && field.DeclaringType.IsGenericType
                                ? field.DeclaringType.NormalizeResourceControllerName().Replace("_T", string.Empty)
                                : field.DeclaringType?.Name ?? string.Empty;
                        }
                        else
                        {
                            scope = string.Empty;
                        }

                        if (!translations.TryGetValue(scope, out var list))
                        {
                            translations.Add(scope, list = new List <string>());
                        }

                        list.Add(value);
                    }
                }
            }
        }
コード例 #20
0
ファイル: GameEventUtilities.cs プロジェクト: EulBart/Thread
    private void LookForMethodCallers()
    {
        AssemblyScanner.Register(type => {
            var methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

            foreach (MethodInfo methodInfo in methods)
            {
                if (methodInfo.IsAbstract)
                {
                    continue;
                }
                MethodBody methodBody = methodInfo.GetMethodBody();
                if (methodBody == null)
                {
                    continue;
                }
                try{
                    List <Instruction> instructions = MethodBodyReader.GetInstructions(methodInfo);
                    foreach (var instruction in instructions)
                    {
                        MethodInfo calledMethod = instruction.Operand as MethodInfo;
                        if (calledMethod == null)
                        {
                            continue;
                        }
                        foreach (var users in allusers)
                        {
                            if (users.TryAddCall(type, methodInfo, calledMethod, instruction))
                            {
                                break;
                            }
                        }
                    }
                }catch (Exception e)
                {
                    //Debug.LogError("On " + methodInfo.DeclaringType.Name+"."+methodInfo.Name);
                    //Debug.LogException(e);
                }
            }
        },
                                 AssemblyScanner.OnlyProject
                                 );
        AssemblyScanner.Scan();
    }
コード例 #21
0
ファイル: MetaLinker.cs プロジェクト: afrog33k/CodeRefractor
        public static List <MethodInterpreter> ComputeDependencies(MethodBase definition)
        {
            var resultDict = new Dictionary <string, MethodInterpreter>();
            var body       = definition.GetMethodBody();

            if (body == null)
            {
                return(new List <MethodInterpreter>());
            }
            var instructions = MethodBodyReader.GetInstructions(definition);

            foreach (var instruction in instructions)
            {
                var opcodeStr = instruction.OpCode.Value;
                switch (opcodeStr)
                {
                case ObcodeIntValues.CallVirt:
                case ObcodeIntValues.Call:
                case ObcodeIntValues.CallInterface:
                {
                    var operand = (MethodBase)instruction.Operand;
                    if (operand == null)
                    {
                        break;
                    }
                    AddMethodIfNecessary(operand, resultDict);
                    break;
                }

                case ObcodeIntValues.NewObj:
                {
                    var operand = (ConstructorInfo)instruction.Operand;
                    if (operand == null)
                    {
                        break;
                    }
                    AddMethodIfNecessary(operand, resultDict);
                    break;
                }
                }
            }
            return(resultDict.Values.ToList());
        }
コード例 #22
0
        static void ReadAssemblies(List <string> assemblyList)
        {
            assemblyList.ForEach(a =>
            {
                Console.WriteLine("Reading {0}", a);
                Assembly assembly = Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, a));
                List <Type> types = assembly.GetTypes().ToList();
                types.ForEach(t => {
                    List <MethodInfo> methods = t.GetMethods().ToList();
                    methods.ForEach(m => {
                        MethodBase methodBase = m;

                        ParameterInfo[] parameters = m.GetParameters();
                        string functionName        = string.Format("{0}({1})",
                                                                   m.Name,
                                                                   String.Join(", ", parameters.Select(p => p.ParameterType.FullName).ToArray())
                                                                   );
                        int functId = db.WriteFunction(t.Namespace, t.Name, functionName);

                        var instructions = MethodBodyReader.GetInstructions(methodBase);

                        foreach (Instruction instruction in instructions)
                        {
                            MethodInfo methodInfo = instruction.Operand as MethodInfo;

                            if (methodInfo != null)
                            {
                                Type type = methodInfo.DeclaringType;
                                ParameterInfo[]  instParameters = methodInfo.GetParameters();

                                string instName = string.Format("{0}({1})",
                                                                methodInfo.Name,
                                                                String.Join(", ", instParameters.Select(p => p.ParameterType.FullName).ToArray())
                                                                );

                                db.WriteReference(functId, type.Namespace, type.Name, instName);
                            }
                        }
                    });
                });
            });
        }
コード例 #23
0
        public void InstructionsTest()
        {
            MethodBase       method   = MethodBase.GetCurrentMethod();
            ILanguageInfo    language = new CsLanguageInfo();
            MethodBodyReader reader   = new MethodBodyReader(method, language);

            language.RegisterNamespace("System");
            language.RegisterNamespace("System.Collections.Generic");
            language.RegisterNamespace("System.Reflection");
            language.RegisterNamespace("Arebis.Reflection");

            IList <ILInstruction> instructions = reader.Instructions;

            foreach (ILInstruction instruction in instructions)
            {
                Console.WriteLine("     {0}", instruction.GetCode());
            }

            Assert.IsTrue(instructions.Count > 12);
        }
コード例 #24
0
        public void Process(CrRuntimeLibrary crRuntime)
        {
            if (Kind != MethodKind.Default)
            {
                return;
            }
            if (Interpreted)
            {
                return;
            }
            if (HandlePlatformInvokeMethod(Method))
            {
                return;
            }
            if (Method.GetMethodBody() == null)
            {
                return;
            }
            var instructions = MethodBodyReader.GetInstructions(Method);

            var labelList = ComputeLabels(Method);

            MidRepresentation.Method = Method;


            MidRepresentation.Vars.SetupLocalVariables(Method);
            var evaluator        = new EvaluatorStack();
            var operationFactory = new MetaMidRepresentationOperationFactory(MidRepresentation, evaluator);

            for (var index = 0; index < instructions.Length; index++)
            {
                var instruction = instructions[index];
                EvaluateInstuction(instruction, operationFactory, labelList, crRuntime);
            }
            //Ensure.IsTrue(evaluator.Count == 0, "Stack not empty!");
            AnalyzeProperties.Setup(MidRepresentation.Vars.Arguments, MidRepresentation.Vars.VirtRegs,
                                    MidRepresentation.Vars.LocalVars);
            Interpreted = true;
        }
コード例 #25
0
        private static HashSet <string> DumpKeybinds(MethodInfo method)
        {
            var instructions = new List <CodeInstruction> {
            };

            MethodBodyReader.GetInstructions(GetILGenerator(), method).ForEach(
                (instr) => instructions.Add(instr.GetCodeInstruction())
                ); // Uses Harmony's internals, because the proper method is not present in SRML's version of Harmony.

            var set = new HashSet <string> {
            };

            foreach (CodeInstruction instr in instructions)
            {
                if (instr.opcode == OpCodes.Ldstr &&
                    ((string)instr.operand).StartsWith(Keybind.KEYBIND_PREFIX))
                {
                    set.Add((string)instr.operand);
                }
            }

            return(set);
コード例 #26
0
        static void Check(Type checkType, string methodName)
        {
            MethodBase methodBase   = checkType.GetMethod(methodName, new Type[] { typeof(Int32) });
            var        instructions = MethodBodyReader.GetInstructions(methodBase);

            foreach (Instruction instruction in instructions)
            {
                MethodInfo methodInfo = instruction.Operand as MethodInfo;

                if (methodInfo != null)
                {
                    Type            type       = methodInfo.DeclaringType;
                    ParameterInfo[] parameters = methodInfo.GetParameters();

                    Console.WriteLine("{0}.{1}({2});",
                                      type.FullName,
                                      methodInfo.Name,
                                      String.Join(", ", parameters.Select(p => p.ParameterType.FullName + " " + p.Name).ToArray())
                                      );
                }
            }
        }
コード例 #27
0
        /// <summary>
        /// Checks if the given method has a IL instruction that SETS (therefore, it changes the value) a customized field
        /// </summary>
        private static IEnumerable <FieldInfo> GetCustomizedFieldsChangedByMethod(MethodBase partModuleMethod, ModuleDefinition definition)
        {
            var listOfFields = new HashSet <FieldInfo>();

            var method       = DynamicTools.CreateDynamicMethod(partModuleMethod, "read");
            var instructions = MethodBodyReader.GetInstructions(method.GetILGenerator(), partModuleMethod);

            //OpCodes.Stfld is the opcode for SETTING the value of a field
            foreach (var instruction in instructions.Where(i => i.opcode == OpCodes.Stfld))
            {
                if (!(instruction.operand is FieldInfo operand))
                {
                    continue;
                }

                if (definition.Fields.Any(f => f.FieldName == operand.Name))
                {
                    listOfFields.Add(operand);
                }
            }

            return(listOfFields);
        }
コード例 #28
0
ファイル: MSILAnalysis.cs プロジェクト: cephdon/systemsharp
        /// <summary>
        /// Constructs an instance based on a method or constructor
        /// </summary>
        /// <param name="mi">a method or constructor</param>
        public ILInstructionInfo(MethodBase mi)
        {
            Method = mi;
            MethodBodyReader mbr = new MethodBodyReader(mi);

            Instructions = mbr.instructions;
            MethodBody body = mi.GetMethodBody();

            Body = body;
            byte[] msil = body.GetILAsByteArray();
            Marshal = new ILInstruction()
            {
                Offset = msil.Length,
                Index  = Instructions.Count,
                Code   = OpCodes.Ret
            };
            _imap = new ILInstruction[msil.Length + 1];
            foreach (ILInstruction ili in Instructions)
            {
                _imap[ili.Offset] = ili;
            }
            _imap[msil.Length] = Marshal;
            InitHandlerMaps();
        }
コード例 #29
0
        public static List <ILInstruction> GetInstructions(MethodInfo method)
        {
            var dummy = new DynamicMethod("Dummy", typeof(void), new Type[] { });

            return(MethodBodyReader.GetInstructions(dummy.GetILGenerator(), method));
        }
コード例 #30
0
        public void CallCompiler(string inputAssemblyName, string outputExeName)
        {
            var commandLineParse = CommandLineParse.Instance;

            if (!String.IsNullOrEmpty(inputAssemblyName))
            {
                commandLineParse.ApplicationInputAssembly = inputAssemblyName;
            }
            if (!String.IsNullOrEmpty(outputExeName))
            {
                commandLineParse.ApplicationNativeExe = outputExeName;
            }
            var dir = Directory.GetCurrentDirectory();

            inputAssemblyName = Path.Combine(dir, commandLineParse.ApplicationInputAssembly);
            var asm        = Assembly.LoadFile(inputAssemblyName);
            var definition = asm.EntryPoint;
            var start      = Environment.TickCount;


            OptimizationLevelBase.ClearOptimizations();
            OptimizationLevelBase.Instance = new OptimizationLevels();
            OptimizationLevelBase.Instance.EnabledCategories.Clear();
            OptimizationLevelBase.Instance.EnabledCategories.AddRange(OptimizationList);
            OptimizationLevelBase.UpdateOptimizationsFromCategories(OptimizationLevelBase.OptimizationPasses);
            OptimizationLevelBase.SortOptimizations();

//            OptimizationLevelBase.Instance = new OptimizationLevels();
//            OptimizationLevelBase.OptimizerLevel = 2;
//            OptimizationLevelBase.Instance.EnabledCategories.Add(OptimizationCategories.All);
            var closureEntities = ClosureEntitiesUtils.BuildClosureEntities(definition, typeof(CrString).Assembly);
            var sb  = closureEntities.BuildFullSourceCode();
            var end = Environment.TickCount - start;

            CompilerErrors += String.Format("Compilation time: {0} ms", end);

            var opcodes = closureEntities.MethodImplementations;

            var intermediateOutput = "-------------IL:-------------\n";

            foreach (var opcode in opcodes)
            {
                intermediateOutput += " " + opcode.Key + ": \n";

                if (opcode.Value.Kind != MethodKind.CilInstructions)
                {
                    intermediateOutput += "// Provided By Framework     \n\n";
                    continue;
                }

                try
                {
                    var instructions = MethodBodyReader.GetInstructions(((CilMethodInterpreter)opcode.Value).Method);
                    foreach (var op in instructions)
                    {
                        var oper = string.Format("\t{0}", op);;
                        intermediateOutput += "     " + oper + "\n";
                    }
                }
                catch (Exception)
                {
                    intermediateOutput += "// Method has no body     \n\n";
                }



                intermediateOutput += "\n";
            }

            intermediateOutput += "\n-------------IR:-------------\n";

            foreach (var opcode in opcodes)
            {
                intermediateOutput += " " + opcode.Key + ": \n";

                if (opcode.Value.Kind != MethodKind.CilInstructions)
                {
                    intermediateOutput += "// Provided By Framework     \n\n";
                    continue;
                }
                var cilInterpreter = (CilMethodInterpreter)opcode.Value;
                foreach (var op in cilInterpreter.MidRepresentation.LocalOperations)
                {
                    var oper = string.Format("{1}\t({0})", op.Kind, op);;
                    intermediateOutput += "     " + oper + "\n";
                }

                intermediateOutput += "\n";
            }


            OutputCode = sb.ToString();

            ILCode = intermediateOutput;



            //TODO: Make this call all the different compilers i.e. TestHelloWorld_GCC.exe etc...
        }
コード例 #31
0
		void Decrypt(IBinaryReader reader, int delegateTypeToken, ISimpleDeobfuscator simpleDeobfuscator) {
			var delegateType = module.ResolveToken(delegateTypeToken) as TypeDef;
			if (delegateType == null)
				throw new ApplicationException("Couldn't find delegate type");

			int delToken, encMethToken, encDeclToken;
			if (!GetTokens(delegateType, out delToken, out encMethToken, out encDeclToken))
				throw new ApplicationException("Could not find encrypted method tokens");
			if (delToken != delegateTypeToken)
				throw new ApplicationException("Invalid delegate type token");
			var encType = module.ResolveToken(encDeclToken) as ITypeDefOrRef;
			if (encType == null)
				throw new ApplicationException("Invalid declaring type token");
			var encMethod = module.ResolveToken(encMethToken) as MethodDef;
			if (encMethod == null)
				throw new ApplicationException("Invalid encrypted method token");

			var bodyReader = new MethodBodyReader(module, reader);
			bodyReader.Read(encMethod);
			bodyReader.RestoreMethod(encMethod);
			Logger.v("Restored method {0} ({1:X8}). Instrs:{2}, Locals:{3}, Exceptions:{4}",
					Utils.RemoveNewlines(encMethod.FullName),
					encMethod.MDToken.ToInt32(),
					encMethod.Body.Instructions.Count,
					encMethod.Body.Variables.Count,
					encMethod.Body.ExceptionHandlers.Count);
			delegateTypes.Add(delegateType);
			simpleDeobfuscator.MethodModified(encMethod);
		}
コード例 #32
0
        /// <summary>
        /// Saves localizable JSON data in the current working directory for the provided assembly.
        /// </summary>
        /// <param name="assembly">Assembly to save localization data from.</param>
        public static void ExportLocalizableForAssembly(Assembly assembly)
        {
            var types = assembly.GetTypes();

            var outList = new Dictionary <string, LocEntry>();

            foreach (var type in types.Where(x => x.IsClass || x.IsAbstract))
            {
                var toParse = new List <MethodBase>();
                toParse.AddRange(type.GetTypeInfo().DeclaredConstructors);
                toParse.AddRange(type.GetTypeInfo().DeclaredMethods);

                foreach (var method in toParse)
                {
                    try
                    {
                        var instructions = MethodBodyReader.GetInstructions(method);

                        foreach (var instruction in instructions)
                        {
                            if (instruction.OpCode == OpCodes.Call)
                            {
                                var methodInfo = instruction.Operand as MethodInfo;

                                if (methodInfo != null && methodInfo.IsStatic)
                                {
                                    var methodType = methodInfo.DeclaringType;
                                    var parameters = methodInfo.GetParameters();

                                    if (!methodInfo.Name.Contains("Localize"))
                                    {
                                        continue;
                                    }

                                    Console.WriteLine("->({0}) {1}.{2}.{3}({4});",
                                                      method.DeclaringType.Assembly.GetName().Name,
                                                      type.FullName,
                                                      methodType.Name,
                                                      methodInfo.Name,
                                                      string.Join(", ",
                                                                  parameters.Select(p =>
                                                                                    p.ParameterType.FullName + " " + p.Name).ToArray())
                                                      );

                                    var entry = new LocEntry
                                    {
                                        Message     = instruction.Previous.Operand as string,
                                        Description = $"{type.Name}.{method.Name}"
                                    };

                                    var key = instruction.Previous.Previous.Operand as string;

                                    if (string.IsNullOrEmpty(key))
                                    {
                                        throw new Exception(
                                                  $"Key was empty for message: {entry.Message} (from {entry.Description})");
                                    }

                                    if (outList.Any(x => x.Key == key))
                                    {
                                        if (outList.Any(x => x.Key == key && x.Value.Message != entry.Message))
                                        {
                                            throw new Exception(
                                                      $"Message with key {key} has previous appearance but other fallback text in {entry.Description}");
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine($"    ->{key} - {entry.Message} (from {entry.Description})");
                                        outList.Add(key, entry);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"Couldn't parse {method.Name}:\n{ex}");
                    }
                }
            }

            File.WriteAllText($"{GetAssemblyName(assembly)}_Localizable.json", JsonConvert.SerializeObject(outList,
                                                                                                           new JsonSerializerSettings
            {
                Formatting = Formatting.Indented
            }));
        }
コード例 #33
0
ファイル: DotNetRedirection.cs プロジェクト: JimmyJune/DotWeb
        public void Run()
        {
            string path = @"F:\src\git\DotWeb\build\bin\Debug\DotWeb.Sample.Script.dll";

            var reader = GetReaderFor(path);

            var sourceType = Type.GetType("DotWeb.Sample.Script.Test.Sandbox, DotWeb.Sample.Script");
            var sourceMethod = sourceType.GetConstructor(Type.EmptyTypes);
            var token = new SymbolToken(sourceMethod.MetadataToken);

            var symMethod = reader.GetMethod(token);
            var points = new SequencePointCollection(symMethod);

            string fileName = "Test.dll";
            string outDir = @"F:\src\git\DotWeb\build\bin\Debug";
            string outPath = Path.Combine(outDir, fileName);

            var asmName = new AssemblyName("Test");
            var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Save, outDir);
            var moduleBuilder = asmBuilder.DefineDynamicModule(fileName, fileName, true);
            var typeBuilder = moduleBuilder.DefineType("Test", System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Class);
            var ctorBuilder = typeBuilder.DefineConstructor(System.Reflection.MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes);
            var ilg = ctorBuilder.GetILGenerator();

            var methodReader = new MethodBodyReader(sourceMethod);

            foreach (var il in methodReader.Instructions) {
                var point = points.GetSequencePointAtOffset(il.Offset);
                if (point != null) {
                    var doc = GetDocumentWriterFor(point.Document, moduleBuilder);
                    ilg.MarkSequencePoint(doc, point.Line, point.Column, point.EndLine, point.EndColumn);
                }

                if (il.Operand is MethodInfo) {
                    RedirectMethodInfo(il);
                }
                Emit(ilg, il);
            }

            typeBuilder.CreateType();
            asmBuilder.Save(fileName);

            var asm = Assembly.LoadFile(outPath);
            var types = asm.GetTypes();
            var type = asm.GetType("Test");
            var obj = Activator.CreateInstance(type);
        }
コード例 #34
0
		public MethodDefReader(ImageReader imageReader, IBinaryReader reader) {
			this.bmd = new BabelMethodDef();
			this.methodRefReader = new MethodRefReader(imageReader, reader, bmd);
			this.methodBodyReader = new MethodBodyReader(imageReader, reader);
		}