Esempio n. 1
0
        public void LuaDoString(string command)
        {
            AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tExecuting Lua \"{command}\"", LogLevel.Verbose);
            if (command.Length > 0)
            {
                byte[]           bytes    = Encoding.UTF8.GetBytes(command);
                MemoryAllocation memAlloc = TrashMem.AllocateMemory(bytes.Length + 1);
                if (memAlloc == null)
                {
                    return;
                }

                TrashMem.WriteBytes(memAlloc.Address, bytes);

                if (memAlloc.Address == 0)
                {
                    return;
                }

                string[] asm = new string[]
                {
                    $"MOV EAX, 0x{memAlloc.Address.ToString("X")}",
                    "PUSH 0",
                    "PUSH EAX",
                    "PUSH EAX",
                    $"CALL 0x{OffsetList.FunctionLuaDoString.ToString("X")}",
                    "ADD ESP, 0xC",
                    "RETN",
                };

                InjectAndExecute(asm, false);
                TrashMem.FreeMemory(memAlloc);
            }
        }
Esempio n. 2
0
        public string GetLocalizedText(string variable)
        {
            AmeisenBotLogger.Instance.Log($"[{ProcessId.ToString("X", CultureInfo.InvariantCulture.NumberFormat)}]\tReading Lua variable \"{variable}\"", LogLevel.Verbose);
            if (variable.Length > 0)
            {
                byte[]           bytes    = Encoding.UTF8.GetBytes(variable);
                MemoryAllocation memAlloc = TrashMem.AllocateMemory(bytes.Length + 1);
                if (memAlloc == null)
                {
                    return("");
                }

                TrashMem.WriteBytes(memAlloc.Address, bytes);

                string[] asmLocalText = new string[]
                {
                    $"CALL 0x{OffsetList.FunctionGetActivePlayerObject.ToString("X")}",
                    "MOV ECX, EAX",
                    "PUSH -1",
                    $"PUSH 0x{memAlloc.Address.ToString("X")}",
                    $"CALL 0x{OffsetList.FunctionGetLocalizedText.ToString("X")}",
                    "RETN",
                };

                string result = Encoding.UTF8.GetString(InjectAndExecute(asmLocalText, true));
                TrashMem.FreeMemory(memAlloc);
                return(result);
            }
            return("");
        }
Esempio n. 3
0
        private static void init()
        {
            if (Allocation != null)
            {
                return;
            }

            Allocation          = Memory.Allocate(0x90);
            TempPoint1          = MemoryObject.FromAddress <NiPoint3>(Allocation.Address);
            TempPoint2          = MemoryObject.FromAddress <NiPoint3>(Allocation.Address + 0x10);
            TempNormal          = MemoryObject.FromAddress <NiPoint3>(Allocation.Address + 0x20);
            TempSafety          = MemoryObject.FromAddress <NiPoint3>(Allocation.Address + 0x30);
            TempTransform       = MemoryObject.FromAddress <NiTransform>(Allocation.Address + 0x40);
            TempTransform.Scale = 1.0f;
            TempSafety.X        = 0.0f;
            TempSafety.Y        = 0.0f;
            TempSafety.Z        = 0.0f;

            SetupRaycastMask(new[]
            {
                CollisionLayers.AnimStatic,
                CollisionLayers.Biped,
                CollisionLayers.CharController,
                //CollisionLayers.Clutter,
                CollisionLayers.DebrisLarge,
                CollisionLayers.Ground,
                //CollisionLayers.Props,
                CollisionLayers.Static,
                CollisionLayers.Terrain,
                CollisionLayers.Trap,
                CollisionLayers.Trees,
                CollisionLayers.Unidentified
            });
        }
Esempio n. 4
0
        private InlineHook(QHackContext ctx, AssemblyCode code, HookParameters parameters)
        {
            Context          = ctx;
            Code             = code.Copy();
            MemoryAllocation = new MemoryAllocation(ctx);
            Parameters       = parameters;

            byte[] headInstBytes = GetHeadBytes(Context.DataAccess.ReadBytes(Parameters.TargetAddress, 32));

            nuint allocAddr        = MemoryAllocation.AllocationBase;
            nuint safeFreeFlagAddr = allocAddr + (uint)HookInfo.Offset_SafeFreeFlag;
            nuint onceFlagAddr     = allocAddr + (uint)HookInfo.Offset_OnceFlag;
            nuint codeAddr         = allocAddr + (uint)HookInfo.HeaderSize;
            nuint retAddr          = Parameters.TargetAddress + (uint)headInstBytes.Length;

            HookInfo info = new(allocAddr, headInstBytes);

            Assembler assembler = new();

            assembler.Emit(DataHelper.GetBytes(info));                                         //emit the header before runnable code
            assembler.Emit((Instruction)$"mov dword ptr [{safeFreeFlagAddr}],1");
            assembler.Emit(Parameters.IsOnce ? GetOnceCheckedCode(Code, onceFlagAddr) : Code); //once or not
            if (Parameters.Original)
            {
                assembler.Emit(headInstBytes);                //emit the raw code replaced by hook jmp
            }
            assembler.Emit((Instruction)$"mov dword ptr [{safeFreeFlagAddr}],0");
            assembler.Emit((Instruction)$"jmp {retAddr}");

            Context.DataAccess.WriteBytes(allocAddr, assembler.GetByteCode(allocAddr));

            JmpHeadBytes = new byte[headInstBytes.Length];
            Array.Fill <byte>(JmpHeadBytes, 0x90);
            Assembler.Assemble($"jmp {codeAddr}", Parameters.TargetAddress).CopyTo(JmpHeadBytes, 0);
        }
Esempio n. 5
0
        private void stepsTable_CurrentCellChanged(object sender, EventArgs e)
        {
            int selectedIndex = stepsTable.CurrentRow.Index;

            applyMemory(selectedIndex);
            accumulatorBox.Text = CurrCode.Steps[selectedIndex].Accumulator.ToString("000");
            outputBox.Text      = CurrCode.getOutput(selectedIndex);

            int lineNumber = CurrCode.Steps[selectedIndex].LineNumber;

            counterBox.Text = lineNumber.ToString("00");
            if (Instruction.Instructions[CurrCode.Lines[lineNumber].Instruction] != "DAT")
            {
                MemoryAllocation currTarget = CurrCode.Lines[lineNumber].Target;
                addressBox.Text     = currTarget != null ? CurrCode.Lines[lineNumber].Target.Address.ToString("00") : "00";
                instructionBox.Text = Math.Floor(CurrCode.getMemoryFromChanges(selectedIndex)[lineNumber] / 100.0).ToString();
            }

            programTable.Rows[CurrCode.Steps[selectedIndex].LineNumber].Selected = true;

            highlightImportant(selectedIndex, false);
            changeSelectedLabel();

            setHelpStrip(selectedIndex);
        }
Esempio n. 6
0
 public void BeforeEach()
 {
     _memBucketInput = new List <int> {
         0, 2, 7, 0
     };
     _systemUnderTest = new MemoryAllocation(_memBucketInput);
 }
        internal CameraStabilize(CameraMain cameraMain, CameraTarget target)
        {
            if (cameraMain == null)
            {
                throw new ArgumentNullException("cameraMain");
            }

            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            CameraMain = cameraMain;

            if (Allocation == null)
            {
                Allocation = Memory.Allocate(0x60);
            }

            TempPoint           = MemoryObject.FromAddress <NiPoint3>(Allocation.Address);
            TempTransform       = MemoryObject.FromAddress <NiTransform>(Allocation.Address + 0x10);
            TempTransform.Scale = 1.0f;
            TweenPoint          = MemoryObject.FromAddress <NiPoint3>(Allocation.Address + 0x50);

            ForTarget = GetFromTarget(target);
        }
Esempio n. 8
0
        public void ConstructorShould_PopulateProperties()
        {
            var allocation = new MemoryAllocation(input);

            Assert.NotNull(allocation.MemoryBanks);
            Assert.Equal(4, allocation.MemoryBanks.Length);
            Assert.NotNull(allocation.MemoryBankHistory);
        }
Esempio n. 9
0
        public void DaySix_PartTwo_ReturnsNumberOfRedistributionCyclesInOneLoop()
        {
            var input      = File.ReadAllLines($"{inputsPrefix}Day6.txt");
            var allocation = new MemoryAllocation(input.First());
            var result     = allocation.GetCyclesForCompleteLoop();

            Assert.Equal(1695, result);
        }
Esempio n. 10
0
        public void DaySix_PartOne_ReturnsNumberOfRedistributionCycles()
        {
            var input      = File.ReadAllLines($"{inputsPrefix}Day6.txt");
            var allocation = new MemoryAllocation(input.First());
            var result     = allocation.GetTotalCyclesBeforeLoopRestart();

            Assert.Equal(7864, result);
        }
Esempio n. 11
0
        public void SetKernelArg(string kernelName, uint idx, MemoryAllocation mem)
        {
            GCHandle garbageCollectorHandle = GCHandle.Alloc(mem.buffer, GCHandleType.Pinned);
            var      errCode = KernelsNativeApi.SetKernelArgument(kernels[kernelName], idx, new UIntPtr((uint)Marshal.SizeOf(mem.buffer)), garbageCollectorHandle.AddrOfPinnedObject());

            garbageCollectorHandle.Free();
            ThrowOnError(errCode, String.Format("Failed to set arg #{0} for kernel {1}", idx, kernelName));
        }
Esempio n. 12
0
 /// <summary>
 /// Frees resources.
 /// </summary>
 protected override void Free()
 {
     if (this.Allocation != null)
     {
         this.Allocation.Dispose();
         this.Allocation = null;
     }
 }
Esempio n. 13
0
        public void MemoryAllocFreeTest()
        {
            MemoryAllocation memAlloc = TrashMem.AllocateMemory(32);

            Assert.IsNotNull(memAlloc);
            Assert.IsTrue(memAlloc.Address != 0x0);
            Assert.IsTrue(memAlloc.Free());
        }
Esempio n. 14
0
        private void button3_Click(object sender, EventArgs e)
        {
            this.Hide();
            MemoryAllocation f4 = new MemoryAllocation();

            f4.ShowDialog();
            this.Close();
        }
Esempio n. 15
0
        internal static IntPtr Allocate(SafeProcessHandle processHandle, int size)
        {
            // Allocate memory in the process

            const MemoryAllocation allocationType = MemoryAllocation.Commit | MemoryAllocation.Reserve;

            return(VirtualAllocEx(processHandle, IntPtr.Zero, size, allocationType, MemoryProtection.PageExecuteReadWrite));
        }
Esempio n. 16
0
        internal FileStream(FileHandle handle)
        {
            Handle = handle;
            // TODO: Store Target in FileHandle
            var targetProcessId = SysCalls.GetProcessIDForCommand(SysCallTarget.OpenFile);

            ReadBuffer  = ApplicationRuntime.RequestMessageBuffer(4096, targetProcessId);
            WriteBuffer = ApplicationRuntime.RequestMessageBuffer(4096, targetProcessId);
        }
Esempio n. 17
0
 internal unsafe RuntimeElfSection(string name, ElfSectionHeader *header, Addr physAddr)
 {
     _Name  = name;
     Header = header;
     _Data  = new MemoryAllocation(physAddr, (int)header->Size)
     {
         Disposable = false,
     };
 }
Esempio n. 18
0
 internal CameraResult()
 {
     Allocation           = Memory.Allocate(0x34);
     Transform            = MemoryObject.FromAddress <NiTransform>(Allocation.Address);
     Transform.Position.X = 0.0f;
     Transform.Position.Y = 0.0f;
     Transform.Position.Z = 0.0f;
     Transform.Rotation.Identity(1.0f);
     Transform.Scale = 1.0f;
 }
Esempio n. 19
0
        public void ReadBuffer(MemoryAllocation mem, bool isBlocking, UIntPtr offset, UIntPtr lengthInBytes, IntPtr output)
        {
            IntPtr ev          = IntPtr.Zero;
            var    errCodeRead = EnqueuedCommandsNativeApi.EnqueueReadBuffer(commandQueue, mem.buffer, isBlocking ? 1U : 0U, offset, lengthInBytes, output, 0, null, out ev);

            ThrowOnError(errCodeRead, String.Format("Failed to enqueue read buffer. Read Size: {0}, Buffer size: {1}", lengthInBytes, mem.bufferSizeInBytes));

            var errCodeEv = EventsNativeApi.ReleaseEvent(ev);

            ThrowOnError(errCodeEv, String.Format("Failed release event (EnqueueReadBuffer)"));
        }
Esempio n. 20
0
 public void Reallocate_TieForBiggest_FirstBucketUsed()
 {
     _systemUnderTest = new MemoryAllocation(new List <int> {
         3, 1, 2, 3
     });
     _systemUnderTest.Reallocate();
     Assert.AreEqual(0, _systemUnderTest.Buckets[0]);
     Assert.AreEqual(2, _systemUnderTest.Buckets[1]);
     Assert.AreEqual(3, _systemUnderTest.Buckets[2]);
     Assert.AreEqual(4, _systemUnderTest.Buckets[3]);
 }
Esempio n. 21
0
        public void UploadToMemory(MemoryAllocation mem, int mem_offset, int sizeInBytes, IntPtr data, bool IsBlocking)
        {
            IntPtr ev           = IntPtr.Zero;
            var    errCodeWrite = EnqueuedCommandsNativeApi.EnqueueWriteBuffer(commandQueue, mem.buffer, IsBlocking ? 1U : 0U, new UIntPtr((uint)mem_offset * 4U), new UIntPtr((uint)sizeInBytes), data, 0, null, out ev);

            ThrowOnError(errCodeWrite, String.Format("Failed to enqueue write buffer. Write-size:{0}, Target buffer size: {1}", sizeInBytes, mem.bufferSizeInBytes));

            var errCodeEv = EventsNativeApi.ReleaseEvent(ev);

            ThrowOnError(errCodeEv, String.Format("Failed release event (EnqueueWriteBuffer, UploadToMemory_1)"));
        }
Esempio n. 22
0
        public MemoryAllocation GetMemoryFor(int requiredSizeInBytes, MemoryFlag flags, IntPtr data, int data_size_in_bytes = -1)
        {
            if (!IsInitialized())
            {
                return(null);
            }

            var accessFlags = flags & (MemoryFlag.ReadOnly | MemoryFlag.WriteOnly | MemoryFlag.ReadWrite);

            MemoryAllocation candidate        = null;
            uint             bestMatchingSize = uint.MaxValue;
            int itemToSwap = -1;

            for (int i = 0; i < freeMemoryAllocations.Count; i++)
            {
                var item = freeMemoryAllocations[i];
                if (item.flags == accessFlags && item.bufferSizeInBytes >= requiredSizeInBytes && item.bufferSizeInBytes < bestMatchingSize) //Select the smallest sufficient memory allocation from our allocations
                {
                    bestMatchingSize = item.bufferSizeInBytes;
                    candidate        = item;
                    itemToSwap       = i;
                    if (item.bufferSizeInBytes == requiredSizeInBytes)
                    {
                        break;
                    }
                }
            }

            if (candidate == null)
            {
                candidate = CreateMemoryAllocation(clContext, (uint)requiredSizeInBytes, accessFlags, IntPtr.Zero);
                usedMemoryAllocations.Add(candidate);
            }
            else
            {
                freeMemoryAllocations.RemoveAt(itemToSwap);
                usedMemoryAllocations.Add(candidate);
            }

            if (flags.HasFlag(MemoryFlag.CopyHostPointer) && data != IntPtr.Zero)
            {
                int upload_size_in_bytes = data_size_in_bytes >= 0 ? data_size_in_bytes : requiredSizeInBytes;

                IntPtr ev           = IntPtr.Zero;
                var    errCodeWrite = EnqueuedCommandsNativeApi.EnqueueWriteBuffer(commandQueue, candidate.buffer, 0U, UIntPtr.Zero, new UIntPtr((uint)upload_size_in_bytes), data, 0, null, out ev);
                ThrowOnError(errCodeWrite, String.Format("Failed to enqueue write buffer. Write-size:{0}, Target buffer size: {1}", requiredSizeInBytes, candidate.bufferSizeInBytes));

                var errCodeEv = EventsNativeApi.ReleaseEvent(ev);
                ThrowOnError(errCodeEv, String.Format("Failed release event (EnqueueWriteBuffer)"));
            }

            return(candidate);
        }
Esempio n. 23
0
        public void DetermineIndexOfHighestLoadShould_ReturnBankWithMostBlocks()
        {
            var allocation = new MemoryAllocation(input);
            var highest    = allocation.DetermineIndexOfHighestLoad();

            Assert.Equal(2, highest);

            allocation = new MemoryAllocation(inputTwo);
            highest    = allocation.DetermineIndexOfHighestLoad();

            Assert.Equal(2, highest);
        }
Esempio n. 24
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         ErrorPanel?.Dispose();
         ErrorMessage?.Dispose();
         MainPanel?.Dispose();
         ServerName?.Dispose();
         MemoryAllocation?.Dispose();
         RadAjaxManager?.Dispose();
         CacheGrid?.Dispose();
     }
 }
Esempio n. 25
0
 /// <summary>
 /// Disposes this hook WITHOUT any check.<br/>
 /// Disposing a hook means to detach and then free memory regions the hook uses.<br/>
 /// It's extremely dangerous to call this method.
 /// Instead, you should call <see cref="WaitToDispose(int)"/>.
 /// </summary>
 public void Dispose()
 {
     lock (this)
     {
         if (_IsDisposed)
         {
             return;
         }
         GC.SuppressFinalize(this);
         Detach();
         MemoryAllocation.Dispose();
         _IsDisposed = true;
     }
 }
Esempio n. 26
0
        protected override void Free()
        {
            if (NetScriptFramework.Main.IsShutdown)
            {
                return;
            }

            this.Transform = null;

            if (this.Allocation != null)
            {
                this.Allocation.Dispose();
                this.Allocation = null;
            }
        }
Esempio n. 27
0
        protected override void Free()
        {
            if (Main.IsShutdown)
            {
                return;
            }

            Transform = null;

            if (Allocation != null)
            {
                Allocation.Dispose();
                Allocation = null;
            }
        }
Esempio n. 28
0
        private RemoteThread(QHackContext ctx, AssemblyCode asm, uint size = 0x1000)
        {
            Context    = ctx;
            Allocation = new MemoryAllocation(ctx, size);
            Header     = new RemoteThreadHeader(Allocation.AllocationBase);

            Assembler assembler = new();

            assembler.Emit(DataHelper.GetBytes(Header));
            assembler.Emit((Instruction)$"mov dword ptr [{Header.Address_SafeFreeFlag}],1");
            assembler.Emit(asm);
            assembler.Emit((Instruction)$"mov dword ptr [{Header.Address_SafeFreeFlag}],0");
            assembler.Emit((Instruction)"ret");
            Context.DataAccess.WriteBytes(Header.AllocationAddress, assembler.GetByteCode(Header.AllocationAddress));
        }
Esempio n. 29
0
        public void MemoryAllocFreeMultiCharsBytesTest()
        {
            MemoryAllocation memAlloc = TrashMem.AllocateMemory(32);

            byte[] sampleBytes = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5 };
            TrashMem.WriteBytes(memAlloc.Address, sampleBytes);
            byte[] bytesRead = TrashMem.ReadChars(memAlloc.Address, 5);

            Assert.AreEqual(sampleBytes[0], bytesRead[0]);
            Assert.AreEqual(sampleBytes[1], bytesRead[1]);
            Assert.AreEqual(sampleBytes[2], bytesRead[2]);
            Assert.AreEqual(sampleBytes[3], bytesRead[3]);
            Assert.AreEqual(sampleBytes[4], bytesRead[4]);

            Assert.IsTrue(memAlloc.Free());
        }
Esempio n. 30
0
        public void UploadToMemory(MemoryAllocation mem, int mem_offset, int data_offset, float[] data, bool IsBlocking, int size = -1)
        {
            uint   uploadSize = size < 0 ? ((uint)data.Length * 4U) : (uint)size * 4U;
            IntPtr ev         = IntPtr.Zero;
            Result errCodeWrite;

            unsafe
            {
                fixed(float *dataPtr = data)
                {
                    errCodeWrite = EnqueuedCommandsNativeApi.EnqueueWriteBuffer(commandQueue, mem.buffer, IsBlocking ? 1U : 0U, new UIntPtr((uint)mem_offset), new UIntPtr(uploadSize), new IntPtr(dataPtr + data_offset), 0, null, out ev);
                }
            }
            ThrowOnError(errCodeWrite, String.Format("Failed to enqueue write buffer. Write-size:{0}, Target buffer size: {1}, data_offset:{2}", uploadSize, mem.bufferSizeInBytes, data_offset * 4));

            var errCodeEv = EventsNativeApi.ReleaseEvent(ev);

            ThrowOnError(errCodeEv, String.Format("Failed to release event (EnqueueWriteBuffer, UploadToMemory_3)"));
        }