Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using System.Text;
- namespace MemoryManagement;
- public class MemoryManagement
- {
- // Unsed
- private const int PROCESS_CREATE_THREAD = 2;
- private const int PROCESS_QUERY_INFORMATION = 1024;
- private const int PROCESS_VM_OPERATION = 8;
- private const int PROCESS_VM_WRITE = 32;
- private const int PROCESS_VM_READ = 16;
- private const uint MEM_COMMIT = 4096u;
- private const uint MEM_RESERVE = 8192u;
- private const uint PAGE_READWRITE = 4u;
- //
- /// <summary>
- /// The handle of the attached process
- /// </summary>
- public static nint ProcessHandle { get => pHandle; }
- private static nint pHandle;
- /// <summary>
- /// The DLL
- /// </summary>
- private ProcessModule? mainModule;
- /// <summary>
- /// The current attached process (Null when not attached)
- /// </summary>
- public Process? AttachedProcess { get => procs; }
- private Process? procs = null;
- public Dictionary<string, nint> Modules { get; private set; } = new();
- // Private imports
- [DllImport("kernel32.dll")]
- private static extern bool WriteProcessMemory(nint hProcess, nint lpBaseAddress, string lpBuffer, nuint nSize, out nint lpNumberOfBytesWritten);
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
- private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName);
- [DllImport("kernel32.dll")]
- private static extern bool ReadProcessMemory(nint hProcess, nuint lpBaseAddress, [Out] byte[] lpBuffer, nuint nSize, nint lpNumberOfBytesRead);
- [DllImport("kernel32.dll", EntryPoint = "CloseHandle")]
- private static extern bool _CloseHandle(nint hObject);
- [DllImport("kernel32.dll")]
- private static extern bool WriteProcessMemory(nint hProcess, nuint lpBaseAddress, byte[] lpBuffer, nuint nSize, nint lpNumberOfBytesWritten);
- //
- // Public imports
- [DllImport("kernel32.dll")]
- public static extern int CloseHandle(nint hObject);
- [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
- public static extern nint GetModuleHandle(string lpModuleName);
- [DllImport("kernel32.dll")]
- public static extern nint OpenProcess(uint dwDesiredAccess, int bInheritHandle, int dwProcessId);
- //
- /// <summary>
- /// Attaches to the process
- /// </summary>
- /// <param name="procID"></param>
- /// <returns></returns>
- public bool OpenGameProcess(int procID)
- {
- if (procID is not 0)
- {
- procs = Process.GetProcessById(procID);
- if (!procs.Responding)
- return false;
- else
- {
- pHandle = OpenProcess(2035711u, 1, procID);
- mainModule = procs.MainModule;
- RefreshModules();
- return true;
- }
- }
- return false;
- }
- /// <summary>
- /// Refreshes the Modules dictionary
- /// </summary>
- public void RefreshModules()
- {
- if (procs is not null)
- {
- Modules.Clear();
- foreach (ProcessModule processModule in procs.Modules)
- if (processModule.ModuleName is not "" &&
- processModule.ModuleName is not null &&
- !Modules.ContainsKey(processModule.ModuleName))
- if (processModule.ModuleName is not null)
- Modules.Add(processModule.ModuleName, processModule.BaseAddress);
- }
- }
- /// <summary>
- /// Gets the ID of a process via its string name
- /// </summary>
- /// <param name="name"></param>
- /// <returns></returns>
- public int GetProcIDFromName(string name)
- {
- Process? process = Process.GetProcessesByName(name).FirstOrDefault();
- return process?.Id ?? 0;
- }
- /// <summary>
- /// Closes the attached process
- /// </summary>
- public void CloseProcess()
- => _ = CloseHandle(pHandle);
- /// <summary>
- /// .INI file loader
- /// </summary>
- /// <param name="name"></param>
- /// <param name="file"></param>
- /// <returns></returns>
- public string LoadCode(string name, string file)
- {
- StringBuilder stringBuilder = new(1024);
- if (file is not "")
- _ = GetPrivateProfileString("codes", name, "", stringBuilder, (uint)file.Length, file);
- else
- _ = stringBuilder.Append(name);
- return stringBuilder.ToString();
- }
- /// <summary>
- /// Read a string from the attached process
- /// </summary>
- /// <param name="code"></param>
- /// <param name="file"></param>
- /// <returns></returns>
- public string ReadString(string code, string file = "")
- {
- _ = getCode(code, file, 4);
- byte[] array = new byte[10];
- return ReadProcessMemory(pHandle,
- !LoadCode(code, file).Contains(',') ?
- loadUIntPtrCode(code, file) :
- getCode(code, file, 4), array,
- (nuint)10uL, nint.Zero) ? Encoding.UTF8.GetString(array) : "";
- }
- /// <summary>
- /// Write data to a specific address of the attached process
- /// </summary>
- /// <param name="code"></param>
- /// <param name="type"></param>
- /// <param name="write"></param>
- /// <param name="file"></param>
- /// <returns></returns>
- public bool WriteMemory(string code, string type, string write, string file = "")
- {
- byte[] lpBuffer = new byte[4];
- int num = 4;
- nuint lpBaseAddress = !LoadCode(code, file).Contains(',') ? loadUIntPtrCode(code, file) : getCode(code, file, 4);
- switch (type)
- {
- case "float":
- lpBuffer = BitConverter.GetBytes(Convert.ToSingle(write));
- break;
- case "int":
- lpBuffer = BitConverter.GetBytes(Convert.ToInt32(write));
- break;
- case "byte":
- lpBuffer = BitConverter.GetBytes(Convert.ToInt32(write));
- num = 1;
- break;
- case "string":
- lpBuffer = Encoding.UTF8.GetBytes(write);
- num = write.Length;
- break;
- }
- return WriteProcessMemory(pHandle, lpBaseAddress, lpBuffer, (nuint)(ulong)(long)num, nint.Zero);
- }
- private nuint loadUIntPtrCode(string name, string path = "")
- {
- string text = LoadCode(name, path);
- if (string.IsNullOrEmpty(text))
- return nuint.Zero;
- string value = text[(text.IndexOf('+') + 1)..];
- if (string.IsNullOrEmpty(value))
- return nuint.Zero;
- int num = Convert.ToInt32(value, 16);
- nuint uIntPtr = nuint.Zero;
- if (text.Contains("base") || text.Contains("main"))
- uIntPtr = (nuint)mainModule.BaseAddress + (nuint)num;
- else if (!text.Contains("base") && !text.Contains("main") && text.Contains('+'))
- {
- string[] array = text.Split('+');
- if (Modules.Count is 0 || !Modules.ContainsKey(array[0]))
- RefreshModules();
- Debug.WriteLine("module=" + array[0]);
- uIntPtr = (nuint)Modules[array[0]] + (nuint)num;
- }
- else
- uIntPtr = (nuint)num;
- return uIntPtr;
- }
- private nuint getCode(string name, string path, int size = 4)
- {
- string text = LoadCode(name, path);
- if (string.IsNullOrEmpty(text))
- return nuint.Zero;
- string[] elements = text.Split('+', ',');
- int[] offsets = new int[elements.Length];
- for (int i = 0; i < elements.Length; i++)
- offsets[i] = Convert.ToInt32(elements[i], 16);
- nuint baseAddress = nuint.Zero;
- if (text.Contains("base") || text.Contains("main"))
- baseAddress = (nuint)mainModule.BaseAddress;
- else if (!text.Contains("base") && !text.Contains("main") && text.Contains('+'))
- {
- string moduleName = elements[0];
- if (Modules.Count is 0 || !Modules.ContainsKey(moduleName))
- RefreshModules();
- baseAddress = (nuint)Modules[moduleName];
- }
- byte[] buffer = new byte[size];
- uint resultValue = 0;
- nuint resultAddress = baseAddress;
- for (int i = 0; i < offsets.Length; i++)
- {
- resultAddress += (nuint)offsets[i];
- _ = ReadProcessMemory(pHandle, resultAddress, buffer, (nuint)size, nint.Zero);
- resultValue = BitConverter.ToUInt32(buffer, 0);
- }
- return new nuint(resultValue);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement