Example #1
0
        // use parsed IL codes and emit them to a generator

        public void FinalizeILCodes(List <TranspilerImpl> transpilers, Label?endLabel)
        {
            if (generator == null)
            {
                return;
            }

            // pass1 - define labels and add them to instructions that are target of a jump
            ilInstructions.ForEach(ilInstruction =>
            {
                switch (ilInstruction.opcode.OperandType)
                {
                case OperandType.InlineSwitch:
                    {
                        var targets = ilInstruction.operand as ILInstruction[];
                        if (targets != null)
                        {
                            var labels = new List <Label>();
                            foreach (var target in targets)
                            {
                                var label = generator.DefineLabel();
                                target.labels.Add(label);
                                labels.Add(label);
                            }
                            ilInstruction.argument = labels.ToArray();
                        }
                        break;
                    }

                case OperandType.ShortInlineBrTarget:
                case OperandType.InlineBrTarget:
                    {
                        var target = ilInstruction.operand as ILInstruction;
                        if (target != null)
                        {
                            var label = generator.DefineLabel();
                            target.labels.Add(label);
                            ilInstruction.argument = label;
                        }
                        break;
                    }
                }
            });

            // pass2 - filter through all processors
            var codeTranspiler = new CodeTranspiler(ilInstructions);

            transpilers.ForEach(transpiler => codeTranspiler.Add(transpiler));
            var codeInstructions = codeTranspiler.GetResult(generator, method)
                                   .Select(instruction =>
            {
                // TODO - improve the logic here. for now, we replace all short jumps
                //        with long jumps regardless of how far the jump is
                //
                new Dictionary <OpCode, OpCode>
                {
                    { OpCodes.Beq_S, OpCodes.Beq },
                    { OpCodes.Bge_S, OpCodes.Bge },
                    { OpCodes.Bge_Un_S, OpCodes.Bge_Un },
                    { OpCodes.Bgt_S, OpCodes.Bgt },
                    { OpCodes.Bgt_Un_S, OpCodes.Bgt_Un },
                    { OpCodes.Ble_S, OpCodes.Ble },
                    { OpCodes.Ble_Un_S, OpCodes.Ble_Un },
                    { OpCodes.Blt_S, OpCodes.Blt },
                    { OpCodes.Blt_Un_S, OpCodes.Blt_Un },
                    { OpCodes.Bne_Un_S, OpCodes.Bne_Un },
                    { OpCodes.Brfalse_S, OpCodes.Brfalse },
                    { OpCodes.Brtrue_S, OpCodes.Brtrue },
                    { OpCodes.Br_S, OpCodes.Br }
                }.Do(pair =>
                {
                    if (instruction.opcode == pair.Key)
                    {
                        instruction.opcode = pair.Value;
                    }
                });

                if (instruction.opcode == OpCodes.Ret && endLabel != null)
                {
                    instruction.opcode  = OpCodes.Br;
                    instruction.operand = endLabel;
                }
                return(instruction);
            });

            // pass3 - mark labels and emit codes
            codeInstructions.Do(codeInstruction =>
            {
                codeInstruction.labels.ForEach(label => Emitter.MarkLabel(generator, label));

                var code    = codeInstruction.opcode;
                var operand = codeInstruction.operand;

                if (code.OperandType == OperandType.InlineNone)
                {
                    Emitter.Emit(generator, code);
                }
                else
                {
                    if (operand == null)
                    {
                        throw new Exception("Wrong null argument: " + codeInstruction);
                    }
                    var emitMethod = EmitMethodForType(operand.GetType());
                    if (emitMethod == null)
                    {
                        throw new Exception("Unknown Emit argument type " + operand.GetType() + " in " + codeInstruction);
                    }
                    if (HarmonyInstance.DEBUG)
                    {
                        FileLog.Log(Emitter.CodePos(generator) + code + " " + Emitter.FormatArgument(operand));
                    }
                    emitMethod.Invoke(generator, new object[] { code, operand });
                }
            });
        }
Example #2
0
        // use parsed IL codes and emit them to a generator
        //
        public void FinalizeILCodes(List <MethodInfo> transpilers, List <Label> endLabels, List <ExceptionBlock> endBlocks)
        {
            if (generator == null)
            {
                return;
            }

            // pass1 - define labels and add them to instructions that are target of a jump
            //
            foreach (var ilInstruction in ilInstructions)
            {
                switch (ilInstruction.opcode.OperandType)
                {
                case OperandType.InlineSwitch:
                {
                    var targets = ilInstruction.operand as ILInstruction[];
                    if (targets != null)
                    {
                        var labels = new List <Label>();
                        foreach (var target in targets)
                        {
                            var label = generator.DefineLabel();
                            target.labels.Add(label);
                            labels.Add(label);
                        }
                        ilInstruction.argument = labels.ToArray();
                    }
                    break;
                }

                case OperandType.ShortInlineBrTarget:
                case OperandType.InlineBrTarget:
                {
                    var target = ilInstruction.operand as ILInstruction;
                    if (target != null)
                    {
                        var label = generator.DefineLabel();
                        target.labels.Add(label);
                        ilInstruction.argument = label;
                    }
                    break;
                }
                }
            }

            // pass2 - filter through all processors
            //
            var codeTranspiler = new CodeTranspiler(ilInstructions);

            transpilers.Do(transpiler => codeTranspiler.Add(transpiler));
            var codeInstructions = codeTranspiler.GetResult(generator, method);

            // pass3 - remove RET if it appears at the end
            while (true)
            {
                var lastInstruction = codeInstructions.LastOrDefault();
                if (lastInstruction == null || lastInstruction.opcode != OpCodes.Ret)
                {
                    break;
                }

                // remember any existing labels
                endLabels.AddRange(lastInstruction.labels);

                codeInstructions.RemoveAt(codeInstructions.Count - 1);
            }

            // pass4 - mark labels and exceptions and emit codes
            //
            var idx = 0;

            codeInstructions.Do(codeInstruction =>
            {
                // mark all labels
                codeInstruction.labels.Do(label => Emitter.MarkLabel(generator, label));

                // start all exception blocks
                // TODO: we ignore the resulting label because we have no way to use it
                //
                codeInstruction.blocks.Do(block => { Label?label; Emitter.MarkBlockBefore(generator, block, out label); });

                var code    = codeInstruction.opcode;
                var operand = codeInstruction.operand;

                // replace RET with a jump to the end (outside this code)
                if (code == OpCodes.Ret)
                {
                    var endLabel = generator.DefineLabel();
                    code         = OpCodes.Br;
                    operand      = endLabel;
                    endLabels.Add(endLabel);
                }

                // replace short jumps with long ones (can be optimized but requires byte counting, not instruction counting)
                if (shortJumps.TryGetValue(code, out var longJump))
                {
                    code = longJump;
                }

                var emitCode = true;

                //if (code == OpCodes.Leave || code == OpCodes.Leave_S)
                //{
                //	// skip LEAVE on EndExceptionBlock
                //	if (codeInstruction.blocks.Any(block => block.blockType == ExceptionBlockType.EndExceptionBlock))
                //		emitCode = false;

                //	// skip LEAVE on next instruction starts a new exception handler and we are already in
                //	if (idx < instructions.Length - 1)
                //		if (instructions[idx + 1].blocks.Any(block => block.blockType != ExceptionBlockType.EndExceptionBlock))
                //			emitCode = false;
                //}

                if (emitCode)
                {
                    switch (code.OperandType)
                    {
                    case OperandType.InlineNone:
                        Emitter.Emit(generator, code);
                        break;

                    case OperandType.InlineSig:

                        // TODO the following will fail because we do not convert the token (operand)
                        // All the decompilers can show the arguments correctly, we just need to find out how
                        //
                        if (operand == null)
                        {
                            throw new Exception("Wrong null argument: " + codeInstruction);
                        }
                        if ((operand is int) == false)
                        {
                            throw new Exception("Wrong Emit argument type " + operand.GetType() + " in " + codeInstruction);
                        }
                        Emitter.Emit(generator, code, (int)operand);

                        /*
                         * // the following will only work if we can convert the original signature token to the required arguments
                         * //
                         * var callingConvention = System.Runtime.InteropServices.CallingConvention.ThisCall;
                         * var returnType = typeof(object);
                         * var parameterTypes = new[] { typeof(object) };
                         * Emitter.EmitCalli(generator, code, callingConvention, returnType, parameterTypes);
                         *
                         * var callingConventions = System.Reflection.CallingConventions.Standard;
                         * var optionalParameterTypes = new[] { typeof(object) };
                         * Emitter.EmitCalli(generator, code, callingConventions, returnType, parameterTypes, optionalParameterTypes);
                         */
                        break;

                    default:
                        if (operand == null)
                        {
                            throw new Exception("Wrong null argument: " + codeInstruction);
                        }
                        var emitMethod = EmitMethodForType(operand.GetType());
                        if (emitMethod == null)
                        {
                            throw new Exception("Unknown Emit argument type " + operand.GetType() + " in " + codeInstruction);
                        }
                        if (HarmonyInstance.DEBUG)
                        {
                            FileLog.LogBuffered(Emitter.CodePos(generator) + code + " " + Emitter.FormatArgument(operand));
                        }
                        emitMethod.Invoke(generator, new object[] { code, operand });
                        break;
                    }
                }

                codeInstruction.blocks.Do(block => Emitter.MarkBlockAfter(generator, block));

                idx++;
            });
        }
Example #3
0
        // use parsed IL codes and emit them to a generator
        //
        public void FinalizeILCodes(List <Label> endLabels, List <ExceptionBlock> endBlocks)
        {
            if (generator == null)
            {
                return;
            }

            // pass1 - define labels and add them to instructions that are target of a jump
            //
            foreach (var ilInstruction in ilInstructions)
            {
                switch (ilInstruction.opcode.OperandType)
                {
                case OperandType.InlineSwitch:
                {
                    var targets = ilInstruction.operand as ILInstruction[];
                    if (targets != null)
                    {
                        var labels = new List <Label>();
                        foreach (var target in targets)
                        {
                            var label = generator.DefineLabel();
                            target.labels.Add(label);
                            labels.Add(label);
                        }
                        ilInstruction.argument = labels.ToArray();
                    }
                    break;
                }

                case OperandType.ShortInlineBrTarget:
                case OperandType.InlineBrTarget:
                {
                    var target = ilInstruction.operand as ILInstruction;
                    if (target != null)
                    {
                        var label = generator.DefineLabel();
                        target.labels.Add(label);
                        ilInstruction.argument = label;
                    }
                    break;
                }
                }
            }

            // pass2 - filter through all processors
            //
            var codeTranspiler = new CodeTranspiler(ilInstructions);
            // Not in MonoMod.
            var codeInstructions = codeTranspiler.GetResult(generator, method);

            // pass3 - remove RET if it appears at the end
            // Not in MonoMod.

            /*
             *          while (true)
             *          {
             *                  var lastInstruction = codeInstructions.LastOrDefault();
             *                  if (lastInstruction == null || lastInstruction.opcode != OpCodes.Ret) break;
             *
             *                  // remember any existing labels
             *                  endLabels.AddRange(lastInstruction.labels);
             *
             *                  var l = codeInstructions.ToList();
             *                  l.RemoveAt(l.Count - 1);
             *                  codeInstructions = l;
             *          }
             */

            // pass4 - mark labels and exceptions and emit codes
            //
            var instructions = codeInstructions.ToArray();
            var idx          = 0;

            foreach (var codeInstruction in instructions)
            {
                // mark all labels
                foreach (var label in codeInstruction.labels)
                {
                    generator.MarkLabel(label);
                }

                // start all exception blocks
                // TODO: we ignore the resulting label because we have no way to use it
                //
                foreach (var block in codeInstruction.blocks)
                {
                    Label?label;
                    Emitter.MarkBlockBefore(generator, block, out label);
                }

                var code    = codeInstruction.opcode;
                var operand = codeInstruction.operand;

                // replace RET with a jump to the end (outside this code)
                // Not in MonoMod.

                /*
                 *              if (code == OpCodes.Ret)
                 *              {
                 *                      var endLabel = generator.DefineLabel();
                 *                      code = OpCodes.Br;
                 *                      operand = endLabel;
                 *                      endLabels.Add(endLabel);
                 *              }
                 */

                var emitCode = true;

                //if (code == OpCodes.Leave || code == OpCodes.Leave_S)
                //{
                //	// skip LEAVE on EndExceptionBlock
                //	if (codeInstruction.blocks.Any(block => block.blockType == ExceptionBlockType.EndExceptionBlock))
                //		emitCode = false;

                //	// skip LEAVE on next instruction starts a new exception handler and we are already in
                //	if (idx < instructions.Length - 1)
                //		if (instructions[idx + 1].blocks.Any(block => block.blockType != ExceptionBlockType.EndExceptionBlock))
                //			emitCode = false;
                //}

                if (emitCode)
                {
                    if (code.OperandType == OperandType.InlineNone)
                    {
                        generator.Emit(code);
                    }
                    else
                    {
                        if (operand == null)
                        {
                            throw new Exception("Wrong null argument: " + codeInstruction);
                        }
                        var emitMethod = EmitMethodForType(operand.GetType());
                        if (emitMethod == null)
                        {
                            throw new Exception("Unknown Emit argument type " + operand.GetType() + " in " + codeInstruction);
                        }
                        emitMethod.Invoke(generator, new object[] { code, operand });
                    }
                }

                foreach (var block in codeInstruction.blocks)
                {
                    Emitter.MarkBlockAfter(generator, block);
                }

                idx++;
            }
        }