void ICilCompilerAware.ImplementInCil(CompilerState state, Instruction ins) { state.EmitIgnoreArguments(ins.Arguments); state.Il.Emit(OpCodes.Newobj, _channelCtor); PType.PrexoniteObjectTypeProxy._ImplementInCil(state, typeof (Channel)); state.Il.Emit(OpCodes.Newobj, _newPValue); }
void ICilCompilerAware.ImplementInCil(CompilerState state, Instruction ins) { var argc = ins.Arguments; if (argc < 2) { state.EmitLoadNullAsPValue(); } else { //pop excessive arguments for (var i = 2; i < argc; i++) state.Il.Emit(OpCodes.Pop); //make pvkvp state.Il.Emit(OpCodes.Newobj, Compiler.Cil.Compiler.NewPValueKeyValuePair); //save pvkvp in temporary variable state.EmitStoreTemp(0); //PType.Object.CreatePValue(temp) state.Il.EmitCall(OpCodes.Call, Compiler.Cil.Compiler.GetObjectPTypeSelector, null); state.EmitLoadTemp(0); state.Il.EmitCall(OpCodes.Call, Compiler.Cil.Compiler.CreatePValueAsObject, null); } }
/// <summary> /// Run a simple check on a list of instructions to check if it evaluates to a constant /// value. /// </summary> /// <param name="expression"></param> /// <returns></returns> public static bool IsSimpleConstant(Instruction[] expression) { // First pass, check basic instructions. foreach (Instruction instruction in expression) { // These are "constant" instructions which can be evaluated without any // context (no locals, globals, instance, or system required). if ( !(instruction is LoadConstant) && !(instruction is CallFunction) && !(instruction is BinaryAdd) && !(instruction is BinaryDiv) && !(instruction is BinaryMod) && !(instruction is BinaryMul) && !(instruction is BinaryPow) && !(instruction is BinarySub) && !(instruction is UnaryAbs) && !(instruction is UnaryNeg) ) return false; } // Second pass, check for pure functions. for (int i = 0; i < expression.Length; i++) { if (expression[i] is CallFunction) { var previous = ((LoadConstant)expression[i - 1]).constant; if (!((DmlFunction)previous.Value).IsPure) return false; } } return true; }
public void Execute(Machine machine, Stack<object> stack, Scope scope, Instruction instr) { int length = (int)machine.TakeByte(); string name = machine.TakeBytes(length * sizeof(char)).AsString(); scope.GetFunction(name).Call(machine); }
public void Execute(Machine machine, Stack<object> stack, Scope scope, Instruction instr) { Instruction type = (Instruction)machine.TakeByte(); switch (type) { default: throw new VMException("Unhandled literal type: {0}", type.ToString()); case Instruction.TypeNumeral: byte[] numBytes = machine.TakeBytes(8); stack.Push(numBytes.AsDouble()); break; case Instruction.TypeString: double length = machine.TakeBytes(8).AsDouble(); string text = machine.TakeBytes((int)length * sizeof(char)).AsString(); stack.Push(text); break; case Instruction.TypeBoolean: stack.Push(Convert.ToBoolean(machine.TakeByte())); break; } }
void HandleOfParameter(Instruction instruction, ILProcessor ilProcessor) { //Info.OfMethod("AssemblyToProcess","MethodClass","InstanceMethod"); var methodNameInstruction = instruction.Previous; var methodName = GetLdString(methodNameInstruction); var typeNameInstruction = methodNameInstruction.Previous; var typeName = GetLdString(typeNameInstruction); var assemblyNameInstruction = typeNameInstruction.Previous; var assemblyName = GetLdString(assemblyNameInstruction); var typeDefinition = GetTypeDefinition(assemblyName, typeName); var methodDefinition = typeDefinition.Methods.FirstOrDefault(x => x.Name == methodName); if (methodDefinition == null) { throw new WeavingException($"Could not find method named '{methodName}'."); } var methodReference = ModuleDefinition.ImportReference(methodDefinition); ilProcessor.Remove(typeNameInstruction); assemblyNameInstruction.OpCode = OpCodes.Ldtoken; assemblyNameInstruction.Operand = methodReference; instruction.Operand = getMethodFromHandle; ilProcessor.InsertAfter(instruction,Instruction.Create(OpCodes.Castclass,methodInfoType)); }
internal static MemoryStream SerializeBytecode(Instruction[] bytecode) { return Utils.SerializeWithMd5CheckSum (str => { SerializeBytecodeImplementation (str, bytecode); } ); }
public static Instruction CreateBinaryInstruction( string mnemonic, OperationNode op, int exUnit, ValueNode vres, RegisterSet vresRegs, ValueNode v1, RegisterSet v1Regs, ValueNode v2, RegisterSet v2Regs) { InstructionPattern ip = new InstructionPattern(); ip.AddNode(op); ip.AddNode(vres); ip.AddNode(v1); ip.AddNode(v2); ip.AddEdge(op, vres); ip.AddEdge(v1, op); ip.AddEdge(v2, op); ip.OperandValues.Add(v1); ip.OperandValues.Add(v2); ip.ResultValue = vres; Instruction i = new Instruction(mnemonic, ip); i.ExecutionUnit = exUnit; i.ResultRegisters = vresRegs; i.OperandsRegisters[0] = v1Regs; i.OperandsRegisters[1] = v2Regs; return i; }
public CompiledInstruction(Instruction Instr, int MemSize, int InputSize) { InAdrA = ConvertMemAdrToInt(Instr.InAdrA, MemSize, InputSize); HyAdrB = ConvertMemAdrToInt(Instr.HyAdrB, MemSize, InputSize); OutAdr = ConvertMemAdrToInt(Instr.OutAdr, MemSize, InputSize); Instuct = Instr.Instuct; }
public AstAsmInstruction(string file, int line, int column, Instruction instruction) : base(file, line, column) { if (instruction == null) throw new ArgumentNullException("instruction"); Instruction = instruction; }
public Result Disassemble(uint PC, Instruction Instruction) { if (ProcessCallback == null) { InstructionDictionary = InstructionTable.ALL.ToDictionary(Item => Item.Name); ProcessCallback = EmitLookupGenerator.GenerateSwitch<Func<uint, MipsDisassembler, Result>>(InstructionTable.ALL, (SafeILGenerator, InstructionInfo) => { //SafeILGenerator.LoadArgument<MipsDisassembler>(1); SafeILGenerator.LoadArgument<uint>(0); if (InstructionInfo == null) { SafeILGenerator.Push("Unknown"); } else { SafeILGenerator.Push(InstructionInfo.Name); } SafeILGenerator.Call((Func<uint, String, Result>)MipsDisassembler._InternalHandle); }); } var Result = ProcessCallback(Instruction, this); Result.InstructionPC = PC; return Result; }
public void Execute(Machine machine, Stack<object> stack, Scope scope, Instruction instr) { int length; string name; switch (instr) { default: throw new VMException("Something just went horribly wrong. Variable instructlet is not supposed to receive {0}", instr.ToString()); case Instruction.SetVar: length = (int)machine.TakeByte(); name = machine.TakeBytes(length).AsString(); machine.ExecuteNextInstructlet(); scope.SetVariable(name, stack.Pop()); break; case Instruction.GetVar: length = (int)machine.TakeByte(); name = machine.TakeBytes((int)length).AsString(); stack.Push(scope.GetVariable(name)); break; } }
public static Instruction Push(object value) { if (value == null) { return _null ?? (_null = new PushInstruction(null)); } if (value is bool) { if ((bool)value) { return _true ?? (_true = new PushInstruction(value)); } else { return _false ?? (_false = new PushInstruction(value)); } } if (value is int) { int i = (int)value; if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue) { if (_ints == null) { _ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1]; } i -= PushIntMinCachedValue; return _ints[i] ?? (_ints[i] = new PushInstruction(value)); } } return new PushInstruction(value); }
void InjectNop(Instruction instruction) { Instruction nop; if (instruction.Previous != null && instruction.Previous.OpCode == OpCodes.Nop) { nop = instruction.Previous; } else { nop = Instruction.Create(OpCodes.Nop); instructions.Insert(instructions.IndexOf(instruction), nop); } foreach (var innerInstruction in instructions) { if (innerInstruction == instruction) { continue; } var flowControl = innerInstruction.OpCode.FlowControl; if (flowControl != FlowControl.Branch && flowControl != FlowControl.Cond_Branch) { continue; } if (innerInstruction.Operand != instruction) { continue; } innerInstruction.Operand = nop; } }
public void MakeLastStatementReturn() { instructions = Method.Body.Instructions; FixHangingHandlerEnd(); sealBranchesNop = Instruction.Create(OpCodes.Nop); instructions.Add(sealBranchesNop); NopBeforeReturn = Instruction.Create(OpCodes.Nop); foreach (var instruction in instructions) { var operand = instruction.Operand as Instruction; if (operand != null) { if (operand.OpCode == OpCodes.Ret) { instruction.Operand = sealBranchesNop; } } } if (Method.MethodReturnType.ReturnType.Name == "Void") { WithNoReturn(); return; } WithReturnValue(); }
public Result Disassemble(uint PC, Instruction Instruction) { if (ProcessCallback == null) { var Dictionary = new Dictionary<InstructionInfo, int>(); InstructionLookup = InstructionTable.ALL.ToArray(); for (int n = 0; n < InstructionLookup.Length; n++) Dictionary[InstructionLookup[n]] = n; ProcessCallback = EmitLookupGenerator.GenerateSwitch<Func<uint, MipsDisassembler, Result>>("", InstructionTable.ALL, (InstructionInfo) => { return ast.Return(ast.CallStatic( (Func<uint, int, Result>)MipsDisassembler._InternalHandle, ast.Argument<uint>(0), (InstructionInfo != null) ? Dictionary[InstructionInfo] : -1 )); }); } var Result = ProcessCallback(Instruction, this); if (Result.InstructionInfo == null) { Console.Error.WriteLine(String.Format("Instruction at 0x{0:X8} with data 0x{1:X8} didn't generate a value", PC, (uint)Instruction)); Result.InstructionInfo = InstructionTable.Unknown; } Result.InstructionPC = PC; return Result; }
public Instruction(Instruction i) { InAdrA = i.InAdrA; HyAdrB = i.HyAdrB; OutAdr = i.OutAdr; Instuct = i.Instuct; }
public object Run(Instruction i) { Debug.Log ("Exec "+i.name); if(i.name=="left") AddImpulse( -1.0f, 0.0f, 0.0f ); else if(i.name=="right") AddImpulse( 1.0f, 0.0f, 0.0f ); else if(i.name=="forward") AddImpulse( 0.0f, 0.0f, 1.0f ); else if(i.name=="backward") AddImpulse( 0.0f, 0.0f, -1.0f ); else if(i.name=="up") AddImpulse( 0.0f, 1.0f, 0.0f ); else if(i.name=="sum"){ float s = 0.0f; foreach(var e in i.arguments){ s+=(float)e; } return s; }else if(i.name=="product"){ float s = 1.0f; foreach(var e in i.arguments){ s+=(float)e; } return s; }else{ Debug.LogError ("illegal instruction: "+i.name); return null; } return null; }
public static void instr(Instruction instr, TargetRegister op1, TargetRegister op2) { BuildInstruction (instr); BuildLengthPrefix (LengthPrefix.f_reg | LengthPrefix.s_reg); BuildRegister (op1); BuildRegister (op2); }
public static void instr(Instruction instr, TargetRegister op1, byte op2) { BuildInstruction (instr); BuildLengthPrefix (LengthPrefix.f_reg | LengthPrefix.s_8); BuildRegister (op1); bitstream.Write (op2 & 0xFF); }
public void Process(Instruction instruction) { Command command; switch (instruction.InstructionType) { case InstructionType.NamespaceDeclaration: command = new NamespaceDeclarationCommand(instruction.NamespaceDeclaration, StateCommuter); break; case InstructionType.StartObject: command = new StartObjectCommand(StateCommuter, TypeSource, instruction.XamlType, rootInstance); break; case InstructionType.StartMember: command = new StartMemberCommand(StateCommuter, GetActualMemberFromMemberSpecifiedInInstruction(instruction.Member)); break; case InstructionType.Value: command = new ValueCommand(StateCommuter, this.TypeSource, TopDownValueContext, (string)instruction.Value); break; case InstructionType.EndObject: command = new EndObjectCommand(StateCommuter, stateCommuter => Result = stateCommuter.Current.Instance); break; case InstructionType.EndMember: command = new EndMemberCommand(TypeSource, StateCommuter); break; case InstructionType.GetObject: command = new GetObjectCommand(StateCommuter); break; default: throw new ParseException($"The XamlInstructionType {instruction.InstructionType} has an unexpected value"); } command.Execute(); }
private int OpCodeCost(Instruction instruction) { switch (instruction.instruction) { case 0x0: switch (instruction.a) { case 0x01: return 3; } return 0; case 0x01: return 1; case 0x06: case 0x07: case 0x08: return 3; case 0x09: case 0x0a: case 0x0b: return 1; default: return 2; } }
private int ValueCost(Instruction instruction) { if (instruction.instruction == 0x0) // extended return ValueCost(instruction.b); return ValueCost(instruction.a) + ValueCost(instruction.b); }
public Node(Position pos, Instruction instruction, BigInteger? arg = null, string label = null) { Position = pos; Instruction = instruction; Arg = arg; Label = label; }
/// <summary> /// Reroute all old targets to the new targets. /// </summary> internal void Reroute(Instruction oldTarget, Instruction newTarget) { if (branches != null) { var count = branches.Count; for (var i = 0; i < count; i++) { var ins = branches[i]; if (ins.Operand == oldTarget) { ins.Operand = newTarget; } else if (ins.Code == RCode.Packed_switch) { var targets = (Instruction[])ins.Operand; for (var j = 0; j < targets.Length; j++) { if (targets[j] == oldTarget) { targets[j] = newTarget; } } } else if (ins.Code == RCode.Sparse_switch) { var targetPairs = (Tuple<int, Instruction>[])ins.Operand; for (var j = 0; j < targetPairs.Length; j++) { if ((targetPairs[j] != null) && (targetPairs[j].Item2 == oldTarget)) { targetPairs[j] = Tuple.Create(targetPairs[j].Item1, newTarget); } } } } } if (exceptionHandlers != null) { var count = exceptionHandlers.Length; for (var i = 0; i < count; i++) { var eh = exceptionHandlers[i]; if (eh.CatchAll == oldTarget) { eh.CatchAll = newTarget; } if (eh.TryEnd == oldTarget) { eh.TryEnd = oldTarget.Previous; } if (eh.TryStart == oldTarget) { eh.TryStart = newTarget; } foreach (var c in eh.Catches) { if (c.Instruction == oldTarget) c.Instruction = newTarget; } } } // Save PDB info /*if ((oldTarget.SourceLocation != null) && (newTarget.SourceLocation == null)) { newTarget.SourceLocation = oldTarget.SourceLocation; }*/ }
/// <summary> /// replaces comparisons where one operand has just been set to a const zero. /// asumes that instruction is a comparison instruction with two registers. /// </summary> private bool OptimizeComparisonToConstZero(Instruction ins, BasicBlock bb) { var r1 = ins.Registers[0]; var r2 = ins.Registers[1]; bool? r1IsZero = null, r2IsZero = null; if (r1.Category == RCategory.Argument || r1.PreventOptimization) r1IsZero = false; if (r2.Category == RCategory.Argument || r2.PreventOptimization) r2IsZero = false; for (var prev = ins.PreviousOrDefault; prev != null && prev.Index >= bb.Entry.Index; prev=prev.PreviousOrDefault) { if(r1IsZero.HasValue && r2IsZero.HasValue) break; if ((r1IsZero.HasValue && r1IsZero.Value) || (r2IsZero.HasValue && r2IsZero.Value)) break; if (r1IsZero == null) { if (r1.IsDestinationIn(prev)) { r1IsZero = prev.Code == RCode.Const && Convert.ToInt32(prev.Operand) == 0; continue; } } if (r2IsZero == null) { if (r2.IsDestinationIn(prev)) { r2IsZero = prev.Code == RCode.Const && Convert.ToInt32(prev.Operand) == 0; continue; } } } if (r2IsZero.HasValue && r2IsZero.Value) { ins.Code = ToComparisonWithZero(ins.Code); ins.Registers.Clear(); ins.Registers.Add(r1); return true; } if (r1IsZero.HasValue && r1IsZero.Value) { // swap the registers before converting to zero-comparison. ins.Code = ToComparisonWithZero(SwapComparisonRegisters(ins.Code)); ins.Registers.Clear(); ins.Registers.Add(r2); return true; } return false; }
string GetLdString(Instruction previous) { if (previous.OpCode != OpCodes.Ldstr) { LogErrorPoint("Expected a string", previous.SequencePoint); } return (string) previous.Operand; }
public void DecodeTestAddMin4095() { ADD target = new ADD(); target.Parse("ADD -4095"); Instruction expected = new Instruction(16383); Instruction actual = target.Decode(); Assert.AreEqual(expected, actual); }
//func<> is a function, it takes an int and return an Instruction public For(int start, int end, Func<int, Instruction> getBody) { this.i = start; this.start = start; this.end = end; this.getBody = getBody; this.body = getBody(i);//this is a Semicolon, made of Wait and CreateAsteroid }
static void InjectWriteIl(List<Instruction> writeTimeIl, ILProcessor ilProcessor, Instruction beforeThis) { foreach (var instruction in writeTimeIl) { ilProcessor.InsertBefore(beforeThis, instruction); } ilProcessor.InsertBefore(beforeThis, Instruction.Create(OpCodes.Endfinally)); }
public override bool Execute(Instruction instruction, InstructionPayload payload) { var rs1 = payload.Rs1; var rs2 = payload.Rs2; var f3 = payload.Funct3; var rs1Signed = Register.ReadSignedInt(rs1); var rs2Signed = Register.ReadSignedInt(rs2); var rs1Unsigned = Register.ReadUnsignedInt(rs1); var rs2Unsigned = Register.ReadUnsignedInt(rs2); bool doJump = false; Logger.Info("Opcode 18 : rs1 = {rs1}, rs2 = {rs2} funct3 = {f3}", rs1, rs2, f3); switch (f3) { // beq case 0: if (rs1Signed == rs2Signed) { doJump = true; } break; // bne case 1: if (rs1Signed != rs2Signed) { doJump = true; } break; // blt case 4: if (rs1Signed < rs2Signed) { doJump = true; } break; // bge case 5: if (rs1Signed > rs2Signed) { doJump = true; } break; // bltu case 6: if (rs1Unsigned < rs2Unsigned) { doJump = true; } break; // bgeu case 7: if (rs1Unsigned > rs2Unsigned) { doJump = true; } break; default: throw new OpCodeNotSupportedException(String.Format("OpCode = {0}, Funct3 = {1}", instruction.OpCode, f3)); } if (doJump) { var pcIndex = Register.ProgramCounter; var pc = Register.ReadUnsignedLong(pcIndex); var newPc = MathHelper.Add(pc, payload.SignedImmediate); var rasPc = pc + 4; // Write it to X1 and the RAS Register.WriteUnsignedLong(1, rasPc); ras.Push(rasPc); Register.WriteUnsignedLong(pcIndex, newPc); } return !doJump; }
public void Process(IAssemblyHelper asmHelper) { asm = asmHelper; Logger.Log(this, string.Format("Processing")); // Set regex/bool foreach (PluginValue ps in asm.Settings) { switch (ps.Name) { case "OpCodeRegex": OpCodeRegex = (List <string>)ps.Value; break; case "OperandRegex": OperandRegex = (List <string>)ps.Value; break; case "AttributeRegex": AttributeRegex = (List <string>)ps.Value; break; case "MethodNameRegex": MethodNameRegex = (List <string>)ps.Value; break; case "MethodTokenRegex": MethodTokenRegex = (List <string>)ps.Value; break; case "MatchAll": MatchAll = (bool)ps.Value; break; case "RemoveInlined": RemoveInlined = (bool)ps.Value; break; case "UseHexToken": UseHexToken = (bool)ps.Value; break; case "UseFullName": UseFullName = (bool)ps.Value; break; } } Logger.Log(this, string.Format("Loaded {0} OpCodeRegex", OpCodeRegex.Count)); Logger.Log(this, string.Format("Loaded {0} OperandRegex", OperandRegex.Count)); Logger.Log(this, string.Format("Loaded {0} AttributeRegex", AttributeRegex.Count)); Logger.Log(this, string.Format("Loaded {0} TokenRegex", MethodTokenRegex.Count)); Logger.Log(this, string.Format("Loaded {0} NameRegex", MethodNameRegex.Count)); List <CallInfo> toPatch = new List <CallInfo>(); foreach (TypeDef td in asm.Module.GetTypes()) { foreach (MethodDef md in td.Methods) { if (!md.HasBody) { continue; } md.Body.SimplifyMacros(md.Parameters); } } List <MethodDef> allMatches = new List <MethodDef>(); foreach (TypeDef td in asm.Module.GetTypes()) { List <MethodDef> methodMatches = GetMatching(td).Distinct().ToList(); Logger.Log(this, string.Format("Found {0} Matches for {1}", methodMatches.Count, td.Name)); allMatches.AddRange(methodMatches); } Logger.Log(this, string.Format("Found {0} Matches Total", allMatches.Count)); foreach (TypeDef td in asm.Module.GetTypes()) { foreach (MethodDef md in td.Methods) { if (!md.HasBody) { continue; } for (int i = 0; i < md.Body.Instructions.Count; i++) { Instruction inst = md.Body.Instructions[i]; if ((inst.OpCode == OpCodes.Call || inst.OpCode == OpCodes.Callvirt) && inst.Operand is MethodDef) { // MethodDef MethodDef mDef = inst.Operand as MethodDef; if (allMatches.Any(x => x.MDToken == mDef.MDToken)) { // Patch this call toPatch.Add(new CallInfo() { CallingInst = inst, ParentMethod = md, TargetMethod = mDef }); } } } } } Logger.Log(this, string.Format("Found {0} calls to inline", toPatch.Count)); List <CallInfo> toPatch2 = new List <CallInfo>(toPatch); // Have to do priority, if a method is already in the topatch and another has it as a target method then there needs to be priority for the latter. List <CallInfo> cInfos = new List <CallInfo>(); foreach (CallInfo cInfo in toPatch) { if (cInfos.Any(x => x.TargetMethod == cInfo.ParentMethod)) { // if it already exists in the list, insert it before CallInfo cMatch = cInfos.Where(x => x.TargetMethod == cInfo.ParentMethod).FirstOrDefault(); if (cMatch == null) { // what the f**k cInfos.Add(cInfo); continue; } int index = cInfos.IndexOf(cMatch); if (index >= 0) { Logger.Log(this, string.Format("Prioritizing {0} over {1}", cInfo.TargetMethod.Name, cMatch.TargetMethod.Name)); cInfos.Insert(index != 0 ? index - 1 : index, cInfo); } else { cInfos.Add(cInfo); } } else { cInfos.Add(cInfo); } } foreach (CallInfo cInfo in cInfos) { if (cInfo.CallingInst == null || cInfo.ParentMethod == null || cInfo.ParentMethod.Body == null) { continue; } int instIndex = cInfo.ParentMethod.Body.Instructions.IndexOf(cInfo.CallingInst); if (!cInfo.TargetMethod.IsStatic) { if (cInfo.ParentMethod.Body.Instructions[instIndex - 1].OpCode == OpCodes.Ldarg) { cInfo.ParentMethod.Body.Instructions[instIndex - 1].OpCode = OpCodes.Nop; cInfo.ParentMethod.Body.Instructions[instIndex - 1].Operand = null; } } List <Instruction> toCopy = cInfo.TargetMethod.Body.Instructions.Where(x => x.OpCode != OpCodes.Ldarg && x.OpCode != OpCodes.Starg && x.OpCode != OpCodes.Nop && x.OpCode != OpCodes.Ret && x.OpCode != OpCodes.Br && x.OpCode != OpCodes.Switch ).ToList(); for (int i = 0; i < toCopy.Count; i++) { toCopy[i] = toCopy[i].Clone(); } Dictionary <int, Local> OldLocals = new Dictionary <int, Local>(); if (cInfo.TargetMethod.Body.HasVariables) { foreach (var loc in cInfo.TargetMethod.Body.Variables) { Local l = new Local(loc.Type) { Name = loc.Name, PdbAttributes = loc.PdbAttributes }; l = cInfo.ParentMethod.Body.Variables.Add(l); OldLocals.Add(loc.Index, l); } Logger.Log(this, string.Format("Copied {0} Locals", OldLocals.Count)); } for (int i = 0; i < toCopy.Count; i++) { if (toCopy[i].OpCode == OpCodes.Stloc || toCopy[i].OpCode == OpCodes.Ldloc) { if (OldLocals.ContainsKey((toCopy[i].Operand as Local).Index)) { toCopy[i].Operand = OldLocals[(toCopy[i].Operand as Local).Index]; } } Instruction tReplace = toCopy[i].Clone(); if (i == 0) { cInfo.ParentMethod.Body.Instructions[instIndex].OpCode = tReplace.OpCode; cInfo.ParentMethod.Body.Instructions[instIndex].Operand = tReplace.Operand; } else { cInfo.ParentMethod.Body.Instructions.Insert(instIndex + i, tReplace); cInfo.ParentMethod.Body.UpdateInstructionOffsets(); } } Logger.Log(this, string.Format("Inlined {0} Instructions", toCopy.Count)); toPatch2.Remove(cInfo); if (RemoveInlined && !toPatch2.Any(x => x.TargetMethod == cInfo.TargetMethod)) { cInfo.TargetMethod.Body.Variables.Clear(); cInfo.TargetMethod.Body.Instructions.Clear(); cInfo.TargetMethod.Body = null; cInfo.TargetMethod.DeclaringType.Methods.Remove(cInfo.TargetMethod); Logger.Log(this, string.Format("Removed Method {0}", cInfo.TargetMethod.Name)); } } Logger.Log(this, string.Format("Processing has finished")); }
public static IEnumerable <Instruction> PushParentObjectsArray(this INode node, ILContext context) { var module = context.Body.Method.Module; var nodes = new List <IElementNode>(); INode n = node.Parent; while (n != null) { var en = n as IElementNode; if (en != null && context.Variables.ContainsKey(en)) { nodes.Add(en); } n = n.Parent; } if (nodes.Count == 0 && context.ParentContextValues == null) { yield return(Instruction.Create(OpCodes.Ldnull)); yield break; } if (nodes.Count == 0) { yield return(Instruction.Create(OpCodes.Ldarg_0)); yield return(Instruction.Create(OpCodes.Ldfld, context.ParentContextValues)); yield break; } //Compute parent object length if (context.ParentContextValues != null) { yield return(Instruction.Create(OpCodes.Ldarg_0)); yield return(Instruction.Create(OpCodes.Ldfld, context.ParentContextValues)); yield return(Instruction.Create(OpCodes.Ldlen)); yield return(Instruction.Create(OpCodes.Conv_I4)); } else { yield return(Instruction.Create(OpCodes.Ldc_I4_0)); } var parentObjectLength = new VariableDefinition(module.TypeSystem.Int32); context.Body.Variables.Add(parentObjectLength); yield return(Instruction.Create(OpCodes.Stloc, parentObjectLength)); //Create the final array yield return(Instruction.Create(OpCodes.Ldloc, parentObjectLength)); yield return(Instruction.Create(OpCodes.Ldc_I4, nodes.Count)); yield return(Instruction.Create(OpCodes.Add)); yield return(Instruction.Create(OpCodes.Newarr, module.TypeSystem.Object)); var finalArray = new VariableDefinition(module.ImportReference(typeof(object[]))); context.Body.Variables.Add(finalArray); yield return(Instruction.Create(OpCodes.Stloc, finalArray)); //Copy original array to final if (context.ParentContextValues != null) { yield return(Instruction.Create(OpCodes.Ldarg_0)); yield return(Instruction.Create(OpCodes.Ldfld, context.ParentContextValues)); //sourceArray yield return(Instruction.Create(OpCodes.Ldc_I4_0)); //sourceIndex yield return(Instruction.Create(OpCodes.Ldloc, finalArray)); //destinationArray yield return(Instruction.Create(OpCodes.Ldc_I4, nodes.Count)); //destinationIndex yield return(Instruction.Create(OpCodes.Ldloc, parentObjectLength)); //length var arrayCopy = module.ImportReference(typeof(Array)) .Resolve() .Methods.First( md => md.Name == "Copy" && md.Parameters.Count == 5 && md.Parameters[1].ParameterType.FullName == module.TypeSystem.Int32.FullName); yield return(Instruction.Create(OpCodes.Call, module.ImportReference(arrayCopy))); } //Add nodes to array yield return(Instruction.Create(OpCodes.Ldloc, finalArray)); if (nodes.Count > 0) { for (var i = 0; i < nodes.Count; i++) { var en = nodes[i]; yield return(Instruction.Create(OpCodes.Dup)); yield return(Instruction.Create(OpCodes.Ldc_I4, i)); yield return(Instruction.Create(OpCodes.Ldloc, context.Variables[en])); if (context.Variables[en].VariableType.IsValueType) { yield return(Instruction.Create(OpCodes.Box, module.ImportReference(context.Variables[en].VariableType))); } yield return(Instruction.Create(OpCodes.Stelem_Ref)); } } }
public static IEnumerable <Instruction> PushConvertedValue(this ValueNode node, ILContext context, TypeReference targetTypeRef, TypeReference typeConverter, IEnumerable <Instruction> pushServiceProvider, bool boxValueTypes, bool unboxValueTypes) { var module = context.Body.Method.Module; var str = (string)node.Value; //If the TypeConverter has a ProvideCompiledAttribute that can be resolved, shortcut this var compiledConverterName = typeConverter?.GetCustomAttribute(module.ImportReference(typeof(ProvideCompiledAttribute)))?.ConstructorArguments?.First().Value as string; Type compiledConverterType; if (compiledConverterName != null && (compiledConverterType = Type.GetType(compiledConverterName)) != null) { var compiledConverter = Activator.CreateInstance(compiledConverterType); var converter = typeof(ICompiledTypeConverter).GetMethods().FirstOrDefault(md => md.Name == "ConvertFromString"); var instructions = (IEnumerable <Instruction>)converter.Invoke(compiledConverter, new object[] { node.Value as string, context, node as BaseNode }); foreach (var i in instructions) { yield return(i); } if (targetTypeRef.IsValueType && boxValueTypes) { yield return(Instruction.Create(OpCodes.Box, module.ImportReference(targetTypeRef))); } yield break; } //If there's a [TypeConverter], use it if (typeConverter != null) { var isExtendedConverter = typeConverter.ImplementsInterface(module.ImportReference(typeof(IExtendedTypeConverter))); var typeConverterCtor = typeConverter.Resolve().Methods.Single(md => md.IsConstructor && md.Parameters.Count == 0 && !md.IsStatic); var typeConverterCtorRef = module.ImportReference(typeConverterCtor); var convertFromInvariantStringDefinition = isExtendedConverter ? module.ImportReference(typeof(IExtendedTypeConverter)) .Resolve() .Methods.FirstOrDefault(md => md.Name == "ConvertFromInvariantString" && md.Parameters.Count == 2) : typeConverter.Resolve() .AllMethods() .FirstOrDefault(md => md.Name == "ConvertFromInvariantString" && md.Parameters.Count == 1); var convertFromInvariantStringReference = module.ImportReference(convertFromInvariantStringDefinition); yield return(Instruction.Create(OpCodes.Newobj, typeConverterCtorRef)); yield return(Instruction.Create(OpCodes.Ldstr, node.Value as string)); if (isExtendedConverter) { foreach (var instruction in pushServiceProvider) { yield return(instruction); } } yield return(Instruction.Create(OpCodes.Callvirt, convertFromInvariantStringReference)); if (targetTypeRef.IsValueType && unboxValueTypes) { yield return(Instruction.Create(OpCodes.Unbox_Any, module.ImportReference(targetTypeRef))); } //ConvertFrom returns an object, no need to Box yield break; } var originalTypeRef = targetTypeRef; var isNullable = false; MethodReference nullableCtor = null; if (targetTypeRef.Resolve().FullName == "System.Nullable`1") { var nullableTypeRef = targetTypeRef; targetTypeRef = ((GenericInstanceType)targetTypeRef).GenericArguments[0]; isNullable = true; nullableCtor = originalTypeRef.GetMethods(md => md.IsConstructor && md.Parameters.Count == 1, module).Single().Item1; nullableCtor = nullableCtor.ResolveGenericParameters(nullableTypeRef, module); } var implicitOperator = module.TypeSystem.String.GetImplicitOperatorTo(targetTypeRef, module); //Obvious Built-in conversions if (targetTypeRef.Resolve().BaseType != null && targetTypeRef.Resolve().BaseType.FullName == "System.Enum") { yield return(PushParsedEnum(targetTypeRef, str, node)); } else if (targetTypeRef.FullName == "System.Char") { yield return(Instruction.Create(OpCodes.Ldc_I4, Char.Parse(str))); } else if (targetTypeRef.FullName == "System.SByte") { yield return(Instruction.Create(OpCodes.Ldc_I4, SByte.Parse(str, CultureInfo.InvariantCulture))); } else if (targetTypeRef.FullName == "System.Int16") { yield return(Instruction.Create(OpCodes.Ldc_I4, Int16.Parse(str, CultureInfo.InvariantCulture))); } else if (targetTypeRef.FullName == "System.Int32") { yield return(Instruction.Create(OpCodes.Ldc_I4, Int32.Parse(str, CultureInfo.InvariantCulture))); } else if (targetTypeRef.FullName == "System.Int64") { yield return(Instruction.Create(OpCodes.Ldc_I8, Int64.Parse(str, CultureInfo.InvariantCulture))); } else if (targetTypeRef.FullName == "System.Byte") { yield return(Instruction.Create(OpCodes.Ldc_I4, Byte.Parse(str, CultureInfo.InvariantCulture))); } else if (targetTypeRef.FullName == "System.UInt16") { yield return(Instruction.Create(OpCodes.Ldc_I4, unchecked ((int)UInt16.Parse(str, CultureInfo.InvariantCulture)))); } else if (targetTypeRef.FullName == "System.UInt32") { yield return(Instruction.Create(OpCodes.Ldc_I4, UInt32.Parse(str, CultureInfo.InvariantCulture))); } else if (targetTypeRef.FullName == "System.UInt64") { yield return(Instruction.Create(OpCodes.Ldc_I8, unchecked ((long)UInt64.Parse(str, CultureInfo.InvariantCulture)))); } else if (targetTypeRef.FullName == "System.Single") { yield return(Instruction.Create(OpCodes.Ldc_R4, Single.Parse(str, CultureInfo.InvariantCulture))); } else if (targetTypeRef.FullName == "System.Double") { yield return(Instruction.Create(OpCodes.Ldc_R8, Double.Parse(str, CultureInfo.InvariantCulture))); } else if (targetTypeRef.FullName == "System.Boolean") { if (Boolean.Parse(str)) { yield return(Instruction.Create(OpCodes.Ldc_I4_1)); } else { yield return(Instruction.Create(OpCodes.Ldc_I4_0)); } } else if (targetTypeRef.FullName == "System.TimeSpan") { var ts = TimeSpan.Parse(str, CultureInfo.InvariantCulture); var ticks = ts.Ticks; var timeSpanCtor = module.ImportReference(typeof(TimeSpan)) .Resolve() .Methods.FirstOrDefault(md => md.IsConstructor && md.Parameters.Count == 1); var timeSpanCtorRef = module.ImportReference(timeSpanCtor); yield return(Instruction.Create(OpCodes.Ldc_I8, ticks)); yield return(Instruction.Create(OpCodes.Newobj, timeSpanCtorRef)); } else if (targetTypeRef.FullName == "System.DateTime") { var dt = DateTime.Parse(str, CultureInfo.InvariantCulture); var ticks = dt.Ticks; var dateTimeCtor = module.ImportReference(typeof(DateTime)) .Resolve() .Methods.FirstOrDefault(md => md.IsConstructor && md.Parameters.Count == 1); var dateTimeCtorRef = module.ImportReference(dateTimeCtor); yield return(Instruction.Create(OpCodes.Ldc_I8, ticks)); yield return(Instruction.Create(OpCodes.Newobj, dateTimeCtorRef)); } else if (targetTypeRef.FullName == "System.String" && str.StartsWith("{}", StringComparison.Ordinal)) { yield return(Instruction.Create(OpCodes.Ldstr, str.Substring(2))); } else if (targetTypeRef.FullName == "System.String") { yield return(Instruction.Create(OpCodes.Ldstr, str)); } else if (targetTypeRef.FullName == "System.Object") { yield return(Instruction.Create(OpCodes.Ldstr, str)); } else if (targetTypeRef.FullName == "System.Decimal") { decimal outdecimal; if (decimal.TryParse(str, NumberStyles.Number, CultureInfo.InvariantCulture, out outdecimal)) { var vardef = new VariableDefinition(context.Body.Method.Module.ImportReference(typeof(decimal))); context.Body.Variables.Add(vardef); //Use an extra temp var so we can push the value to the stack, just like other cases // IL_0003: ldstr "adecimal" // IL_0008: ldc.i4.s 0x6f // IL_000a: call class [mscorlib]System.Globalization.CultureInfo class [mscorlib]System.Globalization.CultureInfo::get_InvariantCulture() // IL_000f: ldloca.s 0 // IL_0011: call bool valuetype [mscorlib]System.Decimal::TryParse(string, valuetype [mscorlib]System.Globalization.NumberStyles, class [mscorlib]System.IFormatProvider, [out] valuetype [mscorlib]System.Decimal&) // IL_0016: pop yield return(Instruction.Create(OpCodes.Ldstr, str)); yield return(Instruction.Create(OpCodes.Ldc_I4, 0x6f)); //NumberStyles.Number var getInvariantInfo = context.Body.Method.Module.ImportReference(typeof(CultureInfo)) .Resolve() .Properties.FirstOrDefault(pd => pd.Name == "InvariantCulture") .GetMethod; var getInvariant = context.Body.Method.Module.ImportReference(getInvariantInfo); yield return(Instruction.Create(OpCodes.Call, getInvariant)); yield return(Instruction.Create(OpCodes.Ldloca, vardef)); var tryParseInfo = context.Body.Method.Module.ImportReference(typeof(decimal)) .Resolve() .Methods.FirstOrDefault(md => md.Name == "TryParse" && md.Parameters.Count == 4); var tryParse = context.Body.Method.Module.ImportReference(tryParseInfo); yield return(Instruction.Create(OpCodes.Call, tryParse)); yield return(Instruction.Create(OpCodes.Pop)); yield return(Instruction.Create(OpCodes.Ldloc, vardef)); } else { yield return(Instruction.Create(OpCodes.Ldc_I4_0)); var decimalctorinfo = context.Body.Method.Module.ImportReference(typeof(decimal)) .Resolve() .Methods.FirstOrDefault( md => md.IsConstructor && md.Parameters.Count == 1 && md.Parameters[0].ParameterType.FullName == "System.Int32"); var decimalctor = context.Body.Method.Module.ImportReference(decimalctorinfo); yield return(Instruction.Create(OpCodes.Newobj, decimalctor)); } } else if (implicitOperator != null) { yield return(Instruction.Create(OpCodes.Ldstr, node.Value as string)); yield return(Instruction.Create(OpCodes.Call, module.ImportReference(implicitOperator))); } else { yield return(Instruction.Create(OpCodes.Ldnull)); } if (isNullable) { yield return(Instruction.Create(OpCodes.Newobj, module.ImportReference(nullableCtor))); } if (originalTypeRef.IsValueType && boxValueTypes) { yield return(Instruction.Create(OpCodes.Box, module.ImportReference(originalTypeRef))); } }
private bool SetSqlQueryInstruction(Instruction instruction) { //This only works with calls to IDbCommand, I will add //the checking with different providers. return(String.Compare(instruction.Operand.ToString(), "System.Void System.Data.IDbCommand::set_CommandText(System.String)") == 0); }
private static Operand GetFPComparison(EmitterContext context, FComp cond, Operand srcA, Operand srcB, Instruction fpType = Instruction.FP32) { Operand res; if (cond == FComp.T) { res = Const(IrConsts.True); } else if (cond == FComp.F) { res = Const(IrConsts.False); } else if (cond == FComp.Nan || cond == FComp.Num) { res = context.BitwiseOr(context.IsNan(srcA, fpType), context.IsNan(srcB, fpType)); if (cond == FComp.Num) { res = context.BitwiseNot(res); } } else { Instruction inst; switch (cond & ~FComp.Nan) { case FComp.Lt: inst = Instruction.CompareLess; break; case FComp.Eq: inst = Instruction.CompareEqual; break; case FComp.Le: inst = Instruction.CompareLessOrEqual; break; case FComp.Gt: inst = Instruction.CompareGreater; break; case FComp.Ne: inst = Instruction.CompareNotEqual; break; case FComp.Ge: inst = Instruction.CompareGreaterOrEqual; break; default: throw new ArgumentException($"Unexpected condition \"{cond}\"."); } res = context.Add(inst | fpType, Local(), srcA, srcB); if ((cond & FComp.Nan) != 0) { res = context.BitwiseOr(res, context.IsNan(srcA, fpType)); res = context.BitwiseOr(res, context.IsNan(srcB, fpType)); } } return(res); }
void CreateEdge(ControlFlowNode fromNode, Instruction toInstruction, JumpType type) { CreateEdge(fromNode, nodes.Single(n => n.Start != null && n.Start.Value == toInstruction), type); }
static MethodDefinition GenerateArraySegmentWriteFunc(TypeReference variable, int recursionCount) { GenericInstanceType genericInstance = (GenericInstanceType)variable; TypeReference elementType = genericInstance.GenericArguments[0]; MethodReference elementWriteFunc = GetWriteFunc(elementType, recursionCount + 1); if (elementWriteFunc == null) { return(null); } string functionName = "_WriteArraySegment_" + elementType.Name + "_"; if (variable.DeclaringType != null) { functionName += variable.DeclaringType.Name; } else { functionName += "None"; } // create new writer for this type MethodDefinition writerFunc = new MethodDefinition(functionName, MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig, Weaver.voidType); writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkWriterType))); writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, variable)); writerFunc.Body.Variables.Add(new VariableDefinition(Weaver.int32Type)); writerFunc.Body.Variables.Add(new VariableDefinition(Weaver.int32Type)); writerFunc.Body.InitLocals = true; ILProcessor worker = writerFunc.Body.GetILProcessor(); MethodReference countref = Weaver.ArraySegmentCountReference.MakeHostInstanceGeneric(genericInstance); // int length = value.Count; worker.Append(worker.Create(OpCodes.Ldarga_S, (byte)1)); worker.Append(worker.Create(OpCodes.Call, countref)); worker.Append(worker.Create(OpCodes.Stloc_0)); // writer.WritePackedInt32(length); worker.Append(worker.Create(OpCodes.Ldarg_0)); worker.Append(worker.Create(OpCodes.Ldloc_0)); worker.Append(worker.Create(OpCodes.Call, GetWriteFunc(Weaver.int32Type))); // Loop through the ArraySegment<T> and call the writer for each element. // generates this: // for (int i=0; i< length; i++) // { // writer.Write(value.Array[i + value.Offset]); // } worker.Append(worker.Create(OpCodes.Ldc_I4_0)); worker.Append(worker.Create(OpCodes.Stloc_1)); Instruction labelHead = worker.Create(OpCodes.Nop); worker.Append(worker.Create(OpCodes.Br, labelHead)); // loop body Instruction labelBody = worker.Create(OpCodes.Nop); worker.Append(labelBody); // writer.Write(value.Array[i + value.Offset]); worker.Append(worker.Create(OpCodes.Ldarg_0)); worker.Append(worker.Create(OpCodes.Ldarga_S, (byte)1)); worker.Append(worker.Create(OpCodes.Call, Weaver.ArraySegmentArrayReference.MakeHostInstanceGeneric(genericInstance))); worker.Append(worker.Create(OpCodes.Ldloc_1)); worker.Append(worker.Create(OpCodes.Ldarga_S, (byte)1)); worker.Append(worker.Create(OpCodes.Call, Weaver.ArraySegmentOffsetReference.MakeHostInstanceGeneric(genericInstance))); worker.Append(worker.Create(OpCodes.Add)); worker.Append(worker.Create(OpCodes.Ldelema, elementType)); worker.Append(worker.Create(OpCodes.Ldobj, elementType)); worker.Append(worker.Create(OpCodes.Call, elementWriteFunc)); worker.Append(worker.Create(OpCodes.Ldloc_1)); worker.Append(worker.Create(OpCodes.Ldc_I4_1)); worker.Append(worker.Create(OpCodes.Add)); worker.Append(worker.Create(OpCodes.Stloc_1)); // end for loop worker.Append(labelHead); worker.Append(worker.Create(OpCodes.Ldloc_1)); worker.Append(worker.Create(OpCodes.Ldloc_0)); worker.Append(worker.Create(OpCodes.Blt, labelBody)); // return worker.Append(worker.Create(OpCodes.Ret)); return(writerFunc); }
public override bool IsInstruction(Instruction instruction) => instruction.OpCode == Opcode.Le && instruction.A == 0 && instruction.B <= 255 && instruction.C <= 255;
public override void SetUp(Instruction op, SpirvInstructionTreeBuilder treeBuilder) { base.SetUp(op, treeBuilder); SetUp((OpFSub)op, treeBuilder); }
public GlobalStringRefToConstantAction(MethodAnalysis context, Instruction instruction) : base(context, instruction) { }
private void EmitILForInlineNone(ILGenerator ilGenerator, Instruction instruction) => ilGenerator.Emit(instruction.OpCode);
public void Handel(IRAssembly assembly, IRMethod meth, UskrContext context, Instruction instruction) { context.Asm("pop eax"); //value context.Asm("pop ebx"); //adress context.Asm("mov [ebx], eax"); }
bool TryCoreCompile(MethodDefinition initComp, MethodDefinition initCompRuntime, ILRootNode rootnode, out Exception exception) { try { var body = new MethodBody(initComp); var il = body.GetILProcessor(); il.Emit(OpCodes.Nop); if (initCompRuntime != null) { // Generating branching code for the Previewer // IL_0007: call class [mscorlib]System.Func`2<class [mscorlib]System.Type,string> class [Xamarin.Forms.Xaml.Internals]Xamarin.Forms.Xaml.XamlLoader::get_XamlFileProvider() // IL_000c: brfalse IL_0031 // IL_0011: call class [mscorlib]System.Func`2<class [mscorlib]System.Type,string> class [Xamarin.Forms.Xaml.Internals]Xamarin.Forms.Xaml.XamlLoader::get_XamlFileProvider() // IL_0016: ldarg.0 // IL_0017: call instance class [mscorlib]System.Type object::GetType() // IL_001c: callvirt instance !1 class [mscorlib]System.Func`2<class [mscorlib]System.Type, string>::Invoke(!0) // IL_0021: brfalse IL_0031 // IL_0026: ldarg.0 // IL_0027: call instance void class Xamarin.Forms.Xaml.UnitTests.XamlLoaderGetXamlForTypeTests::__InitComponentRuntime() // IL_002c: ret // IL_0031: nop var nop = Instruction.Create(OpCodes.Nop); var getXamlFileProvider = body.Method.Module.Import(body.Method.Module.Import(typeof(Xamarin.Forms.Xaml.Internals.XamlLoader)) .Resolve() .Properties.FirstOrDefault(pd => pd.Name == "XamlFileProvider") .GetMethod); il.Emit(OpCodes.Call, getXamlFileProvider); il.Emit(OpCodes.Brfalse, nop); il.Emit(OpCodes.Call, getXamlFileProvider); il.Emit(OpCodes.Ldarg_0); var getType = body.Method.Module.Import(body.Method.Module.Import(typeof(object)) .Resolve() .Methods.FirstOrDefault(md => md.Name == "GetType")); il.Emit(OpCodes.Call, getType); var func = body.Method.Module.Import(body.Method.Module.Import(typeof(Func <Type, string>)) .Resolve() .Methods.FirstOrDefault(md => md.Name == "Invoke")); func = func.ResolveGenericParameters(body.Method.Module.Import(typeof(Func <Type, string>)), body.Method.Module); il.Emit(OpCodes.Callvirt, func); il.Emit(OpCodes.Brfalse, nop); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, initCompRuntime); il.Emit(OpCodes.Ret); il.Append(nop); } var visitorContext = new ILContext(il, body, body.Method.Module); rootnode.Accept(new XamlNodeVisitor((node, parent) => node.Parent = parent), null); rootnode.Accept(new ExpandMarkupsVisitor(visitorContext), null); rootnode.Accept(new PruneIgnoredNodesVisitor(), null); rootnode.Accept(new CreateObjectVisitor(visitorContext), null); rootnode.Accept(new SetNamescopesAndRegisterNamesVisitor(visitorContext), null); rootnode.Accept(new SetFieldVisitor(visitorContext), null); rootnode.Accept(new SetResourcesVisitor(visitorContext), null); rootnode.Accept(new SetPropertiesVisitor(visitorContext, true), null); il.Emit(OpCodes.Ret); initComp.Body = body; exception = null; return(true); } catch (Exception e) { exception = e; return(false); } }
public void Execute(Instruction instruction, ICpu cpu, IMmu mmu) { throw new NotImplementedException(Mnemonic); }
public Or(Instruction left, Instruction right) { this.Left = left; this.Right = right; }
private static void CopyMethodDef(MethodDef methodDef, InjectContext ctx) { var newMethodDef = (MethodDef)ctx.map[methodDef]; newMethodDef.Signature = ctx.Importer.Import(methodDef.Signature); newMethodDef.Parameters.UpdateParameterTypes(); if (methodDef.ImplMap != null) { newMethodDef.ImplMap = new ImplMapUser(new ModuleRefUser(ctx.TargetModule, methodDef.ImplMap.Module.Name), methodDef.ImplMap.Name, methodDef.ImplMap.Attributes); } foreach (var ca in methodDef.CustomAttributes) { newMethodDef.CustomAttributes.Add(new CustomAttribute((ICustomAttributeType)ctx.Importer.Import(ca.Constructor))); } if (!methodDef.HasBody) { return; } newMethodDef.Body = new CilBody(methodDef.Body.InitLocals, new List <Instruction>(), new List <ExceptionHandler>(), new List <Local>()) { MaxStack = methodDef.Body.MaxStack }; var bodyMap = new Dictionary <object, object>(); foreach (var local in methodDef.Body.Variables) { var newLocal = new Local(ctx.Importer.Import(local.Type)); newMethodDef.Body.Variables.Add(newLocal); newLocal.Name = local.Name; newLocal.Attributes = local.Attributes; bodyMap[local] = newLocal; } foreach (var instr in methodDef.Body.Instructions) { var newInstr = new Instruction(instr.OpCode, instr.Operand) { SequencePoint = instr.SequencePoint }; switch (newInstr.Operand) { case IType type: newInstr.Operand = ctx.Importer.Import(type); break; case IMethod method: newInstr.Operand = ctx.Importer.Import(method); break; case IField field: newInstr.Operand = ctx.Importer.Import(field); break; } newMethodDef.Body.Instructions.Add(newInstr); bodyMap[instr] = newInstr; } foreach (var instr in newMethodDef.Body.Instructions) { if (instr.Operand != null && bodyMap.ContainsKey(instr.Operand)) { instr.Operand = bodyMap[instr.Operand]; } else if (instr.Operand is Instruction[] v) { instr.Operand = v.Select(target => (Instruction)bodyMap[target]).ToArray(); } } foreach (var eh in methodDef.Body.ExceptionHandlers) { newMethodDef.Body.ExceptionHandlers.Add(new ExceptionHandler(eh.HandlerType) { CatchType = eh.CatchType == null ? null : ctx.Importer.Import(eh.CatchType), TryStart = (Instruction)bodyMap[eh.TryStart], TryEnd = (Instruction)bodyMap[eh.TryEnd], HandlerStart = (Instruction)bodyMap[eh.HandlerStart], HandlerEnd = (Instruction)bodyMap[eh.HandlerEnd], FilterStart = eh.FilterStart == null ? null : (Instruction)bodyMap[eh.FilterStart] }); } newMethodDef.Body.SimplifyMacros(newMethodDef.Parameters); }
private void EmitILForInlineBrTarget(ILGenerator ilGenerator, Instruction instruction, Dictionary <int, Label> targetInstructions) { Label targetLabel = targetInstructions[(instruction.Operand as Instruction).Offset]; // Offset values could change and not be short form anymore if (instruction.OpCode == OpCodes.Br_S) { ilGenerator.Emit(OpCodes.Br, targetLabel); } else if (instruction.OpCode == OpCodes.Brfalse_S) { ilGenerator.Emit(OpCodes.Brfalse, targetLabel); } else if (instruction.OpCode == OpCodes.Brtrue_S) { ilGenerator.Emit(OpCodes.Brtrue, targetLabel); } else if (instruction.OpCode == OpCodes.Beq_S) { ilGenerator.Emit(OpCodes.Beq, targetLabel); } else if (instruction.OpCode == OpCodes.Bge_S) { ilGenerator.Emit(OpCodes.Bge, targetLabel); } else if (instruction.OpCode == OpCodes.Bgt_S) { ilGenerator.Emit(OpCodes.Bgt, targetLabel); } else if (instruction.OpCode == OpCodes.Ble_S) { ilGenerator.Emit(OpCodes.Ble, targetLabel); } else if (instruction.OpCode == OpCodes.Blt_S) { ilGenerator.Emit(OpCodes.Blt, targetLabel); } else if (instruction.OpCode == OpCodes.Bne_Un_S) { ilGenerator.Emit(OpCodes.Bne_Un, targetLabel); } else if (instruction.OpCode == OpCodes.Bge_Un_S) { ilGenerator.Emit(OpCodes.Bge_Un, targetLabel); } else if (instruction.OpCode == OpCodes.Bgt_Un_S) { ilGenerator.Emit(OpCodes.Bgt_Un, targetLabel); } else if (instruction.OpCode == OpCodes.Ble_Un_S) { ilGenerator.Emit(OpCodes.Ble_Un, targetLabel); } else if (instruction.OpCode == OpCodes.Blt_Un_S) { ilGenerator.Emit(OpCodes.Blt_Un, targetLabel); } else if (instruction.OpCode == OpCodes.Leave_S) { ilGenerator.Emit(OpCodes.Leave, targetLabel); } else { ilGenerator.Emit(instruction.OpCode, targetLabel); } }
private bool IsCallingInstruction(Instruction instruction) { return((instruction.OpCode.Code == Code.Call) || (instruction.OpCode.Code == Code.Callvirt)); }
private void EmitILForInlineString(ILGenerator ilGenerator, Instruction instruction) => ilGenerator.Emit(instruction.OpCode, (string)instruction.Operand);
public static IEnumerable <Instruction> PushServiceProvider(this INode node, ILContext context, FieldReference bpRef = null, PropertyReference propertyRef = null, TypeReference declaringTypeReference = null) { var module = context.Body.Method.Module; #if NOSERVICEPROVIDER yield return(Instruction.Create(OpCodes.Ldnull)); yield break; #endif var ctorinfo = typeof(XamlServiceProvider).GetConstructor(new Type[] { }); var ctor = module.ImportReference(ctorinfo); var addServiceInfo = typeof(XamlServiceProvider).GetMethod("Add", new[] { typeof(Type), typeof(object) }); var addService = module.ImportReference(addServiceInfo); var getTypeFromHandle = module.ImportReference(typeof(Type).GetMethod("GetTypeFromHandle", new[] { typeof(RuntimeTypeHandle) })); var getAssembly = module.ImportReference(typeof(Type).GetProperty("Assembly").GetMethod); yield return(Instruction.Create(OpCodes.Newobj, ctor)); //Add a SimpleValueTargetProvider var pushParentIl = node.PushParentObjectsArray(context).ToList(); if (pushParentIl[pushParentIl.Count - 1].OpCode != OpCodes.Ldnull) { yield return(Instruction.Create(OpCodes.Dup)); //Keep the serviceProvider on the stack yield return(Instruction.Create(OpCodes.Ldtoken, module.ImportReference(typeof(IProvideValueTarget)))); yield return(Instruction.Create(OpCodes.Call, module.ImportReference(getTypeFromHandle))); foreach (var instruction in pushParentIl) { yield return(instruction); } foreach (var instruction in PushTargetProperty(bpRef, propertyRef, declaringTypeReference, module)) { yield return(instruction); } var targetProviderCtor = module.ImportReference(typeof(SimpleValueTargetProvider).GetConstructor(new[] { typeof(object[]), typeof(object) })); yield return(Instruction.Create(OpCodes.Newobj, targetProviderCtor)); yield return(Instruction.Create(OpCodes.Callvirt, addService)); } //Add a NamescopeProvider if (context.Scopes.ContainsKey(node)) { yield return(Instruction.Create(OpCodes.Dup)); //Dupicate the serviceProvider yield return(Instruction.Create(OpCodes.Ldtoken, module.ImportReference(typeof(INameScopeProvider)))); yield return(Instruction.Create(OpCodes.Call, module.ImportReference(getTypeFromHandle))); var namescopeProviderCtor = module.ImportReference(typeof(NameScopeProvider).GetConstructor(new Type[] { })); yield return(Instruction.Create(OpCodes.Newobj, namescopeProviderCtor)); yield return(Instruction.Create(OpCodes.Dup)); //Duplicate the namescopeProvider var setNamescope = module.ImportReference(typeof(NameScopeProvider).GetProperty("NameScope").GetSetMethod()); yield return(Instruction.Create(OpCodes.Ldloc, context.Scopes[node].Item1)); yield return(Instruction.Create(OpCodes.Callvirt, setNamescope)); yield return(Instruction.Create(OpCodes.Callvirt, addService)); } //Add a XamlTypeResolver if (node.NamespaceResolver != null) { yield return(Instruction.Create(OpCodes.Dup)); //Dupicate the serviceProvider yield return(Instruction.Create(OpCodes.Ldtoken, module.ImportReference(typeof(IXamlTypeResolver)))); yield return(Instruction.Create(OpCodes.Call, module.ImportReference(getTypeFromHandle))); var xmlNamespaceResolverCtor = module.ImportReference(typeof(XmlNamespaceResolver).GetConstructor(new Type[] { })); var addNamespace = module.ImportReference(typeof(XmlNamespaceResolver).GetMethod("Add")); yield return(Instruction.Create(OpCodes.Newobj, xmlNamespaceResolverCtor)); foreach (var kvp in node.NamespaceResolver.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml)) { yield return(Instruction.Create(OpCodes.Dup)); //dup the resolver yield return(Instruction.Create(OpCodes.Ldstr, kvp.Key)); yield return(Instruction.Create(OpCodes.Ldstr, kvp.Value)); yield return(Instruction.Create(OpCodes.Callvirt, addNamespace)); } yield return(Instruction.Create(OpCodes.Ldtoken, context.Body.Method.DeclaringType)); yield return(Instruction.Create(OpCodes.Call, module.ImportReference(getTypeFromHandle))); yield return(Instruction.Create(OpCodes.Callvirt, getAssembly)); var xtr = module.ImportReference(typeof(XamlTypeResolver)).Resolve(); var xamlTypeResolverCtor = module.ImportReference(xtr.Methods.First(md => md.IsConstructor && md.Parameters.Count == 2)); yield return(Instruction.Create(OpCodes.Newobj, xamlTypeResolverCtor)); yield return(Instruction.Create(OpCodes.Callvirt, addService)); } if (node is IXmlLineInfo) { yield return(Instruction.Create(OpCodes.Dup)); //Dupicate the serviceProvider yield return(Instruction.Create(OpCodes.Ldtoken, module.ImportReference(typeof(IXmlLineInfoProvider)))); yield return(Instruction.Create(OpCodes.Call, module.ImportReference(getTypeFromHandle))); foreach (var instruction in node.PushXmlLineInfo(context)) { yield return(instruction); } var lip = module.ImportReference(typeof(XmlLineInfoProvider)).Resolve(); var lineInfoProviderCtor = module.ImportReference(lip.Methods.First(md => md.IsConstructor && md.Parameters.Count == 1)); yield return(Instruction.Create(OpCodes.Newobj, lineInfoProviderCtor)); yield return(Instruction.Create(OpCodes.Callvirt, addService)); } }
private void EmitILForShortInlineR(ILGenerator ilGenerator, Instruction instruction) => ilGenerator.Emit(instruction.OpCode, (float)instruction.Operand);
static Instruction PushParsedEnum(TypeReference enumRef, string value, IXmlLineInfo lineInfo) { var enumDef = enumRef.Resolve(); if (!enumDef.IsEnum) { throw new InvalidOperationException(); } // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. // https://msdn.microsoft.com/en-us/library/sbbt4032.aspx byte b = 0; sbyte sb = 0; short s = 0; ushort us = 0; int i = 0; uint ui = 0; long l = 0; ulong ul = 0; bool found = false; TypeReference typeRef = null; foreach (var field in enumDef.Fields) { if (field.Name == "value__") { typeRef = field.FieldType; } } if (typeRef == null) { throw new ArgumentException(); } foreach (var v in value.Split(',')) { foreach (var field in enumDef.Fields) { if (field.Name == "value__") { continue; } if (field.Name == v.Trim()) { switch (typeRef.FullName) { case "System.Byte": b |= (byte)field.Constant; break; case "System.SByte": if (found) { throw new XamlParseException($"Multi-valued enums are not valid on sbyte enum types", lineInfo); } sb = (sbyte)field.Constant; break; case "System.Int16": s |= (short)field.Constant; break; case "System.UInt16": us |= (ushort)field.Constant; break; case "System.Int32": i |= (int)field.Constant; break; case "System.UInt32": ui |= (uint)field.Constant; break; case "System.Int64": l |= (long)field.Constant; break; case "System.UInt64": ul |= (ulong)field.Constant; break; } found = true; } } } if (!found) { throw new XamlParseException($"Enum value not found for {value}", lineInfo); } switch (typeRef.FullName) { case "System.Byte": return(Instruction.Create(OpCodes.Ldc_I4, (int)b)); case "System.SByte": return(Instruction.Create(OpCodes.Ldc_I4, (int)sb)); case "System.Int16": return(Instruction.Create(OpCodes.Ldc_I4, (int)s)); case "System.UInt16": return(Instruction.Create(OpCodes.Ldc_I4, (int)us)); case "System.Int32": return(Instruction.Create(OpCodes.Ldc_I4, (int)i)); case "System.UInt32": return(Instruction.Create(OpCodes.Ldc_I4, (uint)ui)); case "System.Int64": return(Instruction.Create(OpCodes.Ldc_I4, (long)l)); case "System.UInt64": return(Instruction.Create(OpCodes.Ldc_I4, (ulong)ul)); default: throw new XamlParseException($"Enum value not found for {value}", lineInfo); } }
private void EmitILForInlineR(ILGenerator ilGenerator, Instruction instruction) => ilGenerator.Emit(instruction.OpCode, (double)instruction.Operand);
public override bool IsInstruction(Instruction instruction) => instruction.OpCode == Opcode.LoadNil;
protected override SyntaxTreeNode CreateNode(Instruction instruction, string scope, Match match) { return(new ProcedureNode(instruction, scope, match, match.Groups["kind"].Value.Split(' ')[0], new List <SyntaxTreeNode>())); }
public void set_next_inst(Instruction in_inst) { current_inst = in_inst; }
private static void Main(string[] args) { var cmd = new Process { StartInfo = { FileName = "cmd", RedirectStandardInput = true, RedirectStandardOutput = true, CreateNoWindow = true, UseShellExecute = false } }; cmd.Start(); cmd.StandardInput.WriteLine("chcp 65001"); cmd.StandardInput.Flush(); cmd.StandardInput.Close(); Console.OutputEncoding = Encoding.UTF8; var files = new[] { // @"G:\Escape from Tarkov\EscapeFromTarkov_Data\Managed\Assembly-CSharp.dll", @"G:\Escape from Tarkov\EscapeFromTarkov_Data\Managed\Assembly-CSharp.dll.ORG", }; foreach (var dll in files) { var file = new FileInfo(dll); Console.WriteLine("Loaded {0}", file.FullName.Quote()); var _Module = ModuleDefinition.ReadModule(dll); TypeDefinition beClass = null; MethodDefinition beMethod = null; try { foreach (var _class in _Module.GetTypes()) { if (_class.IsPublic || !_class.IsSealed) { continue; } if (!_class.HasProperties || _class.Properties.Count != 1) { continue; } if (!_class.HasFields || _class.Fields.Count != 2) { continue; } if (!_class.HasMethods) { continue; } foreach (var method in _class.Methods) { if (method.ReturnType.ToString() == "System.Collections.IEnumerator") { beMethod = method; break; } } if (beMethod is null) { continue; } beClass = _class; break; } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } if (beClass is null) { var cc = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("[WARNING]"); Console.WriteLine("BattlEye class or method was not found! If your game directly closes after launch you know why!"); Console.WriteLine("[WARNING]"); Console.ForegroundColor = cc; Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } else { var beName = string.Format("{0}::{1} ({2}::{3})", beClass.Name, beMethod.Name, beClass.Name.ToUnicode(), beMethod.Name.ToUnicode()); Console.WriteLine("Found BattlEye as {0}", beName); // Console.ReadKey(); var inst = new Collection <Instruction>(); // print call MethodInfo writeLineMethod = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }); var sentence = string.Concat("BattlEye check called. Bypassing..."); inst.Add(Instruction.Create(OpCodes.Ldstr, sentence)); var writeLine = _Module.Import(writeLineMethod); inst.Add(Instruction.Create(OpCodes.Call, writeLine)); // set success inst.Add(Instruction.Create(OpCodes.Ldarg_0)); inst.Add(Instruction.Create(OpCodes.Ldc_I4_1)); var _com_mod = ModuleDefinition.ReadModule(@"G:\Escape from Tarkov\EscapeFromTarkov_Data\Managed\Comfort.Unity.dll"); var coms = _com_mod.GetTypes(); var abs_op = coms.First(t => t.Name == "AbstractOperation"); var succ_type = _Module.Import(abs_op.Properties.First(p => p.Name == "Succeed").SetMethod); inst.Add(Instruction.Create(OpCodes.Callvirt, succ_type)); // reutrn empty IEnumerator var obj_type = _Module.Import(typeof(object)); var obj_type_get_enu = _Module.Import(typeof(Array).GetMethod("GetEnumerator")); inst.Add(Instruction.Create(OpCodes.Ldc_I4_0)); inst.Add(Instruction.Create(OpCodes.Newarr, obj_type)); inst.Add(Instruction.Create(OpCodes.Call, obj_type_get_enu)); inst.Add(Instruction.Create(OpCodes.Ret)); beMethod.Body.Instructions.Clear(); foreach (var _ins in inst) { beMethod.Body.Instructions.Add(_ins); } Console.WriteLine("Patched BattlEye!"); // Console.ReadKey(); var sFN = file.SplitFileName(); var sF = file.Directory.CombineFile(sFN.Key + ".noBE" + sFN.Value); Console.WriteLine("Saving as {0}!", sF.FullName.Quote()); _Module.Write(sF.FullName); } } Console.ReadKey(); }
void Format_NonDec_MemMinimum(int index, Instruction info, string formattedString) => FormatBase(index, info, formattedString, FormatterFactory.Create_MemMinimum());
static MethodDefinition GenerateArrayWriteFunc(TypeReference variable, int recursionCount) { if (!variable.IsArrayType()) { Weaver.Error($"{variable.Name} is an unsupported type. Jagged and multidimensional arrays are not supported", variable); return(null); } TypeReference elementType = variable.GetElementType(); MethodReference elementWriteFunc = GetWriteFunc(elementType, recursionCount + 1); if (elementWriteFunc == null) { return(null); } string functionName = "_WriteArray" + variable.GetElementType().Name + "_"; if (variable.DeclaringType != null) { functionName += variable.DeclaringType.Name; } else { functionName += "None"; } // create new writer for this type MethodDefinition writerFunc = new MethodDefinition(functionName, MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig, Weaver.voidType); writerFunc.Parameters.Add(new ParameterDefinition("writer", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(Weaver.NetworkWriterType))); writerFunc.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, Weaver.CurrentAssembly.MainModule.ImportReference(variable))); writerFunc.Body.Variables.Add(new VariableDefinition(Weaver.int32Type)); writerFunc.Body.Variables.Add(new VariableDefinition(Weaver.int32Type)); writerFunc.Body.InitLocals = true; ILProcessor worker = writerFunc.Body.GetILProcessor(); // if (value == null) // { // writer.WritePackedInt32(-1); // return; // } Instruction labelNull = worker.Create(OpCodes.Nop); worker.Append(worker.Create(OpCodes.Ldarg_1)); worker.Append(worker.Create(OpCodes.Brtrue, labelNull)); worker.Append(worker.Create(OpCodes.Ldarg_0)); worker.Append(worker.Create(OpCodes.Ldc_I4_M1)); worker.Append(worker.Create(OpCodes.Call, GetWriteFunc(Weaver.int32Type))); worker.Append(worker.Create(OpCodes.Ret)); // int length = value.Length; worker.Append(labelNull); worker.Append(worker.Create(OpCodes.Ldarg_1)); worker.Append(worker.Create(OpCodes.Ldlen)); worker.Append(worker.Create(OpCodes.Stloc_0)); // writer.WritePackedInt32(length); worker.Append(worker.Create(OpCodes.Ldarg_0)); worker.Append(worker.Create(OpCodes.Ldloc_0)); worker.Append(worker.Create(OpCodes.Call, GetWriteFunc(Weaver.int32Type))); // for (int i=0; i< value.length; i++) { worker.Append(worker.Create(OpCodes.Ldc_I4_0)); worker.Append(worker.Create(OpCodes.Stloc_1)); Instruction labelHead = worker.Create(OpCodes.Nop); worker.Append(worker.Create(OpCodes.Br, labelHead)); // loop body Instruction labelBody = worker.Create(OpCodes.Nop); worker.Append(labelBody); // writer.Write(value[i]); worker.Append(worker.Create(OpCodes.Ldarg_0)); worker.Append(worker.Create(OpCodes.Ldarg_1)); worker.Append(worker.Create(OpCodes.Ldloc_1)); worker.Append(worker.Create(OpCodes.Ldelema, variable.GetElementType())); worker.Append(worker.Create(OpCodes.Ldobj, variable.GetElementType())); worker.Append(worker.Create(OpCodes.Call, elementWriteFunc)); worker.Append(worker.Create(OpCodes.Ldloc_1)); worker.Append(worker.Create(OpCodes.Ldc_I4_1)); worker.Append(worker.Create(OpCodes.Add)); worker.Append(worker.Create(OpCodes.Stloc_1)); // end for loop worker.Append(labelHead); worker.Append(worker.Create(OpCodes.Ldloc_1)); worker.Append(worker.Create(OpCodes.Ldarg_1)); worker.Append(worker.Create(OpCodes.Ldlen)); worker.Append(worker.Create(OpCodes.Conv_I4)); worker.Append(worker.Create(OpCodes.Blt, labelBody)); // return worker.Append(worker.Create(OpCodes.Ret)); return(writerFunc); }