public static bool Prefix(Type type, IEnumerable enumerable, ref Dictionary <object, Dictionary <string, object> > unassignedValues, ref IEnumerable __result) { var enumerableAssembly = type.GetGenericTypeDefinition().Assembly; var genericListType = enumerableAssembly.GetType(typeof(List <>).FullName); var elementType = type.GetGenericArguments()[0]; var listType = /*enumerableAssembly.GetType(*/ genericListType.MakeGenericType(new Type[] { elementType }) /*.FullName)*/; var list = Activator.CreateInstance(listType); var listAdd = list.GetType().GetMethod("Add"); unassignedValues = new Dictionary <object, Dictionary <string, object> >(); foreach (var op in enumerable) { var elementTo = CodeTranspiler.ConvertInstruction(elementType, op, out var unassigned); unassignedValues.Add(elementTo, unassigned); listAdd.Invoke(list, new object[] { elementTo }); // cannot yield return 'elementTo' here because we have an out parameter in the method } __result = list as IEnumerable; return(false); }
// use parsed IL codes and emit them to a generator public void FinalizeILCodes(List <MethodInfo> 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) { labels.Add(target.GetLabel(generator)); } ilInstruction.argument = labels.ToArray(); } break; } case OperandType.ShortInlineBrTarget: case OperandType.InlineBrTarget: { var target = ilInstruction.operand as ILInstruction; if (target != null) { ilInstruction.argument = target.GetLabel(generator); } 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 }, { OpCodes.Leave_S, OpCodes.Leave } }.Do(pair => { if (instruction.opcode == pair.Key) { instruction.opcode = pair.Value; } }); if (instruction.opcode == OpCodes.Ret) { instruction.opcode = OpCodes.Br; instruction.operand = endLabel; } return(instruction); }); // pass3 - mark labels and emit codes codeInstructions.Do(codeInstruction => { Emitter.EmitExceptionBlock(generator, codeInstruction); if (codeInstruction.label != null) { Emitter.MarkLabel(generator, codeInstruction.label.Value); } 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 }); } }); }
// 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++; }); }
// 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); 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; instructions.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); } 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) { 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.LogBuffered(Emitter.CodePos(generator) + code + " " + Emitter.FormatArgument(operand)); } emitMethod.Invoke(generator, new object[] { code, operand }); } } codeInstruction.blocks.Do(block => Emitter.MarkBlockAfter(generator, block)); idx++; }); }
/// <summary> /// Compiles a method into IL instructions. /// </summary> /// <param name="method">Method to compile.</param> /// <returns> /// List of ILInstructions. /// </returns> /// <remarks> /// Utilizes harmony library. /// </remarks> public static List <CodeInstruction> MethodToILInstructions(MethodBase method) { DynamicMethod dynamicMethod = DynamicTools.CreateDynamicMethod(method, "_ILParser"); if (dynamicMethod == null) { return(null); } // Get il generato ILGenerator il = dynamicMethod.GetILGenerator(); LocalBuilder[] existingVariables = DynamicTools.DeclareLocalVariables(method, il); Dictionary <string, LocalBuilder> privateVars = new Dictionary <string, LocalBuilder>(); MethodBodyReader reader = new MethodBodyReader(method, il); reader.DeclareVariables(existingVariables); reader.ReadInstructions(); List <ILInstruction> ilInstructions = (List <ILInstruction>)FIilInstructions.GetValue(reader); // Defines function start label il.DefineLabel(); // Define labels foreach (ILInstruction ilInstruction in ilInstructions) { switch (ilInstruction.opcode.OperandType) { case OperandType.InlineSwitch: { ILInstruction[] array = ilInstruction.operand as ILInstruction[]; if (array != null) { List <Label> labels = new List <Label>(); ILInstruction[] array2 = array; foreach (ILInstruction iLInstruction2 in array2) { Label item = il.DefineLabel(); iLInstruction2.labels.Add(item); labels.Add(item); } ilInstruction.argument = labels.ToArray(); } break; } case OperandType.InlineBrTarget: case OperandType.ShortInlineBrTarget: { ILInstruction iLInstruction = ilInstruction.operand as ILInstruction; if (iLInstruction != null) { Label label2 = il.DefineLabel(); iLInstruction.labels.Add(label2); ilInstruction.argument = label2; } break; } } } // Transpile code CodeTranspiler codeTranspiler = new CodeTranspiler(ilInstructions); List <CodeInstruction> result = codeTranspiler.GetResult(il, method); // Replace debug commands with normal foreach (CodeInstruction codeInstruction in result) { OpCode opCode = codeInstruction.opcode; codeInstruction.opcode = ReplaceShortJumps(opCode); } return(result); }