~ruther/csharp-dll-injector

ref: e50413122ffccc9a61f7f524bf7eb773084a41a6 csharp-dll-injector/DllUtils/Memory/AllocatedMemory.cs -rw-r--r-- 1.7 KiB
e5041312 — Rutherther Update README.md 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DllUtils.Interop;
using DllUtils.Process;

namespace DllUtils.Memory
{
    public class AllocatedMemory
    {
        public AllocatedMemory(ProcessHandle process, IntPtr address, byte[] data, int length)
        {
            Process = process;
            Address = address;
            Data = data;
            Length = length;
        }

        public ProcessHandle Process { get; }

        public bool IsAllocated { get; private set; }
        public bool IsFreed { get; private set; }

        public byte[] Data { get; }

        public int Length { get; }

        public IntPtr Address { get; private set; }

        public bool Alloc()
        {
            if (!IsAllocated)
            {
                Address = Kernel32.VirtualAllocEx(Process.Handle, (IntPtr) null, (IntPtr) Length, 0x1000, 0x40);

                if (Address != IntPtr.Zero)
                {
                    IsAllocated = true;
                }
            }

            return Address != IntPtr.Zero;
        }

        public bool Write()
        {
            if (!IsAllocated)
            {
                return false;
            }

            if (Kernel32.WriteProcessMemory(Process.Handle, Address, Data, (uint) Length, out int bytesWritten) == 0)
            {
                return false;
            }

            return bytesWritten == Length;
        }

        public void Free()
        {
            if (!IsFreed)
            {
                IsFreed = Kernel32.VirtualFreeEx(Process.Handle, Address, UIntPtr.Zero, 0x8000);
                IsAllocated = !IsFreed;
                Address = IntPtr.Zero;
            }
        }
    }
}
Do not follow this link