public bool TryPatchX64(out string errorMessage) { var function = functionProvider.GetFunction(IsDebuggerPresentConstants.DllName, IsDebuggerPresentConstants.FuncName); /* * Generate the following code: * * xor eax,eax * ret */ var instructions = new InstructionList(); instructions.Add(Instruction.Create(II.Code.Xor_r32_rm32, Register.EAX, Register.EAX)); instructions.Add(Instruction.Create(II.Code.Retnq)); var block = new InstructionBlock(new CodeWriterImpl(function), instructions, function.NewCodeAddress); if (!BlockEncoder.TryEncode(process.Bitness, block, out var encErrMsg)) { errorMessage = $"Failed to encode: {encErrMsg}"; return(false); } errorMessage = null; return(true); }
private InstructionList GetPaintedChanges() { InstructionList listToReturn = new InstructionList(); foreach (KeyValuePair <SpriteGrid, SpriteGrid> kvp in mObjectsWatching) { SpriteGrid referencedGrid = kvp.Key; SpriteGrid clonedGrid = kvp.Value; // Vic says: If the grid offset values aren't the same, then // the comparing methods will throw exceptions. Eventually we may // want to handle this IF we allow the user to both paint and change // the position of SpriteGrids in the same frame. This currently can't // be done, and it would be a pain to handle, so I'm going to take the easy // way out here. if (referencedGrid.Blueprint.X == clonedGrid.Blueprint.X && referencedGrid.Blueprint.Y == clonedGrid.Blueprint.Y && referencedGrid.Blueprint.Z == clonedGrid.Blueprint.Z) { // Get all of the differences between the two SpriteGrids List <TextureLocation <Texture2D> > textureDifferences = referencedGrid.TextureGrid.GetTextureLocationDifferences(clonedGrid.TextureGrid); List <TextureLocation <FloatRectangle> > textureCoordinateDifferences = referencedGrid.DisplayRegionGrid.GetTextureLocationDifferences(clonedGrid.DisplayRegionGrid); List <TextureLocation <AnimationChain> > animationChainDifferences = referencedGrid.AnimationChainGrid.GetTextureLocationDifferences(clonedGrid.AnimationChainGrid); if (textureDifferences.Count != 0 || textureCoordinateDifferences.Count != 0 || animationChainDifferences.Count != 0) { if (textureDifferences.Count != 0) { SpriteGridTexturePaintInstruction sgtpi = new SpriteGridTexturePaintInstruction( referencedGrid, textureDifferences); listToReturn.Add(sgtpi); } if (textureCoordinateDifferences.Count != 0) { SpriteGridDisplayRegionPaintInstruction sgdrpi = new SpriteGridDisplayRegionPaintInstruction( referencedGrid, textureCoordinateDifferences); listToReturn.Add(sgdrpi); } if (animationChainDifferences.Count != 0) { SpriteGridAnimationChainPaintInstruction sgacpi = new SpriteGridAnimationChainPaintInstruction( referencedGrid, animationChainDifferences); listToReturn.Add(sgacpi); } } } } return(listToReturn); }
public static void AddCallStub(InstructionList instructions, IntPtr regAddr, object[] arguments, bool x86, bool cleanStack = false) { if (x86) { instructions.Add(Instruction.Create(Code.Mov_r32_imm32, Register.EAX, regAddr.ToInt32())); AddCallStub(instructions, Register.EAX, arguments, true, cleanStack); } else { instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RAX, regAddr.ToInt64())); AddCallStub(instructions, Register.RAX, arguments, false, cleanStack); } }
public static uint AutoEncode(this Encoder Encoder, Instruction Instruction, ulong IP) { InstructionList List = new InstructionList(); if (Encoder.Bitness <= 32) { List.Add(Instruction); } else { if (Instruction.IsJmp() && !Instruction.IsCallFar && Instruction.Op0Kind != OpKind.Register) { if (!Instruction.IsANotJmp()) { Instruction.NegateConditionCode(); } var Jmp = Instruction.IPRelativeMemoryAddress.x64FarJmp(); //Get Far Jmp Size + Short Conditional Jmp Size var JmpSize = (uint)Jmp.GetAutoEncodedSize(64, IP); JmpSize += (uint)Instruction.ConditionCode.ToShortJmp(IP + JmpSize, 64).GetEncodedSize(64, IP); List.Add(Instruction.ConditionCode.ToShortJmp(IP + JmpSize, 64)); List.AddRange(Jmp); } else { switch (Instruction.Code) { case Code.Mov_r64_rm64: List.Add(Instruction.Create(Code.Mov_r64_imm64, Instruction.Op0Register, Instruction.IPRelativeMemoryAddress)); List.Add(Instruction.Create(Code.Mov_r64_rm64, Instruction.Op0Register, new MemoryOperand(Instruction.Op0Register))); break; default: List.Add(Instruction); break; } } } uint TotalSize = 0; foreach (var Inst in List) { TotalSize += Encoder.Encode(Inst, IP + TotalSize); } return(TotalSize); }
protected int Emit(Instruction element) { int index = _instructions.Count; _instructions.Add(element); return(index); }
public PositionedObjectUnpauseInstruction(T positionedObject) : base(positionedObject) { mVelocity = positionedObject.Velocity; mRelativeVelocity = positionedObject.RelativeVelocity; mAcceleration = positionedObject.Acceleration; mRelativeAcceleration = positionedObject.RelativeAcceleration; mRealVelocity = positionedObject.RealVelocity; mRealAcceleration = positionedObject.RealAcceleration; mDrag = positionedObject.Drag; mRotationXVelocity = positionedObject.RotationXVelocity; mRotationYVelocity = positionedObject.RotationYVelocity; mRotationZVelocity = positionedObject.RotationZVelocity; mRelativeRotationXVelocity = positionedObject.RelativeRotationXVelocity; mRelativeRotationYVelocity = positionedObject.RelativeRotationYVelocity; mRelativeRotationZVelocity = positionedObject.RelativeRotationZVelocity; foreach (Instruction instruction in positionedObject.Instructions) { mInstructions.Add(instruction); } }
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); }
public static InstructionList AutoEncode(this Encoder Encoder, Instruction Instruction, ulong IP) { InstructionList List = new InstructionList(); if (Encoder.Bitness <= 32) { List.Add(Instruction); } else { if (Instruction.IsJmp() && !Instruction.IsCallFar && Instruction.Op0Kind != OpKind.Register) { if (!Instruction.IsANotJmp()) { Instruction.NegateConditionCode(); } var Jmp = Instruction.Immediate64.AssemblyJmp(); //Get Far Jmp Size + Short Conditional Jmp Size var JmpSize = (uint)Jmp.GetAutoEncodedSize(64, IP); JmpSize += (uint)Instruction.ConditionCode.ToShortJmp(IP + JmpSize, 64).GetEncodedSize(64, IP); List.Add(Instruction.ConditionCode.ToShortJmp(IP + JmpSize, 64)); List.AddRange(Jmp); } else { switch (Instruction.Code) { case Code.Mov_r64_rm64: if (Instruction.Op1Kind != OpKind.Memory || Instruction.MemoryBase != Register.RIP) { goto default; } List.Add(Instruction.Create(Code.Mov_r64_imm64, Instruction.Op0Register, Instruction.IPRelativeMemoryAddress)); List.Add(Instruction.Create(Code.Mov_r64_rm64, Instruction.Op0Register, new MemoryOperand(Instruction.Op0Register))); break; default: List.Add(Instruction); break; } } } return(List); }
/// <summary> /// Pauses this instance and stores the unpause instructions in the argument InstructionList /// </summary> /// <param name="instructions">The list to fill</param> public override void Pause(InstructionList instructions) { SphereUnpauseInstruction instruction = new SphereUnpauseInstruction(this); instruction.Stop(this); instructions.Add(instruction); }
public override void AddInstructions(InstructionList instructions, Transform transform) { base.AddInstructions(instructions, transform); float w2 = Width / 2; float l = Length; float r = 0.4f * Min(w2, l); instructions.Add(Polygon.RoundedRectangle(0, -w2, l, w2, r, 16, transform, Color.Black, 1f)); }
public override InstructionList Load() { InstructionList instructions = new InstructionList(); foreach (string line in _instructionLines) { if (!string.IsNullOrWhiteSpace(line)) { string[] tokens = line.Split(' '); string label = null; if (tokens.First().EndsWith(":")) { label = tokens.First().Remove(tokens.First().Length - 1); tokens = tokens.Skip(1).ToArray(); } //string key = tokens.First().Replace("\r", "").Replace("\n", ""); string key = tokens.First().Trim().ToLowerInvariant(); var type = InstructionSet[key]; string[] args = null; if (tokens.Length > 1) { args = tokens.Skip(1).ToArray(); for (int i = 0; i < args.Length; i++) { args[i] = args[i].TrimEnd('\r'); } } IInstruction instruction = (IInstruction)Activator.CreateInstance(type, args); if (label == null) { instructions.Add(instruction); } else { instructions.Add(instruction, label); } } } return(instructions); }
public static InstructionList DecodeAmount(this Decoder Decoder, uint Count) { var List = new InstructionList(); while (List.Count < Count) { List.Add(Decoder.Decode()); } return(List); }
InstructionList EnumeratorDecode(Decoder decoder) { var list = new InstructionList(); foreach (var instr in decoder) { list.Add(instr); } return(list); }
public ShinyRate() { InitializeComponent(); if (Main.ExeFSPath == null) { WinFormsUtil.Alert("No exeFS code to load."); Close(); } string[] files = Directory.GetFiles(Main.ExeFSPath); if (!File.Exists(files[0]) || !Path.GetFileNameWithoutExtension(files[0]).Contains("code")) { WinFormsUtil.Alert("No .code.bin detected."); Close(); } codebin = files[0]; exefsData = File.ReadAllBytes(codebin); if (exefsData.Length % 0x200 != 0) { WinFormsUtil.Alert(".code.bin not decompressed. Aborting."); Close(); } // Load instruction set byte[] raw = Core.Properties.Resources.asm_mov; for (int i = 0; i < raw.Length; i += 4) { byte[] data = new byte[2]; Array.Copy(raw, i + 2, data, 0, 2); InstructionList.Add(new Instruction(BitConverter.ToUInt16(raw, i), data)); } // Fetch Offset byte[] pattern = { 0x01, 0x50, 0x85, 0xE2, 0x05, 0x00, 0x50, 0xE1, 0xDE, 0xFF, 0xFF, 0xCA }; offset = Util.IndexOfBytes(exefsData, pattern, 0, 0) - 4; if (offset < 0) { WinFormsUtil.Alert("Unable to find PID Generation routine.", "Closing."); Close(); } if (exefsData[offset] != 0x23) // already patched { uint val = BitConverter.ToUInt16(exefsData, offset); var instruction = InstructionList.FirstOrDefault(z => z.ArgVal == val); if (instruction == null) { WinFormsUtil.Alert(".code.bin was modified externally.", "Existing value not loaded."); } else { WinFormsUtil.Alert(".code.bin was already patched for shiny rate.", "Loaded existing value."); NUD_Rerolls.Value = instruction.Value; } modified = true; } changeRerolls(null, null); CheckAlwaysShiny(); }
public static InstructionList DecodeMany(this Decoder Decoder, uint MinLength) { var List = new InstructionList(); var Begin = Decoder.IP; while (Decoder.IP < Begin + MinLength) { List.Add(Decoder.Decode()); } return(List); }
protected void CreateCodeSegment(IReadOnlyList <Instruction> instructions, ushort segmentOrdinal = 1) { var instructionList = new InstructionList(instructions.Count); foreach (var i in instructions) { instructionList.Add(i); } CreateCodeSegment(instructionList, segmentOrdinal); }
public void RegisterCommand(char symbol, Action <IVirtualMachine> execute) { if (InstructionList == null) { InstructionList = new Dictionary <char, Action <IVirtualMachine> > { [symbol] = execute } } ; else { InstructionList.Add(symbol, execute); } }
void Add_works() { var instructions = GetInstructions(); var list = new InstructionList(); for (int i = 0; i < instructions.Length; i++) { list.Add(instructions[i]); Assert.Equal(i + 1, list.Count); Assert.True(i < list.Capacity); var listElems = new Instruction[list.Count]; list.CopyTo(listElems); AssertEqual(instructions, listElems, listElems.Length); } }
// ---------------------------------------------------------------------------------------- #region World public InstructionList GetInstructions() { InstructionList instructions = new InstructionList(); AddInstructions(instructions, Transform); Polygon polygon = new Polygon(Color.Black, 1f) { { XLo, YLo }, { XHi, YLo }, { XHi, YHi }, { XLo, YHi }, }; instructions.Add(polygon); return(instructions); }
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); }
/// <summary> /// Initializes a new instance of the <see cref="CSharpScope"/> class. /// </summary> /// <param name="context">The creation context.</param> /// <param name="parentFeature">The parent feature.</param> /// <param name="source">The Easly node from which the C# node is created.</param> protected CSharpScope(ICSharpContext context, ICSharpFeature parentFeature, IScope source) : base(source) { ParentFeature = parentFeature; foreach (IEntityDeclaration Declaration in source.EntityDeclarationList) { ICSharpScopeAttributeFeature NewDeclaration = CSharpScopeAttributeFeature.Create(context, parentFeature.Owner, Declaration.ValidEntity.Item); EntityDeclarationList.Add(NewDeclaration); } foreach (IInstruction Instruction in source.InstructionList) { ICSharpInstruction NewInstruction = CSharpInstruction.Create(context, parentFeature, Instruction); InstructionList.Add(NewInstruction); } }
private InstructionList DisassembleMethodInstructions(long methodOffset) { const int NativeBitness = 64; const int MaxMethodLength = 0xFFFF; var codeReader = new ByteArrayCodeReader(NativeDllCode, (int)methodOffset, (int)Math.Min(MaxMethodLength, NativeDllCode.Length - methodOffset)); var decoder = Decoder.Create(NativeBitness, codeReader); decoder.InstructionPointer = 0; ulong endRip = decoder.InstructionPointer + MaxMethodLength; var instructions = new InstructionList(); int int3count = 0; while (decoder.InstructionPointer < endRip) { if (decoder.InstructionPointer > 0) { long currentOffset = methodOffset + (long)decoder.InstructionPointer; if (Offsets.MethodsFromOffsets.ContainsKey(currentOffset)) { break; } } decoder.Decode(out Instruction instruction); if (instruction.Code == Code.INVALID) { break; } else if (instruction.Code == Code.Int3) { int3count++; if (int3count >= 2) { break; } } else { int3count = 0; } instructions.Add(instruction); } return(instructions); }
void ToArray_works(Instruction[] instructions, bool addExtraElem) { var list = new InstructionList(instructions); if (addExtraElem) { var instr = Instruction.Create(Code.Nopw); list.Add(instr); Array.Resize(ref instructions, instructions.Length + 1); instructions[instructions.Length - 1] = instr; } Assert.Equal(instructions.Length, list.Count); Assert.True(instructions.Length <= list.Capacity); var array = list.ToArray(); Assert.Equal(list.Count, array.Length); AssertEqual(instructions, array); }
public static void RecordInstructions(InstructionList listToRecordTo, double timeToExecute, List <string> membersToIgnore, Text textToRecord) { foreach (string member in EditorData.CurrentTextMembersWatching) { if (membersToIgnore.Contains(member) == false) { Type memberType = InstructionManager.GetTypeForMember(mTextType, member); Type genericType = typeof(Instruction <,>).MakeGenericType( mTextType, memberType); object value = FlatRedBall.Instructions.Reflection.LateBinder <Text> .Instance[textToRecord, member]; Instruction instruction = Activator.CreateInstance(genericType, textToRecord, member, value, timeToExecute) as Instruction; listToRecordTo.Add(instruction); } } }
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); } } }
public InstructionList Parse() { if (_instructions != null) { return(_instructions); } var reader = new StreamReader(Stream); _instructions = new InstructionList(); _dataSet = new DataSet(); string line; while ((line = reader.ReadLine()) != null) { _instructions.Add(ParseInstruction(line.Trim())); } _instructions.MaxLocals = _dataSet.MaxLocals; return(_instructions); }
public override InstructionList GetChangedMemberInstructions(Polygon objectToWatch) { InstructionList listToReturn = base.GetChangedMemberInstructions(objectToWatch); Polygon polygonToCompareAgainst = mObjectsWatching[objectToWatch]; #region See if points differ bool pointsDiffer = false; for (int i = 0; i < objectToWatch.Points.Count; i++) { if (objectToWatch.Points[i] != polygonToCompareAgainst.Points[i]) { pointsDiffer = true; break; } } if (pointsDiffer) { Point[] oldPoints = new Point[polygonToCompareAgainst.Points.Count]; polygonToCompareAgainst.Points.CopyTo(oldPoints, 0); listToReturn.Add( new Instruction <Polygon, Point[]>( objectToWatch, "Points", oldPoints, 0)); polygonToCompareAgainst.Points = objectToWatch.Points; } #endregion return(listToReturn); }
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); } }
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; }
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 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); }
private void Gen(Instruction instr) { InstructionList.Add(instr); }
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; }
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 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 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; }