public LightCompiler(int compilationThreshold) { this._locals = new LocalVariables(); this._debugInfos = new List<DebugInfo>(); this._treeLabels = new HybridReferenceDictionary<LabelTarget, LabelInfo>(); this._labelBlock = new LabelScopeInfo(null, LabelScopeKind.Lambda); this._exceptionForRethrowStack = new Stack<ParameterExpression>(); this._instructions = new InstructionList(); this._compilationThreshold = (compilationThreshold < 0) ? 0x20 : compilationThreshold; }
internal void Mark(InstructionList instructions) { this._stackDepth = instructions.CurrentStackDepth; this._continuationStackDepth = instructions.CurrentContinuationsDepth; this._targetIndex = instructions.Count; if (this._forwardBranchFixups != null) { foreach (int num in this._forwardBranchFixups) { this.FixupBranch(instructions, num); } this._forwardBranchFixups = null; } }
internal void AddBranch(InstructionList instructions, int branchIndex) { if (this._targetIndex == -2147483648) { if (this._forwardBranchFixups == null) { this._forwardBranchFixups = new List<int>(); } this._forwardBranchFixups.Add(branchIndex); } else { this.FixupBranch(instructions, branchIndex); } }
internal void Mark(InstructionList instructions) { //ContractUtils.Requires(_targetIndex == UnknownIndex && _stackDepth == UnknownDepth && _continuationStackDepth == UnknownDepth); _stackDepth = instructions.CurrentStackDepth; _continuationStackDepth = instructions.CurrentContinuationsDepth; _targetIndex = instructions.Count; if (_forwardBranchFixups != null) { foreach (var branchIndex in _forwardBranchFixups) { FixupBranch(instructions, branchIndex); } _forwardBranchFixups = null; } }
public static void RecordInstructions(InstructionList listToRecordTo, double timeToExecute, List<string> membersToIgnore, PositionedModel modelToRecord) { foreach (string member in EditorData.CurrentPositionedModelMembersWatching) { if (membersToIgnore.Contains(member) == false) { Type memberType = InstructionManager.GetTypeForMember(mPositionedModelType, member); Type genericType = typeof(Instruction<,>).MakeGenericType( mPositionedModelType, memberType); object value = FlatRedBall.Instructions.Reflection.LateBinder<PositionedModel>.Instance[modelToRecord, member]; Instruction instruction = Activator.CreateInstance(genericType, modelToRecord, member, value, timeToExecute) as Instruction; listToRecordTo.Add(instruction); } } }
internal void Box(ParameterExpression variable, InstructionList instructions) { VariableScope scope = this._variables[variable]; LocalVariable variable2 = scope.Variable; this._variables[variable].Variable.IsBoxed = true; int num = 0; for (int i = scope.Start; (i < scope.Stop) && (i < instructions.Count); i++) { if ((scope.ChildScopes != null) && (scope.ChildScopes[num].Start == i)) { VariableScope scope2 = scope.ChildScopes[num]; i = scope2.Stop; num++; } else { instructions.SwitchToBoxed(variable2.Index, i); } } }
public void AddList(InstructionList list) { KeyframeSave keyframe = new KeyframeSave(); foreach (Instruction instruction in list) { if (instruction is GenericInstruction) { GenericInstruction asGenericInstruction = instruction as GenericInstruction; InstructionSave instructionSave = InstructionSave.FromInstruction(asGenericInstruction); keyframe.InstructionSaves.Add(instructionSave); } else { throw new NotImplementedException("This list contains a type of instruction that cannot be saved."); } } keyframe.Name = list.Name; SceneKeyframes.Add(keyframe); }
private void MarkReachable(int index, InstructionList instructions, bool[] reachable, MethodBody body) { for (;index < instructions.Count; ++index) { if (reachable[index]) return; // marked before. var ins = instructions[index]; reachable[index] = true; foreach (var ex in body.Exceptions.Where(p => p.TryStart.Index <= index && p.TryEnd.Index >= index)) { ex.Catches.ForEach(c => MarkReachable(c.Instruction.Index, instructions, reachable, body)); if (ex.CatchAll != null) MarkReachable(ex.CatchAll.Index, instructions, reachable, body); } if (ins.Code.IsReturn() || ins.Code == RCode.Throw) return; if (ins.Code == RCode.Goto) { MarkReachable(((Instruction) ins.Operand).Index, instructions, reachable, body); return; } if (ins.Code == RCode.Packed_switch) { foreach (var target in (Instruction[]) ins.Operand) MarkReachable(target.Index, instructions, reachable, body); } else if (ins.Code == RCode.Sparse_switch) { foreach (var target in (IList<Tuple<int,Instruction>>)ins.Operand) MarkReachable(target.Item2.Index, instructions, reachable, body); } else if (ins.Code.IsBranch()) { MarkReachable(((Instruction) ins.Operand).Index, instructions, reachable, body); } } }
private static IntPtr AllocateStub(IntPtr hProc, string asmPath, string typeName, string methodName, string?args, IntPtr fnAddr, bool x86, bool isV4) { const string clrVersion2 = "v2.0.50727"; const string clrVersion4 = "v4.0.30319"; string clrVersion = isV4 ? clrVersion4 : clrVersion2; const string buildFlavor = "wks"; // WorkStation var clsidCLRRuntimeHost = new Guid(0x90F1A06E, 0x7712, 0x4762, 0x86, 0xB5, 0x7A, 0x5E, 0xBA, 0x6B, 0xDB, 0x02); var iidICLRRuntimeHost = new Guid(0x90F1A06C, 0x7712, 0x4762, 0x86, 0xB5, 0x7A, 0x5E, 0xBA, 0x6B, 0xDB, 0x02); IntPtr ppv = alloc(IntPtr.Size); IntPtr riid = allocBytes(iidICLRRuntimeHost.ToByteArray()); IntPtr rcslid = allocBytes(clsidCLRRuntimeHost.ToByteArray()); IntPtr pwszBuildFlavor = allocString(buildFlavor); IntPtr pwszVersion = allocString(clrVersion); IntPtr pReturnValue = alloc(4); IntPtr pwzArgument = allocString(args); IntPtr pwzMethodName = allocString(methodName); IntPtr pwzTypeName = allocString(typeName); IntPtr pwzAssemblyPath = allocString(asmPath); var instructions = new InstructionList(); if (x86) { // call CorBindtoRuntimeEx instructions.Add(Instruction.Create(Code.Pushd_imm32, ppv.ToInt32())); instructions.Add(Instruction.Create(Code.Pushd_imm32, riid.ToInt32())); instructions.Add(Instruction.Create(Code.Pushd_imm32, rcslid.ToInt32())); instructions.Add(Instruction.Create(Code.Pushd_imm8, 0)); // startupFlags instructions.Add(Instruction.Create(Code.Pushd_imm32, pwszBuildFlavor.ToInt32())); instructions.Add(Instruction.Create(Code.Pushd_imm32, pwszVersion.ToInt32())); instructions.Add(Instruction.Create(Code.Mov_r32_imm32, Register.EAX, fnAddr.ToInt32())); instructions.Add(Instruction.Create(Code.Call_rm32, Register.EAX)); // call ICLRRuntimeHost::Start instructions.Add(Instruction.Create(Code.Mov_r32_rm32, Register.EAX, new MemoryOperand(Register.None, ppv.ToInt32()))); instructions.Add(Instruction.Create(Code.Mov_r32_rm32, Register.ECX, new MemoryOperand(Register.EAX))); instructions.Add(Instruction.Create(Code.Mov_r32_rm32, Register.EDX, new MemoryOperand(Register.ECX, 0x0C))); instructions.Add(Instruction.Create(Code.Push_r32, Register.EAX)); instructions.Add(Instruction.Create(Code.Call_rm32, Register.EDX)); // call ICLRRuntimeHost::ExecuteInDefaultAppDomain instructions.Add(Instruction.Create(Code.Pushd_imm32, pReturnValue.ToInt32())); instructions.Add(Instruction.Create(Code.Pushd_imm32, pwzArgument.ToInt32())); instructions.Add(Instruction.Create(Code.Pushd_imm32, pwzMethodName.ToInt32())); instructions.Add(Instruction.Create(Code.Pushd_imm32, pwzTypeName.ToInt32())); instructions.Add(Instruction.Create(Code.Pushd_imm32, pwzAssemblyPath.ToInt32())); instructions.Add(Instruction.Create(Code.Mov_r32_rm32, Register.EAX, new MemoryOperand(Register.None, ppv.ToInt32()))); instructions.Add(Instruction.Create(Code.Mov_r32_rm32, Register.ECX, new MemoryOperand(Register.EAX))); instructions.Add(Instruction.Create(Code.Push_r32, Register.EAX)); instructions.Add(Instruction.Create(Code.Mov_r32_rm32, Register.EAX, new MemoryOperand(Register.ECX, 0x2C))); instructions.Add(Instruction.Create(Code.Call_rm32, Register.EAX)); instructions.Add(Instruction.Create(Code.Retnd)); } else { const int maxStackIndex = 3; const int stackSize = 0x20 + maxStackIndex * 8; // 0x20 bytes shadow space, because x64 MemoryOperand stackAccess(int i) => new MemoryOperand(Register.RSP, stackSize - (maxStackIndex - i) * 8); instructions.Add(Instruction.Create(Code.Sub_rm64_imm8, Register.RSP, stackSize)); // call CorBindtoRuntimeEx // calling convention: https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=vs-2019 instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RAX, ppv.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_rm64_r64, stackAccess(1), Register.RAX)); instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RAX, riid.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_rm64_r64, stackAccess(0), Register.RAX)); instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.R9, rcslid.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_r32_imm32, Register.R8D, 0)); // startupFlags instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RDX, pwszBuildFlavor.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RCX, pwszVersion.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RAX, fnAddr.ToInt64())); instructions.Add(Instruction.Create(Code.Call_rm64, Register.RAX)); // call pClrHost->Start(); instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RCX, ppv.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_r64_rm64, Register.RCX, new MemoryOperand(Register.RCX))); instructions.Add(Instruction.Create(Code.Mov_r64_rm64, Register.RAX, new MemoryOperand(Register.RCX))); instructions.Add(Instruction.Create(Code.Mov_r64_rm64, Register.RDX, new MemoryOperand(Register.RAX, 0x18))); instructions.Add(Instruction.Create(Code.Call_rm64, Register.RDX)); // call pClrHost->ExecuteInDefaultAppDomain() instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RDX, pReturnValue.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_rm64_r64, stackAccess(1), Register.RDX)); instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RDX, pwzArgument.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_rm64_r64, stackAccess(0), Register.RDX)); instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.R9, pwzMethodName.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.R8, pwzTypeName.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RDX, pwzAssemblyPath.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RCX, ppv.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_r64_rm64, Register.RCX, new MemoryOperand(Register.RCX))); instructions.Add(Instruction.Create(Code.Mov_r64_rm64, Register.RAX, new MemoryOperand(Register.RCX))); instructions.Add(Instruction.Create(Code.Mov_r64_rm64, Register.RAX, new MemoryOperand(Register.RAX, 0x58))); instructions.Add(Instruction.Create(Code.Call_rm64, Register.RAX)); instructions.Add(Instruction.Create(Code.Add_rm64_imm8, Register.RSP, stackSize)); instructions.Add(Instruction.Create(Code.Retnq)); } var cw = new CodeWriterImpl(); var ib = new InstructionBlock(cw, instructions, 0); bool success = BlockEncoder.TryEncode(x86 ? 32 : 64, ib, out string errMsg); if (!success) { throw new Exception("Error during Iced encode: " + errMsg); } byte[] bytes = cw.ToArray(); var ptrStub = alloc(bytes.Length, 0x40); // RWX writeBytes(ptrStub, bytes); return(ptrStub); IntPtr alloc(int size, int protection = 0x04) => Native.VirtualAllocEx(hProc, IntPtr.Zero, (uint)size, 0x1000, protection); void writeBytes(IntPtr address, byte[] b) => Native.WriteProcessMemory(hProc, address, b, (uint)b.Length, out _); void writeString(IntPtr address, string str) => writeBytes(address, new UnicodeEncoding().GetBytes(str)); IntPtr allocString(string?str) { if (str is null) { return(IntPtr.Zero); } IntPtr pString = alloc(str.Length * 2 + 2); writeString(pString, str); return(pString); } IntPtr allocBytes(byte[] buffer) { IntPtr pBuffer = alloc(buffer.Length); writeBytes(pBuffer, buffer); return(pBuffer); } }
private VisualInstructionUserControl InsertConditionInstructionAtLeft(bool after, VisualInstructionUserControl visualInstruction, InstructionList instructions) { int index = VerifyPositionToInsert(after, visualInstruction, this.visualInstructions); foreach (Instruction instruction in instructions) { line.Instructions.Insert(index, instruction); InsertVisualInstructionAt(index, this.visualInstructions, instruction); index++; } return(this.visualInstructions[index - 1]); }
public void HighlightNoCall(InstructionList keyframe) { UpdateLists(); mInstructionSetListBox.HighlightObjectNoCall(keyframe, false); }
private static void AddSetToSave(InstructionSet instructionSet, InstructionSetSaveList instructionSetSaveList, string targetName) { // This following members be used as a buffer for holding the lists that will be saved. // In the following loop the code will only copy over instructions that set properties // which are included in EditorData.SavedMembers List<InstructionList> temporaryListList = new List<InstructionList>(); InstructionList temporaryList = new InstructionList(); InstructionSetSave instructionSetSave = new InstructionSetSave(); foreach (KeyframeList keyframeList in instructionSet) { temporaryListList = new List<InstructionList>(); foreach (InstructionList instructionList in keyframeList) { temporaryList = new InstructionList(); temporaryList.Name = instructionList.Name; foreach (Instruction instruction in instructionList) { // Assume that all instructions are GenericInstructions GenericInstruction asGenericInstruction = instruction as GenericInstruction; bool toAdd = false; if (asGenericInstruction.Target is PositionedModel) { toAdd = EditorData.CurrentPositionedModelMembersWatching.Contains(asGenericInstruction.Member); } else if (asGenericInstruction.Target is Sprite) { toAdd = EditorData.CurrentSpriteMembersWatching.Contains(asGenericInstruction.Member); } else if (asGenericInstruction.Target is SpriteFrame) { toAdd = EditorData.CurrentSpriteFrameMembersWatching.Contains(asGenericInstruction.Member); } else if (asGenericInstruction.Target is Text) { toAdd = EditorData.CurrentTextMembersWatching.Contains(asGenericInstruction.Member); } if (toAdd) { // this instruction is one we want to save temporaryList.Add(instruction); } } if (temporaryList.Count != 0) { temporaryListList.Add(temporaryList); } } if (temporaryListList.Count != 0) { instructionSetSave.AddInstructions(temporaryListList, keyframeList.Name); } } if (instructionSetSave.Instructions.Count != 0) { instructionSetSave.Target = targetName; instructionSetSaveList.InstructionSetSaves.Add(instructionSetSave); } }
public DebugView(InstructionList list) { _list = list; }
private void Disassemble(ITextOutput output, ReadyToRunReader reader, ReadyToRunMethod readyToRunMethod, RuntimeFunction runtimeFunction, int bitness, ulong address) { WriteCommentLine(output, readyToRunMethod.SignatureString); byte[] codeBytes = new byte[runtimeFunction.Size]; for (int i = 0; i < runtimeFunction.Size; i++) { codeBytes[i] = reader.Image[reader.GetOffset(runtimeFunction.StartAddress) + i]; } // TODO: Decorate the disassembly with Unwind, GC and debug info var codeReader = new ByteArrayCodeReader(codeBytes); var decoder = Decoder.Create(bitness, codeReader); decoder.IP = address; ulong endRip = decoder.IP + (uint)codeBytes.Length; var instructions = new InstructionList(); while (decoder.IP < endRip) { decoder.Decode(out instructions.AllocUninitializedElement()); } string disassemblyFormat = ReadyToRunOptions.GetDisassemblyFormat(null); Formatter formatter = null; if (disassemblyFormat.Equals(ReadyToRunOptions.intel)) { formatter = new NasmFormatter(); } else { Debug.Assert(disassemblyFormat.Equals(ReadyToRunOptions.gas)); formatter = new GasFormatter(); } formatter.Options.DigitSeparator = "`"; formatter.Options.FirstOperandCharIndex = 10; var tempOutput = new StringOutput(); foreach (var instr in instructions) { int byteBaseIndex = (int)(instr.IP - address); foreach (var bound in runtimeFunction.DebugInfo.BoundsList) { if (bound.NativeOffset == byteBaseIndex) { if (bound.ILOffset == (uint)DebugInfoBoundsType.Prolog) { WriteCommentLine(output, "Prolog"); } else if (bound.ILOffset == (uint)DebugInfoBoundsType.Epilog) { WriteCommentLine(output, "Epilog"); } else { WriteCommentLine(output, $"IL_{bound.ILOffset:x4}"); } } } formatter.Format(instr, tempOutput); output.Write(instr.IP.ToString("X16")); output.Write(" "); int instrLen = instr.Length; for (int i = 0; i < instrLen; i++) { output.Write(codeBytes[byteBaseIndex + i].ToString("X2")); } int missingBytes = 10 - instrLen; for (int i = 0; i < missingBytes; i++) { output.Write(" "); } output.Write(" "); output.WriteLine(tempOutput.ToStringAndReset()); } output.WriteLine(); }
public static void AddInstructionsToList(InstructionList instructionList, double timeToExecute, List<string> membersToIgnore) { if (GuiData.TimeLineWindow.InstructionMode == InstructionMode.All) { #region Loop through all Sprites and create instructions for them foreach (Sprite sprite in BlockingScene.Sprites) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, sprite); } #endregion #region Loop through all SpriteFrames and create instructions for them foreach (SpriteFrame spriteFrame in BlockingScene.SpriteFrames) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, spriteFrame); } #endregion #region Loop through all PositionedModels and create Instructions for them foreach (PositionedModel positionedModel in mBlockingScene.PositionedModels) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, positionedModel); } #endregion #region Loop through all Texts and create Instructions for them foreach (Text text in BlockingScene.Texts) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, text); } #endregion } else if (GuiData.TimeLineWindow.InstructionMode == InstructionMode.Current) { if (EditorData.EditorLogic.CurrentSprites.Count != 0) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, EditorData.EditorLogic.CurrentSprites[0]); } else if (EditorData.EditorLogic.CurrentSpriteFrames.Count != 0) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, EditorData.EditorLogic.CurrentSpriteFrames[0]); } else if (EditorData.EditorLogic.CurrentPositionedModels.Count != 0) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, EditorData.EditorLogic.CurrentPositionedModels[0]); } else if (EditorData.EditorLogic.CurrentTexts.Count != 0) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, EditorData.EditorLogic.CurrentTexts[0]); } } }
public InstructionSet ToInstructionSet(IInstructable instructable) { InstructionSet instructionSet = new InstructionSet(); instructionSet.Name = this.Target; //INameable nameable = null; foreach (KeyframeListSave keyframeList in Instructions) { KeyframeList keyframes = new KeyframeList(); keyframes.Name = keyframeList.Name; instructionSet.Add(keyframes); foreach (KeyframeSave keyframe in keyframeList.SceneKeyframes) { InstructionList list = new InstructionList(); list.Name = keyframe.Name; keyframes.Add(list); foreach (InstructionSave instructionSave in keyframe.InstructionSaves) { list.Add(instructionSave.ToInstruction(instructable)); } } } return instructionSet; }
/// <summary> /// Default ctor /// </summary> private BasicBlock(InstructionList instructions, Instruction entry, Instruction exit) { this.instructions = instructions; this.entry = entry; this.exit = exit; }
internal void Box(ParameterExpression variable, InstructionList instructions) { var scope = _variables[variable]; LocalVariable local = scope.Variable; Debug.Assert(!local.IsBoxed && !local.InClosure); _variables[variable].Variable.IsBoxed = true; int curChild = 0; for (int i = scope.Start; i < scope.Stop && i < instructions.Count; i++) { if (scope.ChildScopes != null && scope.ChildScopes[curChild].Start == i) { // skip boxing in the child scope var child = scope.ChildScopes[curChild]; i = child.Stop; curChild++; continue; } instructions.SwitchToBoxed(local.Index, i); } }
private static void CreateCompareArrayInstructions(InstructionList ins, MethodBody body, Register rthis, Register rother, FieldDefinition field, Register rThisValue, Register rOtherValue, Instruction returnFalseInstruction) { Instruction done = new Instruction(RCode.Nop); // Load the instance fields. ins.Add(new Instruction(RCode.Iget_object, rThisValue, rthis) {Operand = field}); ins.Add(new Instruction(RCode.Iget_object, rOtherValue, rother) {Operand = field}); var rThisLen = body.AllocateRegister(RCategory.Temp, RType.Value); var rOtherLen = body.AllocateRegister(RCategory.Temp, RType.Value); // load length ins.Add(new Instruction(RCode.Array_length, rThisLen, rThisValue)); ins.Add(new Instruction(RCode.Array_length, rOtherLen, rOtherValue)); // Compare the length ins.Add(new Instruction(RCode.If_ne, returnFalseInstruction, new[] { rThisLen, rOtherLen })); ins.Add(new Instruction(RCode.If_eqz, done, new[] {rThisLen})); // now iterate over all elements in the array. var thisType = body.AllocateRegister(RCategory.Temp, RType.Object); var otherType = body.AllocateRegister(RCategory.Temp, RType.Object); var counter = body.AllocateRegister(RCategory.Temp, RType.Object); ins.Add(new Instruction(RCode.Const, 0, new[] {counter})); var loadThisVal = new Instruction(RCode.Aget_object, thisType, rThisValue, counter); ins.Add(loadThisVal); ins.Add(new Instruction(RCode.Aget_object, otherType, rOtherValue, counter)); // compare types. ins.Add(new Instruction(RCode.If_ne, returnFalseInstruction, new[] {thisType, otherType})); ins.Add(new Instruction(RCode.Add_int_lit8, 1, new[] {counter, counter})); ins.Add(new Instruction(RCode.If_ne, loadThisVal, new[] {counter, rThisLen})); ins.Add(done); }
private static void CreateCodeSegment(InstructionList instructionList, ushort segmentOrdinal = 1) { mbbsEmuMemoryCore.AddSegment(segmentOrdinal, instructionList); }
public Formation() { ia = new InstructionList(); fa = new FormationArray(); }
public InstructionSet ToInstructionSet(FlatRedBall.Scene scene) { InstructionSet instructionSet = new InstructionSet(); instructionSet.Name = this.Target; INameable nameable = null; foreach (KeyframeListSave keyframeList in Instructions) { KeyframeList keyframes = new KeyframeList(); keyframes.Name = keyframeList.Name; instructionSet.Add(keyframes); foreach (KeyframeSave keyframe in keyframeList.SceneKeyframes) { InstructionList list = new InstructionList(); list.Name = keyframe.Name; keyframes.Add(list); foreach (InstructionSave instructionSave in keyframe.InstructionSaves) { if (nameable == null || nameable.Name != instructionSave.TargetName) { // We don't have a nameable yet, or the current instruction is // not modifying the one referenced by nameable. nameable = scene.Sprites.FindByName(instructionSave.TargetName); if (nameable == null) { nameable = scene.SpriteFrames.FindByName(instructionSave.TargetName); } } if (nameable == null) { throw new NullReferenceException("Could not find an object of instance " + instructionSave.Type + " with the name " + instructionSave.TargetName); } list.Add(instructionSave.ToInstruction(nameable)); } } } return instructionSet; }
internal void FixupBranch(InstructionList instructions, int branchIndex) { instructions.FixupBranch(branchIndex, this._targetIndex - branchIndex); }
private Instruction AddInstruction(OpCode opCode, int offset, object value) { Instruction instruction = new Instruction(opCode, offset, value); InstructionList instructions = (InstructionList)this.ehMap[offset + 1]; if(instructions == null) this.ehMap[offset + 1] = instructions = new InstructionList(); instructions.Add(instruction); if(this.method.contextForOffset != null) { object sctx = this.method.contextForOffset[offset + 1]; if(sctx != null) instruction.SourceContext = (SourceContext)sctx; } return instruction; }
internal static void ReadSwitches <TValue>(InstructionList instr, Action <byte, TValue, bool> setHandler, Action <byte, TValue, bool> defaultHandler) { bool first = true; int ix = 0, count = instr.Count, ix2, offset = 0; while (ix < count) { var i1 = instr[ix++]; if (i1.ILCode == ILCode.Ret) { break; } if (i1 is SwitchInstruction) { //Get offset var oi = instr[ix - 2]; if (oi.ILCode == ILCode.Sub) { oi = instr[ix - 3]; { offset = (int)oi.RawOperand; } } //Read string values from switch statement var switchJumps = ((SwitchInstruction)i1).JumpToInstructions; var jCount = switchJumps.Count; ix2 = 0; while (ix2 < jCount) { ParseOperand <TValue>((byte)(ix2 + offset), instr, switchJumps[ix2++], setHandler); } } else if (i1 is LabelInstruction) { bool useDefault = true; if (i1.ILCode == ILCode.Beq || i1.ILCode == ILCode.Beq_S) { var def = instr[ix - 2]; var opnd = def.RawOperand; if (opnd != null) { ix2 = Convert.ToInt32(opnd); useDefault = false; } else { ix2 = offset - 1; } } else { ix2 = offset - 1; ix = count; } if (useDefault) { ParseOperand <TValue>((byte)ix2, instr, ((LabelInstruction)i1).JumpToInstruction, defaultHandler); } else { ParseOperand <TValue>((byte)ix2, instr, ((LabelInstruction)i1).JumpToInstruction, setHandler); } } } }
internal InstructionList ParseInstructions() { this.ParseHeader(); if(this.size == 0) return new InstructionList(); InstructionList result = new InstructionList(); result.Add(new Instruction(OpCode._Locals, 0, this.locals)); while(this.counter <= size) { InstructionList instructions = (InstructionList)this.ehMap[this.counter + 1]; if(instructions != null) { for(int i = 0; i < instructions.Count; i++) result.Add(instructions[i]); } if(this.counter < size) result.Add(this.ParseInstruction()); else break; } return result; }
public YukaScript(string name, InstructionList instructions) { Name = name; InstructionList = instructions; }
private void DisassembleAndWriteSimpleMethod(JitWriteContext context, MethodBase method) { var handle = method.MethodHandle; RuntimeHelpers.PrepareMethod(handle); var clrMethod = context.Runtime.GetMethodByHandle((ulong)handle.Value.ToInt64()); var regions = FindNonEmptyHotColdInfo(clrMethod); if (clrMethod == null || regions == null) { context.Runtime.Flush(); clrMethod = context.Runtime.GetMethodByHandle((ulong)handle.Value.ToInt64()); regions = FindNonEmptyHotColdInfo(clrMethod); } if (clrMethod == null || regions == null) { var address = (ulong)handle.GetFunctionPointer().ToInt64(); clrMethod = context.Runtime.GetMethodByAddress(address); regions = FindNonEmptyHotColdInfo(clrMethod); } var writer = context.Writer; if (clrMethod != null) { writer.WriteLine(); writer.WriteLine(clrMethod.GetFullSignature()); } else { WriteSignatureFromReflection(context, method); } if (regions == null) { if (method.IsGenericMethod || (method.DeclaringType?.IsGenericType ?? false)) { writer.WriteLine(" ; Failed to find HotColdInfo for generic method (reference types?)."); return; } writer.WriteLine(" ; Failed to find HotColdRegions."); return; } var methodAddress = regions.HotStart; var methodLength = regions.HotSize; var reader = new MemoryCodeReader(new IntPtr(unchecked ((long)methodAddress)), methodLength); var decoder = Decoder.Create(MapArchitectureToBitness(context.Runtime.DataTarget.Architecture), reader); var instructions = new InstructionList(); decoder.IP = methodAddress; while (decoder.IP < (methodAddress + methodLength)) { decoder.Decode(out instructions.AllocUninitializedElement()); } var resolver = new JitAsmSymbolResolver(context.Runtime, methodAddress, methodLength); var formatter = new IntelFormatter(FormatterOptions, resolver); var output = new StringOutput(); foreach (ref var instruction in instructions) { formatter.Format(instruction, output); writer.Write(" L"); writer.Write((instruction.IP - methodAddress).ToString("x4")); writer.Write(": "); writer.WriteLine(output.ToStringAndReset()); } }
public Element (ElementType type, object val, InstructionList children) { this.type = type; this.val = val; this.children = children; }
/// <summary> /// Reads assembly from <see cref="functionPtr" /> (at least <see cref="minimumTrampolineLength" /> bytes), and writes /// it to <see cref="trampolinePtr" /> plus a jmp to continue execution. /// </summary> /// <param name="instructionBuffer">The buffer to copy assembly from.</param> /// <param name="functionPtr">The pointer to the function to copy assembly from.</param> /// <param name="trampolinePtr">The pointer to write the trampoline assembly to.</param> /// <param name="arch">The architecture of the current platform.</param> /// <param name="minimumTrampolineLength">Copies at least this many bytes of assembly from <see cref="functionPtr" />.</param> /// <param name="trampolineLength">Returns the total length of the trampoline, in bytes.</param> /// <param name="jmpLength">Returns the length of the jmp at the end of the trampoline, in bytes.</param> public static void CreateTrampolineFromFunction(byte[] instructionBuffer, IntPtr functionPtr, IntPtr trampolinePtr, int minimumTrampolineLength, Architecture arch, out int trampolineLength, out int jmpLength) { // Decode original function up until we go past the needed bytes to write the jump to patchedFunctionPtr var codeReader = new ByteArrayCodeReader(instructionBuffer); var decoder = Decoder.Create(arch == Architecture.X64 ? 64 : 32, codeReader); decoder.IP = (ulong)functionPtr.ToInt64(); uint totalBytes = 0; var origInstructions = new InstructionList(); var readOverflowArea = false; while (codeReader.CanReadByte) { decoder.Decode(out var instr); origInstructions.Add(instr); totalBytes += (uint)instr.Length; if (instr.Code == Code.INVALID) { throw new Exception("Found garbage"); } if (totalBytes >= minimumTrampolineLength) { break; } if (readOverflowArea) { if (instr.Mnemonic != Mnemonic.Int3 && instr.Mnemonic != Mnemonic.Nop) { throw new Exception("Function is too short to hook"); } continue; } switch (instr.FlowControl) { case FlowControl.Next: break; // Interrupts are usually used for aligning case FlowControl.Interrupt: // eg. int n break; // Handled by BlockEncoder in most cases case FlowControl.UnconditionalBranch: case FlowControl.IndirectBranch: // eg. jmp reg/mem case FlowControl.ConditionalBranch: // eg. je, jno, etc break; case FlowControl.Return: // eg. ret // There is a possibility of an overflow area, attempt to allocate trampoline onto it readOverflowArea = true; break; case FlowControl.Call: // eg. call method case FlowControl.IndirectCall: // eg. call reg/mem case FlowControl.XbeginXabortXend: case FlowControl.Exception: // eg. ud0 default: throw new Exception("Not supported yet - " + instr.FlowControl); } } if (totalBytes < minimumTrampolineLength) { throw new Exception("Not enough bytes!"); } if (origInstructions.Count == 0) { throw new Exception("Not enough instructions!"); } ref readonly var lastInstr = ref origInstructions[origInstructions.Count - 1];
public VisualInstructionUserControl InsertInstructionAtLocalToBeDefined(bool after, VisualInstructionUserControl visualInstruction, InstructionList instructions) { instructions.ValidateOperands(); if (!instructions.Contains(OperationCode.OutputCoil) && !instructions.Contains(OperationCode.Timer) && !instructions.Contains(OperationCode.Counter)) { return(InsertConditionInstructionAtLeft(after, visualInstruction, instructions)); } else { return(InsertOutputInstructionAtRight(after, visualInstruction, instructions)); } }
public virtual void UndefineTemps(InstructionList instructions, LocalVariables locals) { // Empty }
private VisualInstructionUserControl InsertOutputInstructionAtRight(bool after, VisualInstructionUserControl visualInstruction, InstructionList instructions) { int index = 0; int autToRetornInsertedInstruction = 0; switch (visualOutputInstructions.Count) { case 0: index = 0; if (instructions.Count > 1) { instructions.InsertParallelBranch(InstructionList.ParallelBranchInsertionType.ParallelBranchCompleted); autToRetornInsertedInstruction = -1; } break; case 1: index = VerifyPositionToInsert(after, visualInstruction, this.visualOutputInstructions); if (index == 0) { instructions.InsertParallelBranch(InstructionList.ParallelBranchInsertionType.ParallelBranchInitialized); line.Outputs.Insert(0, InstructionFactory.createInstruction(OperationCode.ParallelBranchNext)); InsertVisualInstructionAt(0, this.visualOutputInstructions, InstructionFactory.createInstruction(OperationCode.ParallelBranchNext)); line.Outputs.Insert(this.visualOutputInstructions.Count, InstructionFactory.createInstruction(OperationCode.ParallelBranchEnd)); InsertVisualInstructionAt(this.visualOutputInstructions.Count, this.visualOutputInstructions, InstructionFactory.createInstruction(OperationCode.ParallelBranchEnd)); } else { instructions.InsertParallelBranch(InstructionList.ParallelBranchInsertionType.ParallelBranchFinalized); autToRetornInsertedInstruction = -1; line.Outputs.Insert(0, InstructionFactory.createInstruction(OperationCode.ParallelBranchBegin)); InsertVisualInstructionAt(0, this.visualOutputInstructions, InstructionFactory.createInstruction(OperationCode.ParallelBranchBegin)); index++; } break; default: index = VerifyPositionToInsert(false, visualInstruction, this.visualOutputInstructions); switch (this.visualOutputInstructions[index].OpCode) { case OperationCode.ParallelBranchBegin: instructions.InsertParallelBranch(InstructionList.ParallelBranchInsertionType.ParallelBranchInitialized); line.Outputs[0].OpCode = OperationCode.ParallelBranchNext; this.visualOutputInstructions[0].OpCode = OperationCode.ParallelBranchNext; break; case OperationCode.ParallelBranchNext: instructions.InsertParallelBranchNext(); break; case OperationCode.ParallelBranchEnd: instructions.InsertParallelBranchNext(); break; default: instructions.InsertParallelBranchNext(); index++; break; } break; } foreach (Instruction instruction in instructions) { line.Outputs.Insert(index, instruction); InsertVisualInstructionAt(index, this.visualOutputInstructions, instruction); index++; } return(this.visualOutputInstructions[index - 1 + autToRetornInsertedInstruction]); }
public override void UndefineTemps(InstructionList instructions, LocalVariables locals) { locals.UndefineLocal(_array, instructions.Count); locals.UndefineLocal(_index, instructions.Count); }
protected void CreateCodeSegment(InstructionList instructionList, ushort segmentOrdinal = 1) { mbbsEmuProtectedModeMemoryCore.AddSegment(segmentOrdinal, instructionList); }
private Robot(int maximumDataOffset, int ignoreColumns) { mainFunction = InstructionList.createInstructionList(); this.maximumDataOffset = maximumDataOffset; this.ignoreColumns = ignoreColumns; }
private static void AddSetToSave(InstructionSet instructionSet, InstructionSetSaveList instructionSetSaveList, string targetName) { // This following members be used as a buffer for holding the lists that will be saved. // In the following loop the code will only copy over instructions that set properties // which are included in EditorData.SavedMembers List <InstructionList> temporaryListList = new List <InstructionList>(); InstructionList temporaryList = new InstructionList(); InstructionSetSave instructionSetSave = new InstructionSetSave(); foreach (KeyframeList keyframeList in instructionSet) { temporaryListList = new List <InstructionList>(); foreach (InstructionList instructionList in keyframeList) { temporaryList = new InstructionList(); temporaryList.Name = instructionList.Name; foreach (Instruction instruction in instructionList) { // Assume that all instructions are GenericInstructions GenericInstruction asGenericInstruction = instruction as GenericInstruction; bool toAdd = false; if (asGenericInstruction.Target is PositionedModel) { toAdd = EditorData.CurrentPositionedModelMembersWatching.Contains(asGenericInstruction.Member); } else if (asGenericInstruction.Target is Sprite) { toAdd = EditorData.CurrentSpriteMembersWatching.Contains(asGenericInstruction.Member); } else if (asGenericInstruction.Target is SpriteFrame) { toAdd = EditorData.CurrentSpriteFrameMembersWatching.Contains(asGenericInstruction.Member); } else if (asGenericInstruction.Target is Text) { toAdd = EditorData.CurrentTextMembersWatching.Contains(asGenericInstruction.Member); } if (toAdd) { // this instruction is one we want to save temporaryList.Add(instruction); } } if (temporaryList.Count != 0) { temporaryListList.Add(temporaryList); } } if (temporaryListList.Count != 0) { instructionSetSave.AddInstructions(temporaryListList, keyframeList.Name); } } if (instructionSetSave.Instructions.Count != 0) { instructionSetSave.Target = targetName; instructionSetSaveList.InstructionSetSaves.Add(instructionSetSave); } }
public static void AddInstructionsToList(InstructionList instructionList, double timeToExecute) { AddInstructionsToList(instructionList, timeToExecute, mEmptyList); }
public void Play(double timeToStartAt, bool cycle) { // There are 3 categories of TimedKeyframeLists: // 1: Ones that begin and end before timeToStartAt // 2: Ones that begin before timeToStartAt but end after - in other words // timeToStartAt is in the middle of these TimedKeyframeLists // 3: Ones that have not started yet. // Category 1: List <TimedKeyframeList> keyframesBefore = new List <TimedKeyframeList>(); // Category 2: List <TimedKeyframeList> keyframesDuring = new List <TimedKeyframeList>(); // Category 3: List <TimedKeyframeList> keyframesAfter = new List <TimedKeyframeList>(); #region Sort all timed keyframes in the lists foreach (TimedKeyframeList timedKeyframeList in this) { if (timedKeyframeList.TimeToExecute < timeToStartAt) { if (timedKeyframeList.TimeToExecute + timedKeyframeList.Length < timeToStartAt) { keyframesBefore.Add(timedKeyframeList); } else { keyframesDuring.Add(timedKeyframeList); } } else { keyframesAfter.Add(timedKeyframeList); } } #endregion InstructionList instructionsToExecute = new InstructionList(); #region Add the keyframes before TimedKeyframeList.SortEndTimeAscending(keyframesBefore); foreach (TimedKeyframeList keyframeList in keyframesBefore) { // TODO } #endregion foreach (TimedKeyframeList keyframeList in keyframesAfter) { InstructionList instructionsToAdd = keyframeList.KeyframeList.CreateVelocityListAtTime(timeToStartAt); instructionsToAdd.ShiftTime(keyframeList.TimeToExecute); instructionsToExecute.AddRange(instructionsToAdd); } #region If cycle == true if (cycle == true) { foreach (Instruction instruction in instructionsToExecute) { instruction.CycleTime = this.Length; } } #endregion instructionsToExecute.ShiftTime(TimeManager.CurrentTime); instructionsToExecute.ExecuteAndRemoveOrCyclePassedInstructions( timeToStartAt + TimeManager.CurrentTime); InstructionManager.Instructions.AddRange(instructionsToExecute); }
public static void AddInstructionsToList(InstructionList instructionList, double timeToExecute, List <string> membersToIgnore) { if (GuiData.TimeLineWindow.InstructionMode == InstructionMode.All) { #region Loop through all Sprites and create instructions for them foreach (Sprite sprite in BlockingScene.Sprites) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, sprite); } #endregion #region Loop through all SpriteFrames and create instructions for them foreach (SpriteFrame spriteFrame in BlockingScene.SpriteFrames) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, spriteFrame); } #endregion #region Loop through all PositionedModels and create Instructions for them foreach (PositionedModel positionedModel in mBlockingScene.PositionedModels) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, positionedModel); } #endregion #region Loop through all Texts and create Instructions for them foreach (Text text in BlockingScene.Texts) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, text); } #endregion } else if (GuiData.TimeLineWindow.InstructionMode == InstructionMode.Current) { if (EditorData.EditorLogic.CurrentSprites.Count != 0) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, EditorData.EditorLogic.CurrentSprites[0]); } else if (EditorData.EditorLogic.CurrentSpriteFrames.Count != 0) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, EditorData.EditorLogic.CurrentSpriteFrames[0]); } else if (EditorData.EditorLogic.CurrentPositionedModels.Count != 0) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, EditorData.EditorLogic.CurrentPositionedModels[0]); } else if (EditorData.EditorLogic.CurrentTexts.Count != 0) { InstructionRecorder.RecordInstructions(instructionList, timeToExecute, membersToIgnore, EditorData.EditorLogic.CurrentTexts[0]); } } }
public static void AddInstructionsToList(InstructionList instructionList, double timeToExecute) { AddInstructionsToList(instructionList, timeToExecute, mEmptyList); }
/// <summary> /// Exports the code that can be executed instead of the global instruction set /// </summary> /// <returns>The string containing the source code.</returns> #endregion public static string GetStringForInstructions() { StringBuilder stringBuilder = new StringBuilder(); InstructionList temporaryInstructionList = new InstructionList(); #region Create an array of doubles for times //stringBuilder.AppendLine("static double[][] KeyframeTimes = new double[][]{"); //foreach (InstructionSet instructionSet in EditorData.GlobalInstructionSets) //{ // for (int keyframeListIndex = 0; keyframeListIndex < instructionSet.Count; keyframeListIndex++) // { // KeyframeList keyframeList = mGlobalInstructionSet[keyframeListIndex]; // stringBuilder.AppendLine("\tnew double[]{"); // for (int i = 0; i < keyframeList.Count; i++) // { // if (i == keyframeList.Count - 1) // { // stringBuilder.AppendLine("\t\t" + keyframeList[i][0].TimeToExecute); // } // else // { // stringBuilder.AppendLine("\t\t" + keyframeList[i][0].TimeToExecute + ","); // } // } // if (keyframeListIndex == mGlobalInstructionSet.Count - 1) // { // stringBuilder.AppendLine("\t}"); // } // else // { // stringBuilder.AppendLine("\t},"); // } // } //} #endregion stringBuilder.AppendLine("};"); stringBuilder.AppendLine(); stringBuilder.AppendLine(); stringBuilder.AppendLine(); stringBuilder.AppendLine("public void SetCurrentFrame()"); stringBuilder.AppendLine("{"); stringBuilder.AppendLine("\tswitch( mCurrentAnimation )"); stringBuilder.AppendLine("\t{"); //for(int keyframeIndex = 0; keyframeIndex < mGlobalInstructionSet.Count; keyframeIndex++) //{ // KeyframeList keyframeList = mGlobalInstructionSet[keyframeIndex]; // stringBuilder.AppendLine("\t\tcase " + keyframeIndex + ":"); // stringBuilder.AppendLine("\t\tswitch( mCurrentKeyframe )"); // stringBuilder.AppendLine("\t\t{"); // for(int i= 0; i < keyframeList.Count; i++) // { // temporaryInstructionList.Clear(); // temporaryInstructionList.AddRange( keyframeList[i] ); // temporaryInstructionList.AddRange( mGlobalInstructionSet[keyframeIndex].CreateVelocityListAtIndex(i) ); // stringBuilder.AppendLine("\t\t\tcase " + i + ":"); // foreach (GenericInstruction instruction in temporaryInstructionList) // { // #region Get the name of the object and stuff it in objectName // string objectName = "object"; // if(instruction.Target is Sprite) // { // int index = mBlockingScene.Sprites.IndexOf(instruction.Target as Sprite); // objectName = "mSprites[" + index + "]."; // } // if (instruction.Target is SpriteFrame) // { // int index = mBlockingScene.SpriteFrames.IndexOf(instruction.Target as SpriteFrame); // objectName = "mSpriteFrames[" + index + "]."; // } // if (instruction.Target is Text) // { // int index = mBlockingScene.Texts.IndexOf(instruction.Target as Text); // objectName = "mTexts[" + index + "]."; // } // if (instruction.Target is PositionedModel) // { // int index = mBlockingScene.PositionedModels.IndexOf(instruction.Target as PositionedModel); // objectName = "mPositionedModels[" + index + "]."; // } // #endregion // string memberValueAsString = instruction.MemberValueAsString; // if (instruction.MemberValueAsObject is float) // { // memberValueAsString += "f"; // } // else if (instruction.MemberValueAsObject != null && instruction.MemberValueAsObject.GetType().IsEnum) // { // memberValueAsString = // instruction.MemberValueAsObject.GetType().FullName + "." + memberValueAsString; // } // stringBuilder.AppendLine("\t\t\t\t" + objectName + instruction.Member + " = " + // memberValueAsString + ";"); // } // stringBuilder.AppendLine("\t\t\t\tbreak;"); // } // stringBuilder.AppendLine("\t\t}"); // stringBuilder.AppendLine("\t\tbreak;"); //} stringBuilder.AppendLine("\t}"); stringBuilder.AppendLine("}"); return(stringBuilder.ToString()); }
private static void UpdateCurrentKeyframe(Window callingWindow) { if (EditorData.EditorLogic.CurrentKeyframe != null) { double timeToExecute = TimeLineWindow.CurrentValue; if (EditorData.EditorLogic.CurrentKeyframe.Count > 0) { timeToExecute = EditorData.EditorLogic.CurrentKeyframe[0].TimeToExecute; } InstructionList instructionList = new InstructionList(); EditorData.AddInstructionsToList(instructionList, timeToExecute); EditorData.EditorLogic.CurrentKeyframe.Clear(); EditorData.EditorLogic.CurrentKeyframe.AddRange(instructionList); } }
public VirtualMachine(InstructionList instructions) { Instructions = instructions ?? throw new ArgumentNullException("instructions"); Stack = new Stack(); InstructionIndex = 0; }
public void ExecuteBatch(ISQLDatabase database, InstructionList instructions) { using (ITransaction transaction = database.BeginTransaction()) { foreach (string instr in instructions) using (IDbCommand cmd = transaction.CreateCommand()) { cmd.CommandText = instr; cmd.ExecuteNonQuery(); } transaction.Commit(); } }
private void Gen(Instruction instr) { InstructionList.Add(instr); }
public static T ParseOperand <T>(byte id, InstructionList instr, InstructionBase i, Action <byte, T, bool> setHandler, bool condition = false) { object value = null; if (typeof(T) == typeof(string)) { string accum = ""; //string accum = (string)value; var ix3 = instr.IndexOf(i); while (true) { var i2 = instr[ix3++]; if (i2 is LabelInstruction) { var cond = instr[ix3 - 2]; if (cond is ParameterInstruction) { //We can only use bool here if (i2.ILCode == ILCode.Brfalse || i2.ILCode == ILCode.Brfalse_S) { condition = true; } else if (i2.ILCode != ILCode.Brtrue && i2.ILCode != ILCode.Brtrue_S) { throw new InvalidOperationException("Can't handle this condition properly!"); } ParseOperand(id, instr, ((LabelInstruction)i2).JumpToInstruction, setHandler, !condition); } } else if (i2.ILCode == ILCode.Ret) { break; } else if (instr[ix3].ILCode == ILCode.Newarr) { ix3++; continue; } else if (i2 is StringInstruction || instr[ix3].ILCode == ILCode.Box) { accum += i2.RawOperand; } } value = accum; } else if (typeof(T) == typeof(byte[])) { if (i.ILCode != ILCode.Ldnull) { var ix3 = instr.IndexOf(i) + 1; int length = (int)i.RawOperand; byte[] data = new byte[length]; value = data; while (true) { var i2 = instr[ix3++]; if (i2.ILCode == ILCode.Ldtoken) { System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(data, ((FieldInfo)((MemberInstruction)i2).Operand).FieldHandle); break; } else if (i2.ILCode == ILCode.Stelem_I1) { var ind = (int)instr[ix3 - 3].RawOperand; var val = Convert.ToByte(instr[ix3 - 2].RawOperand); data[ind] = val; } else if (i2.ILCode == ILCode.Ret) { break; } } } } else { value = i.RawOperand; } if (value != null && !(value is T)) { value = Convert.ChangeType(value, typeof(T)); } setHandler(id, (T)value, condition); return((T)value); }
void Default_ctor_creates_empty_list() { var list = new InstructionList(); Assert.Equal(0, list.Count); }
private void CreateCodeSegment(InstructionList instructionList, ushort segmentOrdinal = 0x1000) { protectedModeMemoryCore.AddSegment(segmentOrdinal, instructionList); }
public Formation() { ia = new InstructionList(); fa = new FormationArray(); }
public void Setup(InstructionList instructions) { Instructions = instructions; Reset(); }
/// <summary> /// Exports the code that can be executed instead of the global instruction set /// </summary> /// <returns>The string containing the source code.</returns> #endregion public static string GetStringForInstructions() { StringBuilder stringBuilder = new StringBuilder(); InstructionList temporaryInstructionList = new InstructionList(); #region Create an array of doubles for times //stringBuilder.AppendLine("static double[][] KeyframeTimes = new double[][]{"); //foreach (InstructionSet instructionSet in EditorData.GlobalInstructionSets) //{ // for (int keyframeListIndex = 0; keyframeListIndex < instructionSet.Count; keyframeListIndex++) // { // KeyframeList keyframeList = mGlobalInstructionSet[keyframeListIndex]; // stringBuilder.AppendLine("\tnew double[]{"); // for (int i = 0; i < keyframeList.Count; i++) // { // if (i == keyframeList.Count - 1) // { // stringBuilder.AppendLine("\t\t" + keyframeList[i][0].TimeToExecute); // } // else // { // stringBuilder.AppendLine("\t\t" + keyframeList[i][0].TimeToExecute + ","); // } // } // if (keyframeListIndex == mGlobalInstructionSet.Count - 1) // { // stringBuilder.AppendLine("\t}"); // } // else // { // stringBuilder.AppendLine("\t},"); // } // } //} #endregion stringBuilder.AppendLine("};"); stringBuilder.AppendLine(); stringBuilder.AppendLine(); stringBuilder.AppendLine(); stringBuilder.AppendLine("public void SetCurrentFrame()"); stringBuilder.AppendLine("{"); stringBuilder.AppendLine("\tswitch( mCurrentAnimation )"); stringBuilder.AppendLine("\t{"); //for(int keyframeIndex = 0; keyframeIndex < mGlobalInstructionSet.Count; keyframeIndex++) //{ // KeyframeList keyframeList = mGlobalInstructionSet[keyframeIndex]; // stringBuilder.AppendLine("\t\tcase " + keyframeIndex + ":"); // stringBuilder.AppendLine("\t\tswitch( mCurrentKeyframe )"); // stringBuilder.AppendLine("\t\t{"); // for(int i= 0; i < keyframeList.Count; i++) // { // temporaryInstructionList.Clear(); // temporaryInstructionList.AddRange( keyframeList[i] ); // temporaryInstructionList.AddRange( mGlobalInstructionSet[keyframeIndex].CreateVelocityListAtIndex(i) ); // stringBuilder.AppendLine("\t\t\tcase " + i + ":"); // foreach (GenericInstruction instruction in temporaryInstructionList) // { // #region Get the name of the object and stuff it in objectName // string objectName = "object"; // if(instruction.Target is Sprite) // { // int index = mBlockingScene.Sprites.IndexOf(instruction.Target as Sprite); // objectName = "mSprites[" + index + "]."; // } // if (instruction.Target is SpriteFrame) // { // int index = mBlockingScene.SpriteFrames.IndexOf(instruction.Target as SpriteFrame); // objectName = "mSpriteFrames[" + index + "]."; // } // if (instruction.Target is Text) // { // int index = mBlockingScene.Texts.IndexOf(instruction.Target as Text); // objectName = "mTexts[" + index + "]."; // } // if (instruction.Target is PositionedModel) // { // int index = mBlockingScene.PositionedModels.IndexOf(instruction.Target as PositionedModel); // objectName = "mPositionedModels[" + index + "]."; // } // #endregion // string memberValueAsString = instruction.MemberValueAsString; // if (instruction.MemberValueAsObject is float) // { // memberValueAsString += "f"; // } // else if (instruction.MemberValueAsObject != null && instruction.MemberValueAsObject.GetType().IsEnum) // { // memberValueAsString = // instruction.MemberValueAsObject.GetType().FullName + "." + memberValueAsString; // } // stringBuilder.AppendLine("\t\t\t\t" + objectName + instruction.Member + " = " + // memberValueAsString + ";"); // } // stringBuilder.AppendLine("\t\t\t\tbreak;"); // } // stringBuilder.AppendLine("\t\t}"); // stringBuilder.AppendLine("\t\tbreak;"); //} stringBuilder.AppendLine("\t}"); stringBuilder.AppendLine("}"); return stringBuilder.ToString(); }
public void ExecuteBatch(ITransaction transaction, InstructionList instructions, IDictionary <string, IList <string> > migrationPlaceholderTables = null) { throw new NotImplementedException(); }
private void Disassemble(PEFile currentFile, ITextOutput output, ReadyToRunReader reader, ReadyToRunMethod readyToRunMethod, RuntimeFunction runtimeFunction, int bitness, ulong address, bool showMetadataTokens, bool showMetadataTokensInBase10) { // TODO: Decorate the disassembly with GCInfo WriteCommentLine(output, readyToRunMethod.SignatureString); Dictionary <ulong, UnwindCode> unwindInfo = null; if (ReadyToRunOptions.GetIsShowUnwindInfo(null) && bitness == 64) { unwindInfo = WriteUnwindInfo(runtimeFunction, output); } bool isShowDebugInfo = ReadyToRunOptions.GetIsShowDebugInfo(null); Dictionary <VarLocType, HashSet <ValueTuple <DebugInfo, NativeVarInfo> > > debugInfo = null; if (isShowDebugInfo) { debugInfo = WriteDebugInfo(readyToRunMethod, output); } byte[] codeBytes = new byte[runtimeFunction.Size]; for (int i = 0; i < runtimeFunction.Size; i++) { codeBytes[i] = reader.Image[reader.GetOffset(runtimeFunction.StartAddress) + i]; } var codeReader = new ByteArrayCodeReader(codeBytes); var decoder = Decoder.Create(bitness, codeReader); decoder.IP = address; ulong endRip = decoder.IP + (uint)codeBytes.Length; var instructions = new InstructionList(); while (decoder.IP < endRip) { decoder.Decode(out instructions.AllocUninitializedElement()); } string disassemblyFormat = ReadyToRunOptions.GetDisassemblyFormat(null); Formatter formatter = null; if (disassemblyFormat.Equals(ReadyToRunOptions.intel)) { formatter = new NasmFormatter(); } else { Debug.Assert(disassemblyFormat.Equals(ReadyToRunOptions.gas)); formatter = new GasFormatter(); } formatter.Options.DigitSeparator = "`"; formatter.Options.FirstOperandCharIndex = 10; var tempOutput = new StringOutput(); ulong baseInstrIP = instructions[0].IP; foreach (var instr in instructions) { int byteBaseIndex = (int)(instr.IP - address); if (isShowDebugInfo && runtimeFunction.DebugInfo != null) { foreach (var bound in runtimeFunction.DebugInfo.BoundsList) { if (bound.NativeOffset == byteBaseIndex) { if (bound.ILOffset == (uint)DebugInfoBoundsType.Prolog) { WriteCommentLine(output, "Prolog"); } else if (bound.ILOffset == (uint)DebugInfoBoundsType.Epilog) { WriteCommentLine(output, "Epilog"); } else { WriteCommentLine(output, $"IL_{bound.ILOffset:x4}"); } } } } formatter.Format(instr, tempOutput); output.Write(instr.IP.ToString("X16")); output.Write(" "); int instrLen = instr.Length; for (int i = 0; i < instrLen; i++) { output.Write(codeBytes[byteBaseIndex + i].ToString("X2")); } int missingBytes = 10 - instrLen; for (int i = 0; i < missingBytes; i++) { output.Write(" "); } output.Write(" "); output.Write(tempOutput.ToStringAndReset()); DecorateUnwindInfo(output, unwindInfo, baseInstrIP, instr); DecorateDebugInfo(output, instr, debugInfo, baseInstrIP); DecorateCallSite(currentFile, output, reader, showMetadataTokens, showMetadataTokensInBase10, instr); } output.WriteLine(); }
public LadderProgram ReadExecutable(string content, string projectName) { if (content.IndexOf("@laddermic.com") == -1) { throw new Exception("Executable has no Ladder content!"); } OperationCode opCode = OperationCode.None; int countOfEnds = 0; int lineIndex = 0; Address address; AddressTypeEnum addressType; int index = 0; LadderProgram program = new LadderProgram(); program.Name = projectName; program.device = DeviceFactory.CreateNewDevice(); addressingServices.AlocateIOAddressing(program.device); addressingServices.AlocateAddressingMemoryAndTimerAndCounter(program, program.addressing.ListMemoryAddress, AddressTypeEnum.DigitalMemory, 10); addressingServices.AlocateAddressingMemoryAndTimerAndCounter(program, program.addressing.ListTimerAddress, AddressTypeEnum.DigitalMemoryTimer, 10); addressingServices.AlocateAddressingMemoryAndTimerAndCounter(program, program.addressing.ListCounterAddress, AddressTypeEnum.DigitalMemoryCounter, 10); lineIndex = program.InsertLineAtEnd(new Line()); for (int position = content.IndexOf("@laddermic.com") + 15; position < content.Length; position++) { opCode = (OperationCode)Convert.ToChar(content.Substring(position, 1)); switch (opCode) { case OperationCode.None: countOfEnds++; break; case OperationCode.LineEnd: countOfEnds++; if ((OperationCode)Convert.ToChar(content.Substring(position + 1, 1)) != OperationCode.None) { lineIndex = program.InsertLineAtEnd(new Line()); } break; case OperationCode.NormallyOpenContact: case OperationCode.NormallyClosedContact: countOfEnds = 0; //Instruction instruction = new Instruction((OperationCode)opCode); Instruction instruction = InstructionFactory.createInstruction(opCode); addressType = (AddressTypeEnum)Convert.ToChar(content.Substring(position + 1, 1)); index = (Int32)Convert.ToChar(content.Substring(position + 2, 1)); address = addressingServices.Find(addressType, index); if (address == null) { program.device.Pins[index - 1].Type = addressType; addressingServices.RealocatePinAddressesByPinTypesFromDevice(program.device); addressingServices.AlocateIOAddressing(program.device); address = addressingServices.Find(addressType, index); } instruction.SetOperand(0, address); position += 2; program.Lines[lineIndex].Instructions.Add(instruction); break; case OperationCode.OutputCoil: case OperationCode.Reset: countOfEnds = 0; { InstructionList instructions = new InstructionList(); instructions.Add(InstructionFactory.createInstruction(opCode)); addressType = (AddressTypeEnum)Convert.ToChar(content.Substring(position + 1, 1)); index = (Int32)Convert.ToChar(content.Substring(position + 2, 1)); address = addressingServices.Find(addressType, index); if (address == null) { program.device.Pins[index - 1].Type = addressType; addressingServices.RealocatePinAddressesByPinTypesFromDevice(program.device); addressingServices.AlocateIOAddressing(program.device); address = addressingServices.Find(addressType, index); } instructions[instructions.Count - 1].SetOperand(0, address); position += 2; lineServices.InsertToOutputs(program.Lines[lineIndex], instructions); instructions.Clear(); } break; case OperationCode.ParallelBranchBegin: case OperationCode.ParallelBranchEnd: case OperationCode.ParallelBranchNext: countOfEnds = 0; program.Lines[lineIndex].Instructions.Add(InstructionFactory.createInstruction(opCode)); break; case OperationCode.Counter: countOfEnds = 0; { InstructionList instructions = new InstructionList(); CounterInstruction counter = (CounterInstruction)InstructionFactory.createInstruction(opCode); counter.SetAddress(addressingServices.Find(AddressTypeEnum.DigitalMemoryCounter, (Int32)Convert.ToChar(content.Substring(position + 1, 1)))); counter.setBoxType((int)Convert.ToChar(content.Substring(position + 2, 1))); counter.setPreset((int)Convert.ToChar(content.Substring(position + 3, 1))); instructions.Add(counter); //instructions.Add(InstructionFactory.createInstruction(opCode)); //instructions[instructions.Count - 1].SetOperand(0, addressingServices.Find(AddressTypeEnum.DigitalMemoryCounter, (Int32)Convert.ToChar(content.Substring(position + 1, 1)))); //((Address)instructions[instructions.Count - 1].GetOperand(0)).Counter.Type = (Int32)Convert.ToChar(content.Substring(position + 2, 1)); //((Address)instructions[instructions.Count - 1].GetOperand(0)).Counter.Preset = (Int32)Convert.ToChar(content.Substring(position + 3, 1)); //instructions[instructions.Count - 1].SetOperand(1, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Counter.Type); //instructions[instructions.Count - 1].SetOperand(2, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Counter.Preset); position += 3; lineServices.InsertToOutputs(program.Lines[lineIndex], instructions); instructions.Clear(); } break; case OperationCode.Timer: countOfEnds = 0; { InstructionList instructions = new InstructionList(); instructions.Add(InstructionFactory.createInstruction(opCode)); instructions[instructions.Count - 1].SetOperand(0, addressingServices.Find(AddressTypeEnum.DigitalMemoryTimer, (Int32)Convert.ToChar(content.Substring(position + 1, 1)))); ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.Type = (Int32)Convert.ToChar(content.Substring(position + 2, 1)); ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.TimeBase = (Int32)Convert.ToChar(content.Substring(position + 3, 1)); ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.Preset = (Int32)Convert.ToChar(content.Substring(position + 4, 1)); instructions[instructions.Count - 1].SetOperand(1, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.Type); instructions[instructions.Count - 1].SetOperand(2, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.Preset); instructions[instructions.Count - 1].SetOperand(4, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.TimeBase); position += 4; lineServices.InsertToOutputs(program.Lines[lineIndex], instructions); instructions.Clear(); } break; } /// end of codes if (countOfEnds >= 2) { MicIntegrationServices p = new MicIntegrationServices(); //p.CreateFile("opcode.txt", content.Substring(content.IndexOf("@laddermic.com"), i - content.IndexOf("@laddermic.com") + 1)); //position = content.Length; break; } } return(program); }
internal void AddBranch(InstructionList instructions, int branchIndex) { Debug.Assert(((_targetIndex == UnknownIndex) == (_stackDepth == UnknownDepth))); Debug.Assert(((_targetIndex == UnknownIndex) == (_continuationStackDepth == UnknownDepth))); if (_targetIndex == UnknownIndex) { if (_forwardBranchFixups == null) { _forwardBranchFixups = new List<int>(); } _forwardBranchFixups.Add(branchIndex); } else { FixupBranch(instructions, branchIndex); } }
public Element (ElementType type, object val) { this.type = type; this.val = val; this.children = null; }
internal void FixupBranch(InstructionList instructions, int branchIndex) { Debug.Assert(_targetIndex != UnknownIndex); instructions.FixupBranch(branchIndex, _targetIndex - branchIndex); }
public override void Pause(InstructionList instructions) { base.Pause(instructions); mIsPaused = true; }
public static void AddKeyframeOk(Window callingWindow) { if (EditorData.EditorLogic.CurrentKeyframeList == null) { GuiManager.ShowMessageBox("There is no Keyframe List currently selected", "Error"); return; } if (EditorData.CurrentSpriteMembersWatching.Count == 0 && EditorData.CurrentSpriteFrameMembersWatching.Count == 0 && EditorData.CurrentPositionedModelMembersWatching.Count == 0 && EditorData.CurrentTextMembersWatching.Count == 0) { GuiManager.ShowMessageBox("There are no members being recorded. Try opening the " + "\"used members\" window through Window->Used Members menu item.", "No members"); return; } InstructionList instructionList = new InstructionList(); instructionList.Name = ((TextInputWindow)callingWindow).Text; double timeToExecute = GuiData.TimeLineWindow.timeLine.CurrentValue; EditorData.AddInstructionsToList(instructionList, timeToExecute); GuiData.TimeLineWindow.UpdateToCurrentSet(); EditorData.EditorLogic.CurrentKeyframeList.Add(instructionList); GuiData.ListBoxWindow.UpdateLists(); }