├── README.md ├── wallhack.ahk └── classMemory.ahk /README.md: -------------------------------------------------------------------------------- 1 | # OBWH-AHK - Legal wallhack 2 | 3 | -------------------------------------------------------------------------------- /wallhack.ahk: -------------------------------------------------------------------------------- 1 | #Include classMemory.ahk 2 | 3 | setbatchlines -1 4 | Process, Wait, csgo.exe 5 | 6 | csgo := new _ClassMemory("ahk_exe csgo.exe", "", hProcess) 7 | if !IsObject(csgo) 8 | { 9 | if (hProcess = "") 10 | msgbox class memory not correctly installed. Or the (global class) variable "_ClassMemory" has been overwritten 11 | msgbox A_LastError %A_LastError% 12 | ExitApp 13 | } 14 | 15 | base := csgo.getModuleBaseAddress("client.dll") 16 | 17 | Pattern := [0x33, 0xC0, 0x83, 0xFA, "??", 0xB9, 0x20] 18 | 19 | address := csgo.modulePatternScan("client.dll", Pattern*) 20 | offsetwallhack := (address - base) + 4 21 | 22 | F10:: 23 | t := !t 24 | 25 | Data := t 26 | Size := 1 27 | 28 | VarSetCapacity(pBuffer, Size, 0) 29 | NumPut(Data, pBuffer, "Uchar") 30 | 31 | csgo.writeRaw(base + offsetwallhack, &pBuffer, Size) 32 | return 33 | -------------------------------------------------------------------------------- /classMemory.ahk: -------------------------------------------------------------------------------- 1 | /* 2 | A basic memory class by RHCP: 3 | This is a wrapper for commonly used read and write memory functions. 4 | It also contains a variety of pattern scan functions. 5 | This class allows scripts to read/write integers and strings of various types. 6 | Pointer addresses can easily be read/written by passing the base address and offsets to the various read/write functions. 7 | 8 | Process handles are kept open between reads. This increases speed. 9 | However, if a program closes/restarts then the process handle will become invalid 10 | and you will need to re-open another handle (blank/destroy the object and recreate it) 11 | isHandleValid() can be used to check if a handle is still active/valid. 12 | read(), readString(), write(), and writeString() can be used to read and write memory addresses respectively. 13 | readRaw() can be used to dump large chunks of memory, this is considerably faster when 14 | reading data from a large structure compared to repeated calls to read(). 15 | For example, reading a single UInt takes approximately the same amount of time as reading 1000 bytes via readRaw(). 16 | Although, most people wouldn't notice the performance difference. This does however require you 17 | to retrieve the values using AHK's numget()/strGet() from the dumped memory. 18 | In a similar fashion writeRaw() allows a buffer to be be written in a single operation. 19 | 20 | When the new operator is used this class returns an object which can be used to read that process's 21 | memory space.To read another process simply create another object. 22 | Process handles are automatically closed when the script exits/restarts or when you free the object. 23 | **Notes: 24 | This was initially written for 32 bit target processes, however the various read/write functions 25 | should now completely support pointers in 64 bit target applications. The only caveat is that the AHK exe must also be 64 bit. 26 | If AHK is 32 bit and the target application is 64 bit you can still read, write, and use pointers, so long as the addresses 27 | fit inside a 4 byte pointer, i.e. The maximum address is limited to the 32 bit range. 28 | The various pattern scan functions are intended to be used on 32 bit target applications, however: 29 | - A 32 bit AHK script can perform pattern scans on a 32 bit target application. 30 | - A 32 bit AHK script may be able to perform pattern scans on a 64 bit process, providing the addresses fall within the 32 bit range. 31 | - A 64 bit AHK script should be able to perform pattern scans on a 32 or 64 bit target application without issue. 32 | If the target process has admin privileges, then the AHK script will also require admin privileges. 33 | AHK doesn't support unsigned 64bit ints, you can however read them as Int64 and interpret negative values as large numbers. 34 | 35 | Commonly used methods: 36 | read() 37 | readString() 38 | readRaw() 39 | write() 40 | writeString() 41 | writeBytes() 42 | writeRaw() 43 | isHandleValid() 44 | getModuleBaseAddress() 45 | Less commonly used methods: 46 | getProcessBaseAddress() 47 | hexStringToPattern() 48 | stringToPattern() 49 | modulePatternScan() 50 | processPatternScan() 51 | addressPatternScan() 52 | rawPatternScan() 53 | getModules() 54 | numberOfBytesRead() 55 | numberOfBytesWritten() 56 | suspend() 57 | resume() 58 | Internal methods: (some may be useful when directly called) 59 | getAddressFromOffsets() ; Это вернет окончательный адрес памяти указателя. Это полезно, если указанный адрес изменяется только при запуске или изменении карты/уровня, и вы хотите устранить накладные расходы, связанные с указателями. 60 | isTargetProcess64Bit() 61 | pointer() 62 | GetModuleFileNameEx() 63 | EnumProcessModulesEx() 64 | GetModuleInformation() 65 | getNeedleFromAOBPattern() 66 | virtualQueryEx() 67 | patternScan() 68 | bufferScanForMaskedPattern() 69 | openProcess() 70 | closeHandle() 71 | Useful properties: (Не изменяйте значения этих свойств - они устанавливаются автоматически) 72 | baseAddress ; The base address of the target process 73 | hProcess ; The handle to the target process 74 | PID ; The PID of the target process 75 | currentProgram ; The string the user used to identify the target process e.g. "ahk_exe calc.exe" 76 | isTarget64bit ; True if target process is 64 bit, otherwise false 77 | readStringLastError ; Used to check for success/failure when reading a string 78 | Useful editable properties: 79 | insertNullTerminator ; Determines if a null terminator is inserted when writing strings. 80 | 81 | Usage: 82 | ; **Note: If you wish to try this calc example, consider using the 32 bit version of calc.exe - 83 | ; which is in C:\Windows\SysWOW64\calc.exe on win7 64 bit systems. 84 | ; The contents of this file can be copied directly into your script. Alternately, you can copy the classMemory.ahk file into your library folder, 85 | ; in which case you will need to use the #include directive in your script i.e. 86 | #Include 87 | 88 | ; You can use this code to check if you have installed the class correctly. 89 | if (_ClassMemory.__Class != "_ClassMemory") 90 | { 91 | msgbox class memory not correctly installed. Or the (global class) variable "_ClassMemory" has been overwritten 92 | ExitApp 93 | } 94 | ; Open a process with sufficient access to read and write memory addresses (this is required before you can use the other functions) 95 | ; You only need to do this once. But if the process closes/restarts, then you will need to perform this step again. Refer to the notes section below. 96 | ; Also, if the target process is running as admin, then the script will also require admin rights! 97 | ; Note: The program identifier can be any AHK windowTitle i.e.ahk_exe, ahk_class, ahk_pid, or simply the window title. 98 | ; hProcessCopy is an optional variable in which the opened handled is stored. 99 | 100 | calc := new _ClassMemory("ahk_exe calc.exe", "", hProcessCopy) 101 | 102 | ; Check if the above method was successful. 103 | if !isObject(calc) 104 | { 105 | msgbox failed to open a handle 106 | if (hProcessCopy = 0) 107 | msgbox The program isn't running (not found) or you passed an incorrect program identifier parameter. In some cases _ClassMemory.setSeDebugPrivilege() may be required. 108 | else if (hProcessCopy = "") 109 | msgbox OpenProcess failed. If the target process has admin rights, then the script also needs to be ran as admin. _ClassMemory.setSeDebugPrivilege() may also be required. Consult A_LastError for more information. 110 | ExitApp 111 | } 112 | ; Get the process's base address. 113 | ; When using the new operator this property is automatically set to the result of getModuleBaseAddress() or getProcessBaseAddress(); 114 | ; the specific method used depends on the bitness of the target application and AHK. 115 | ; If the returned address is incorrect and the target application is 64 bit, but AHK is 32 bit, try using the 64 bit version of AHK. 116 | msgbox % calc.BaseAddress 117 | 118 | ; Get the base address of a specific module. 119 | msgbox % calc.getModuleBaseAddress("GDI32.dll") 120 | ; The rest of these examples are just for illustration (the addresses specified are probably not valid). 121 | ; You can use cheat engine to find real addresses to read and write for testing purposes. 122 | 123 | ; Write 1234 as a UInt at address 0x0016CB60. 124 | calc.write(0x0016CB60, 1234, "UInt") 125 | ; Read a UInt. 126 | value := calc.read(0x0016CB60, "UInt") 127 | ; Read a pointer with offsets 0x20 and 0x15C which points to a UChar. 128 | value := calc.read(pointerBase, "UChar", 0x20, 0x15C) 129 | ; Note: read(), readString(), readRaw(), write(), writeString(), and writeRaw() all support pointers/offsets. 130 | ; An array of pointers can be passed directly, i.e. 131 | arrayPointerOffsets := [0x20, 0x15C] 132 | value := calc.read(pointerBase, "UChar", arrayPointerOffsets*) 133 | ; Or they can be entered manually. 134 | value := calc.read(pointerBase, "UChar", 0x20, 0x15C) 135 | ; You can also pass all the parameters directly, i.e. 136 | aMyPointer := [pointerBase, "UChar", 0x20, 0x15C] 137 | value := calc.read(aMyPointer*) 138 | 139 | ; Read a utf-16 null terminated string of unknown size at address 0x1234556 - the function will read until the null terminator is found or something goes wrong. 140 | string := calc.readString(0x1234556, length := 0, encoding := "utf-16") 141 | 142 | ; Read a utf-8 encoded string which is 12 bytes long at address 0x1234556. 143 | string := calc.readString(0x1234556, 12) 144 | ; By default a null terminator is included at the end of written strings for writeString(). 145 | ; The nullterminator property can be used to change this. 146 | _ClassMemory.insertNullTerminator := False ; This will change the property for all processes 147 | calc.insertNullTerminator := False ; Changes the property for just this process 148 | Notes: 149 | If the target process exits and then starts again (or restarts) you will need to free the derived object and then use the new operator to create a new object i.e. 150 | calc := [] ; or calc := "" ; free the object. This is actually optional if using the line below, as the line below would free the previous derived object calc prior to initialising the new copy. 151 | calc := new _ClassMemory("ahk_exe calc.exe") ; Create a new derived object to read calc's memory. 152 | isHandleValid() can be used to check if a target process has closed or restarted. 153 | */ 154 | 155 | class _ClassMemory 156 | { 157 | ; List of useful accessible values. Some of these inherited values (the non objects) are set when the new operator is used. 158 | static baseAddress, hProcess, PID, currentProgram 159 | , insertNullTerminator := True 160 | , readStringLastError := False 161 | , isTarget64bit := False 162 | , ptrType := "UInt" 163 | , aTypeSize := { "UChar": 1, "Char": 1 164 | , "UShort": 2, "Short": 2 165 | , "UInt": 4, "Int": 4 166 | , "UFloat": 4, "Float": 4 167 | , "Int64": 8, "Double": 8} 168 | , aRights := { "PROCESS_ALL_ACCESS": 0x001F0FFF 169 | , "PROCESS_CREATE_PROCESS": 0x0080 170 | , "PROCESS_CREATE_THREAD": 0x0002 171 | , "PROCESS_DUP_HANDLE": 0x0040 172 | , "PROCESS_QUERY_INFORMATION": 0x0400 173 | , "PROCESS_QUERY_LIMITED_INFORMATION": 0x1000 174 | , "PROCESS_SET_INFORMATION": 0x0200 175 | , "PROCESS_SET_QUOTA": 0x0100 176 | , "PROCESS_SUSPEND_RESUME": 0x0800 177 | , "PROCESS_TERMINATE": 0x0001 178 | , "PROCESS_VM_OPERATION": 0x0008 179 | , "PROCESS_VM_READ": 0x0010 180 | , "PROCESS_VM_WRITE": 0x0020 181 | , "SYNCHRONIZE": 0x00100000} 182 | 183 | 184 | ; Method: __new(program, dwDesiredAccess := "", byRef handle := "", windowMatchMode := 3) 185 | ; Example: derivedObject := new _ClassMemory("ahk_exe calc.exe") 186 | ; This is the first method which should be called when trying to access a program's memory. 187 | ; If the process is successfully opened, an object is returned which can be used to read that processes memory space. 188 | ; [derivedObject].hProcess stores the opened handle. 189 | ; If the target process closes and re-opens, simply free the derived object and use the new operator again to open a new handle. 190 | ; Parameters: 191 | ; program The program to be opened. This can be any AHK windowTitle identifier, such as 192 | ; ahk_exe, ahk_class, ahk_pid, or simply the window title. e.g. "ahk_exe calc.exe" or "Calculator". 193 | ; It's safer not to use the window title, as some things can have the same window title e.g. an open folder called "Starcraft II" 194 | ; would have the same window title as the game itself. 195 | ; *'DetectHiddenWindows, On' is required for hidden windows* 196 | ; dwDesiredAccess The access rights requested when opening the process. 197 | ; If this parameter is null the process will be opened with the following rights 198 | ; PROCESS_QUERY_INFORMATION, PROCESS_VM_OPERATION, PROCESS_VM_READ, PROCESS_VM_WRITE, & SYNCHRONIZE 199 | ; This access level is sufficient to allow all of the methods in this class to work. 200 | ; Specific process access rights are listed here http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx 201 | ; handle (Output) Optional variable in which a copy of the opened processes handle will be stored. 202 | ; Values: 203 | ; Null OpenProcess failed. The script may need to be run with admin rights admin, 204 | ; and/or with the use of _ClassMemory.setSeDebugPrivilege(). Consult A_LastError for more information. 205 | ; 0 The program isn't running (not found) or you passed an incorrect program identifier parameter. 206 | ; In some cases _ClassMemory.setSeDebugPrivilege() may be required. 207 | ; Positive Integer A handle to the process. (Success) 208 | ; windowMatchMode - Determines the matching mode used when finding the program (windowTitle). 209 | ; The default value is 3 i.e. an exact match. Refer to AHK's setTitleMathMode for more information. 210 | ; Return Values: 211 | ; Object On success an object is returned which can be used to read the processes memory. 212 | ; Null Failure. A_LastError and the optional handle parameter can be consulted for more information. 213 | 214 | 215 | __new(program, dwDesiredAccess := "", byRef handle := "", windowMatchMode := 3) 216 | { 217 | if this.PID := handle := this.findPID(program, windowMatchMode) ; set handle to 0 if program not found 218 | { 219 | ; This default access level is sufficient to read and write memory addresses, and to perform pattern scans. 220 | ; if the program is run using admin privileges, then this script will also need admin privileges 221 | if dwDesiredAccess is not integer 222 | dwDesiredAccess := this.aRights.PROCESS_QUERY_INFORMATION | this.aRights.PROCESS_VM_OPERATION | this.aRights.PROCESS_VM_READ | this.aRights.PROCESS_VM_WRITE 223 | dwDesiredAccess |= this.aRights.SYNCHRONIZE ; add SYNCHRONIZE to all handles to allow isHandleValid() to work 224 | 225 | if this.hProcess := handle := this.OpenProcess(this.PID, dwDesiredAccess) ; NULL/Blank if failed to open process for some reason 226 | { 227 | this.pNumberOfBytesRead := DllCall("GlobalAlloc", "UInt", 0x0040, "Ptr", A_PtrSize, "Ptr") ; 0x0040 initialise to 0 228 | this.pNumberOfBytesWritten := DllCall("GlobalAlloc", "UInt", 0x0040, "Ptr", A_PtrSize, "Ptr") ; initialise to 0 229 | 230 | this.readStringLastError := False 231 | this.currentProgram := program 232 | if this.isTarget64bit := this.isTargetProcess64Bit(this.PID, this.hProcess, dwDesiredAccess) 233 | this.ptrType := "Int64" 234 | else this.ptrType := "UInt" ; If false or Null (fails) assume 32bit 235 | 236 | ; if script is 64 bit, getModuleBaseAddress() should always work 237 | ; if target app is truly 32 bit, then getModuleBaseAddress() 238 | ; will work when script is 32 bit 239 | if (A_PtrSize != 4 || !this.isTarget64bit) 240 | this.BaseAddress := this.getModuleBaseAddress() 241 | 242 | ; If the above failed or wasn't called, fall back to alternate method 243 | if this.BaseAddress < 0 || !this.BaseAddress 244 | this.BaseAddress := this.getProcessBaseAddress(program, windowMatchMode) 245 | 246 | return this 247 | } 248 | } 249 | return 250 | } 251 | 252 | __delete() 253 | { 254 | this.closeHandle(this.hProcess) 255 | if this.pNumberOfBytesRead 256 | DllCall("GlobalFree", "Ptr", this.pNumberOfBytesRead) 257 | if this.pNumberOfBytesWritten 258 | DllCall("GlobalFree", "Ptr", this.pNumberOfBytesWritten) 259 | return 260 | } 261 | 262 | version() 263 | { 264 | return 2.92 265 | } 266 | 267 | findPID(program, windowMatchMode := "3") 268 | { 269 | ; If user passes an AHK_PID, don't bother searching. There are cases where searching windows for PIDs 270 | ; wont work - console apps 271 | if RegExMatch(program, "i)\s*AHK_PID\s+(0x[[:xdigit:]]+|\d+)", pid) 272 | return pid1 273 | if windowMatchMode 274 | { 275 | ; This is a string and will not contain the 0x prefix 276 | mode := A_TitleMatchMode 277 | ; remove hex prefix as SetTitleMatchMode will throw a run time error. This will occur if integer mode is set to hex and user passed an int (unquoted) 278 | StringReplace, windowMatchMode, windowMatchMode, 0x 279 | SetTitleMatchMode, %windowMatchMode% 280 | } 281 | WinGet, pid, pid, %program% 282 | if windowMatchMode 283 | SetTitleMatchMode, %mode% ; In case executed in autoexec 284 | 285 | ; If use 'ahk_exe test.exe' and winget fails (which can happen when setSeDebugPrivilege is required), 286 | ; try using the process command. When it fails due to setSeDebugPrivilege, setSeDebugPrivilege will still be required to openProcess 287 | ; This should also work for apps without windows. 288 | if (!pid && RegExMatch(program, "i)\bAHK_EXE\b\s*(.*)", fileName)) 289 | { 290 | ; remove any trailing AHK_XXX arguments 291 | filename := RegExReplace(filename1, "i)\bahk_(class|id|pid|group)\b.*", "") 292 | filename := trim(filename) ; extra spaces will make process command fail 293 | ; AHK_EXE can be the full path, so just get filename 294 | SplitPath, fileName , fileName 295 | if (fileName) ; if filename blank, scripts own pid is returned 296 | { 297 | process, Exist, %fileName% 298 | pid := ErrorLevel 299 | } 300 | } 301 | 302 | return pid ? pid : 0 ; PID is null on fail, return 0 303 | } 304 | ; Method: isHandleValid() 305 | ; This method provides a means to check if the internal process handle is still valid 306 | ; or in other words, the specific target application instance (which you have been reading from) 307 | ; has closed or restarted. 308 | ; For example, if the target application closes or restarts the handle will become invalid 309 | ; and subsequent calls to this method will return false. 310 | ; 311 | ; Return Values: 312 | ; True The handle is valid. 313 | ; False The handle is not valid. 314 | ; 315 | ; Notes: 316 | ; This operation requires a handle with SYNCHRONIZE access rights. 317 | ; All handles, even user specified ones are opened with the SYNCHRONIZE access right. 318 | 319 | isHandleValid() 320 | { 321 | return 0x102 = DllCall("WaitForSingleObject", "Ptr", this.hProcess, "UInt", 0) 322 | ; WaitForSingleObject return values 323 | ; -1 if called with null hProcess (sets lastError to 6 - invalid handle) 324 | ; 258 / 0x102 WAIT_TIMEOUT - if handle is valid (process still running) 325 | ; 0 WAIT_OBJECT_0 - if process has terminated 326 | } 327 | 328 | ; Method: openProcess(PID, dwDesiredAccess) 329 | ; ***Note: This is an internal method which shouldn't be called directly unless you absolutely know what you are doing. 330 | ; This is because the new operator, in addition to calling this method also sets other values 331 | ; which are required for the other methods to work correctly. 332 | ; Parameters: 333 | ; PID The Process ID of the target process. 334 | ; dwDesiredAccess The access rights requested when opening the process. 335 | ; Specific process access rights are listed here http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx 336 | ; Return Values: 337 | ; Null/blank OpenProcess failed. If the target process has admin rights, then the script also needs to be ran as admin. 338 | ; _ClassMemory.setSeDebugPrivilege() may also be required. 339 | ; Positive integer A handle to the process. 340 | 341 | openProcess(PID, dwDesiredAccess) 342 | { 343 | r := DllCall("OpenProcess", "UInt", dwDesiredAccess, "Int", False, "UInt", PID, "Ptr") 344 | ; if it fails with 0x5 ERROR_ACCESS_DENIED, try enabling privilege ... lots of users never try this. 345 | ; there may be other errors which also require DebugPrivilege.... 346 | if (!r && A_LastError = 5) 347 | { 348 | this.setSeDebugPrivilege(true) ; no harm in enabling it if it is already enabled by user 349 | if (r2 := DllCall("OpenProcess", "UInt", dwDesiredAccess, "Int", False, "UInt", PID, "Ptr")) 350 | return r2 351 | DllCall("SetLastError", "UInt", 5) ; restore original error if it doesnt work 352 | } 353 | ; If fails with 0x5 ERROR_ACCESS_DENIED (when setSeDebugPrivilege() is req.), the func. returns 0 rather than null!! Set it to null. 354 | ; If fails for another reason, then it is null. 355 | return r ? r : "" 356 | } 357 | 358 | ; Method: closeHandle(hProcess) 359 | ; Note: This is an internal method which is automatically called when the script exits or the derived object is freed/destroyed. 360 | ; There is no need to call this method directly. If you wish to close the handle simply free the derived object. 361 | ; i.e. derivedObject := [] ; or derivedObject := "" 362 | ; Parameters: 363 | ; hProcess The handle to the process, as returned by openProcess(). 364 | ; Return Values: 365 | ; Non-Zero Success 366 | ; 0 Failure 367 | 368 | closeHandle(hProcess) 369 | { 370 | return DllCall("CloseHandle", "Ptr", hProcess) 371 | } 372 | 373 | ; Methods: numberOfBytesRead() / numberOfBytesWritten() 374 | ; Returns the number of bytes read or written by the last ReadProcessMemory or WriteProcessMemory operation. 375 | ; 376 | ; Return Values: 377 | ; zero or positive value Number of bytes read/written 378 | ; -1 Failure. Shouldn't occur 379 | 380 | numberOfBytesRead() 381 | { 382 | return !this.pNumberOfBytesRead ? -1 : NumGet(this.pNumberOfBytesRead+0, "Ptr") 383 | } 384 | numberOfBytesWritten() 385 | { 386 | return !this.pNumberOfBytesWritten ? -1 : NumGet(this.pNumberOfBytesWritten+0, "Ptr") 387 | } 388 | 389 | 390 | ; Method: read(address, type := "UInt", aOffsets*) 391 | ; Reads various integer type values 392 | ; Parameters: 393 | ; address - The memory address of the value or if using the offset parameter, 394 | ; the base address of the pointer. 395 | ; type - The integer type. 396 | ; Valid types are UChar, Char, UShort, Short, UInt, Int, Float, Int64 and Double. 397 | ; Note: Types must not contain spaces i.e. " UInt" or "UInt " will not work. 398 | ; When an invalid type is passed the method returns NULL and sets ErrorLevel to -2 399 | ; aOffsets* - A variadic list of offsets. When using offsets the address parameter should equal the base address of the pointer. 400 | ; The address (base address) and offsets should point to the memory address which holds the integer. 401 | ; Return Values: 402 | ; integer - Indicates success. 403 | ; Null - Indicates failure. Check ErrorLevel and A_LastError for more information. 404 | ; Note: Since the returned integer value may be 0, to check for success/failure compare the result 405 | ; against null i.e. if (result = "") then an error has occurred. 406 | ; When reading doubles, adjusting "SetFormat, float, totalWidth.DecimalPlaces" 407 | ; may be required depending on your requirements. 408 | 409 | read(address, type := "UInt", aOffsets*) 410 | { 411 | ; If invalid type RPM() returns success (as bytes to read resolves to null in dllCall()) 412 | ; so set errorlevel to invalid parameter for DLLCall() i.e. -2 413 | if !this.aTypeSize.hasKey(type) 414 | return "", ErrorLevel := -2 415 | if DllCall("ReadProcessMemory", "Ptr", this.hProcess, "Ptr", aOffsets.maxIndex() ? this.getAddressFromOffsets(address, aOffsets*) : address, type "*", result, "Ptr", this.aTypeSize[type], "Ptr", this.pNumberOfBytesRead) 416 | return result 417 | return 418 | } 419 | 420 | ; Method: readRaw(address, byRef buffer, bytes := 4, aOffsets*) 421 | ; Reads an area of the processes memory and stores it in the buffer variable 422 | ; Parameters: 423 | ; address - The memory address of the area to read or if using the offsets parameter 424 | ; the base address of the pointer which points to the memory region. 425 | ; buffer - The unquoted variable name for the buffer. This variable will receive the contents from the address space. 426 | ; This method calls varsetCapcity() to ensure the variable has an adequate size to perform the operation. 427 | ; If the variable already has a larger capacity (from a previous call to varsetcapcity()), then it will not be shrunk. 428 | ; Therefore it is the callers responsibility to ensure that any subsequent actions performed on the buffer variable 429 | ; do not exceed the bytes which have been read - as these remaining bytes could contain anything. 430 | ; bytes - The number of bytes to be read. 431 | ; aOffsets* - A variadic list of offsets. When using offsets the address parameter should equal the base address of the pointer. 432 | ; The address (base address) and offsets should point to the memory address which is to be read 433 | ; Return Values: 434 | ; Non Zero - Indicates success. 435 | ; Zero - Indicates failure. Check errorLevel and A_LastError for more information 436 | ; 437 | ; Notes: The contents of the buffer may then be retrieved using AHK's NumGet() and StrGet() functions. 438 | ; This method offers significant (~30% and up) performance boost when reading large areas of memory. 439 | ; As calling ReadProcessMemory for four bytes takes a similar amount of time as it does for 1,000 bytes. 440 | 441 | readRaw(address, byRef buffer, bytes := 4, aOffsets*) 442 | { 443 | VarSetCapacity(buffer, bytes) 444 | return DllCall("ReadProcessMemory", "Ptr", this.hProcess, "Ptr", aOffsets.maxIndex() ? this.getAddressFromOffsets(address, aOffsets*) : address, "Ptr", &buffer, "Ptr", bytes, "Ptr", this.pNumberOfBytesRead) 445 | } 446 | 447 | ; Method: readString(address, sizeBytes := 0, encoding := "utf-8", aOffsets*) 448 | ; Reads string values of various encoding types 449 | ; Parameters: 450 | ; address - The memory address of the value or if using the offset parameter, 451 | ; the base address of the pointer. 452 | ; sizeBytes - The size (in bytes) of the string to be read. 453 | ; If zero is passed, then the function will read each character until a null terminator is found 454 | ; and then returns the entire string. 455 | ; encoding - This refers to how the string is stored in the program's memory. 456 | ; UTF-8 and UTF-16 are common. Refer to the AHK manual for other encoding types. 457 | ; aOffsets* - A variadic list of offsets. When using offsets the address parameter should equal the base address of the pointer. 458 | ; The address (base address) and offsets should point to the memory address which holds the string. 459 | ; 460 | ; Return Values: 461 | ; String - On failure an empty (null) string is always returned. Since it's possible for the actual string 462 | ; being read to be null (empty), then a null return value should not be used to determine failure of the method. 463 | ; Instead the property [derivedObject].ReadStringLastError can be used to check for success/failure. 464 | ; This property is set to 0 on success and 1 on failure. On failure ErrorLevel and A_LastError should be consulted 465 | ; for more information. 466 | ; Notes: 467 | ; For best performance use the sizeBytes parameter to specify the exact size of the string. 468 | ; If the exact size is not known and the string is null terminated, then specifying the maximum 469 | ; possible size of the string will yield the same performance. 470 | ; If neither the actual or maximum size is known and the string is null terminated, then specifying 471 | ; zero for the sizeBytes parameter is fine. Generally speaking for all intents and purposes the performance difference is 472 | ; inconsequential. 473 | 474 | readString(address, sizeBytes := 0, encoding := "UTF-8", aOffsets*) 475 | { 476 | bufferSize := VarSetCapacity(buffer, sizeBytes ? sizeBytes : 100, 0) 477 | this.ReadStringLastError := False 478 | if aOffsets.maxIndex() 479 | address := this.getAddressFromOffsets(address, aOffsets*) 480 | if !sizeBytes ; read until null terminator is found or something goes wrong 481 | { 482 | ; Even if there are multi-byte-characters (bigger than the encodingSize i.e. surrogates) in the string, when reading in encodingSize byte chunks they will never register as null (as they will have bits set on those bytes) 483 | if (encoding = "utf-16" || encoding = "cp1200") 484 | encodingSize := 2, charType := "UShort", loopCount := 2 485 | else encodingSize := 1, charType := "Char", loopCount := 4 486 | Loop 487 | { ; Lets save a few reads by reading in 4 byte chunks 488 | if !DllCall("ReadProcessMemory", "Ptr", this.hProcess, "Ptr", address + ((outterIndex := A_index) - 1) * 4, "Ptr", &buffer, "Ptr", 4, "Ptr", this.pNumberOfBytesRead) || ErrorLevel 489 | return "", this.ReadStringLastError := True 490 | else loop, %loopCount% 491 | { 492 | if NumGet(buffer, (A_Index - 1) * encodingSize, charType) = 0 ; NULL terminator 493 | { 494 | if (bufferSize < sizeBytes := outterIndex * 4 - (4 - A_Index * encodingSize)) 495 | VarSetCapacity(buffer, sizeBytes) 496 | break, 2 497 | } 498 | } 499 | } 500 | } 501 | if DllCall("ReadProcessMemory", "Ptr", this.hProcess, "Ptr", address, "Ptr", &buffer, "Ptr", sizeBytes, "Ptr", this.pNumberOfBytesRead) 502 | return StrGet(&buffer,, encoding) 503 | return "", this.ReadStringLastError := True 504 | } 505 | 506 | ; Method: writeString(address, string, encoding := "utf-8", aOffsets*) 507 | ; Encodes and then writes a string to the process. 508 | ; Parameters: 509 | ; address - The memory address to which data will be written or if using the offset parameter, 510 | ; the base address of the pointer. 511 | ; string - The string to be written. 512 | ; encoding - This refers to how the string is to be stored in the program's memory. 513 | ; UTF-8 and UTF-16 are common. Refer to the AHK manual for other encoding types. 514 | ; aOffsets* - A variadic list of offsets. When using offsets the address parameter should equal the base address of the pointer. 515 | ; The address (base address) and offsets should point to the memory address which is to be written to. 516 | ; Return Values: 517 | ; Non Zero - Indicates success. 518 | ; Zero - Indicates failure. Check errorLevel and A_LastError for more information 519 | ; Notes: 520 | ; By default a null terminator is included at the end of written strings. 521 | ; This behaviour is determined by the property [derivedObject].insertNullTerminator 522 | ; If this property is true, then a null terminator will be included. 523 | 524 | writeString(address, string, encoding := "utf-8", aOffsets*) 525 | { 526 | encodingSize := (encoding = "utf-16" || encoding = "cp1200") ? 2 : 1 527 | requiredSize := StrPut(string, encoding) * encodingSize - (this.insertNullTerminator ? 0 : encodingSize) 528 | VarSetCapacity(buffer, requiredSize) 529 | StrPut(string, &buffer, StrLen(string) + (this.insertNullTerminator ? 1 : 0), encoding) 530 | return DllCall("WriteProcessMemory", "Ptr", this.hProcess, "Ptr", aOffsets.maxIndex() ? this.getAddressFromOffsets(address, aOffsets*) : address, "Ptr", &buffer, "Ptr", requiredSize, "Ptr", this.pNumberOfBytesWritten) 531 | } 532 | 533 | ; Method: write(address, value, type := "Uint", aOffsets*) 534 | ; Writes various integer type values to the process. 535 | ; Parameters: 536 | ; address - The memory address to which data will be written or if using the offset parameter, 537 | ; the base address of the pointer. 538 | ; type - The integer type. 539 | ; Valid types are UChar, Char, UShort, Short, UInt, Int, Float, Int64 and Double. 540 | ; Note: Types must not contain spaces i.e. " UInt" or "UInt " will not work. 541 | ; When an invalid type is passed the method returns NULL and sets ErrorLevel to -2 542 | ; aOffsets* - A variadic list of offsets. When using offsets the address parameter should equal the base address of the pointer. 543 | ; The address (base address) and offsets should point to the memory address which is to be written to. 544 | ; Return Values: 545 | ; Non Zero - Indicates success. 546 | ; Zero - Indicates failure. Check errorLevel and A_LastError for more information 547 | ; Null - An invalid type was passed. Errorlevel is set to -2 548 | 549 | write(address, value, type := "Uint", aOffsets*) 550 | { 551 | if !this.aTypeSize.hasKey(type) 552 | return "", ErrorLevel := -2 553 | return DllCall("WriteProcessMemory", "Ptr", this.hProcess, "Ptr", aOffsets.maxIndex() ? this.getAddressFromOffsets(address, aOffsets*) : address, type "*", value, "Ptr", this.aTypeSize[type], "Ptr", this.pNumberOfBytesWritten) 554 | } 555 | 556 | ; Method: writeRaw(address, pBuffer, sizeBytes, aOffsets*) 557 | ; Writes a buffer to the process. 558 | ; Parameters: 559 | ; address - The memory address to which the contents of the buffer will be written 560 | ; or if using the offset parameter, the base address of the pointer. 561 | ; pBuffer - A pointer to the buffer which is to be written. 562 | ; This does not necessarily have to be the beginning of the buffer itself e.g. pBuffer := &buffer + offset 563 | ; sizeBytes - The number of bytes which are to be written from the buffer. 564 | ; aOffsets* - A variadic list of offsets. When using offsets the address parameter should equal the base address of the pointer. 565 | ; The address (base address) and offsets should point to the memory address which is to be written to. 566 | ; Return Values: 567 | ; Non Zero - Indicates success. 568 | ; Zero - Indicates failure. Check errorLevel and A_LastError for more information 569 | 570 | writeRaw(address, pBuffer, sizeBytes, aOffsets*) 571 | { 572 | return DllCall("WriteProcessMemory", "Ptr", this.hProcess, "Ptr", aOffsets.maxIndex() ? this.getAddressFromOffsets(address, aOffsets*) : address, "Ptr", pBuffer, "Ptr", sizeBytes, "Ptr", this.pNumberOfBytesWritten) 573 | } 574 | 575 | ; Method: writeBytes(address, hexStringOrByteArray, aOffsets*) 576 | ; Writes a sequence of byte values to the process. 577 | ; Parameters: 578 | ; address - The memory address to where the bytes will be written 579 | ; or if using the offset parameter, the base address of the pointer. 580 | ; hexStringOrByteArray - This can either be either a string (A) or an object/array (B) containing the values to be written. 581 | ; 582 | ; A) HexString - A string of hex bytes. The '0x' hex prefix is optional. 583 | ; Bytes can optionally be separated using the space or tab characters. 584 | ; Each byte must be two characters in length i.e. '04' or '0x04' (not '4' or '0x4') 585 | ; B) Object/Array - An array containing hex or decimal byte values e.g. array := [10, 29, 0xA] 586 | ; 587 | ; aOffsets* - A variadic list of offsets. When using offsets the address parameter should equal the base address of the pointer. 588 | ; The address (base address) and offsets should point to the memory address which is to be written to. 589 | ; Return Values: 590 | ; -1, -2, -3, -4 - Error with the hexstring. Refer to hexStringToPattern() for details. 591 | ; Other Non Zero - Indicates success. 592 | ; Zero - Indicates write failure. Check errorLevel and A_LastError for more information 593 | ; 594 | ; Examples: 595 | ; writeBytes(0xAABBCC11, "DEADBEEF") ; Writes the bytes DE AD BE EF starting at address 0xAABBCC11 596 | ; writeBytes(0xAABBCC11, [10, 20, 0xA, 2]) 597 | 598 | writeBytes(address, hexStringOrByteArray, aOffsets*) 599 | { 600 | if !IsObject(hexStringOrByteArray) 601 | { 602 | if !IsObject(hexStringOrByteArray := this.hexStringToPattern(hexStringOrByteArray)) 603 | return hexStringOrByteArray 604 | } 605 | sizeBytes := this.getNeedleFromAOBPattern("", buffer, hexStringOrByteArray*) 606 | return this.writeRaw(address, &buffer, sizeBytes, aOffsets*) 607 | } 608 | 609 | ; Method: pointer(address, finalType := "UInt", offsets*) 610 | ; This is an internal method. Since the other various methods all offer this functionality, they should be used instead. 611 | ; This will read integer values of both pointers and non-pointers (i.e. a single memory address) 612 | ; Parameters: 613 | ; address - The base address of the pointer or the memory address for a non-pointer. 614 | ; finalType - The type of integer stored at the final address. 615 | ; Valid types are UChar, Char, UShort, Short, UInt, Int, Float, Int64 and Double. 616 | ; Note: Types must not contain spaces i.e. " UInt" or "UInt " will not work. 617 | ; When an invalid type is passed the method returns NULL and sets ErrorLevel to -2 618 | ; aOffsets* - A variadic list of offsets used to calculate the pointers final address. 619 | ; Return Values: (The same as the read() method) 620 | ; integer - Indicates success. 621 | ; Null - Indicates failure. Check ErrorLevel and A_LastError for more information. 622 | ; Note: Since the returned integer value may be 0, to check for success/failure compare the result 623 | ; against null i.e. if (result = "") then an error has occurred. 624 | ; If the target application is 64bit the pointers are read as an 8 byte Int64 (this.PtrType) 625 | 626 | pointer(address, finalType := "UInt", offsets*) 627 | { 628 | For index, offset in offsets 629 | address := this.Read(address, this.ptrType) + offset 630 | Return this.Read(address, finalType) 631 | } 632 | 633 | ; Method: getAddressFromOffsets(address, aOffsets*) 634 | ; Returns the final address of a pointer. 635 | ; This is an internal method used by various methods however, this method may be useful if you are 636 | ; looking to eliminate the overhead overhead associated with reading pointers which only change 637 | ; on startup or map/level change. In other words you can cache the final address and 638 | ; read from this address directly. 639 | ; Parameters: 640 | ; address The base address of the pointer. 641 | ; aOffsets* A variadic list of offsets used to calculate the pointers final address. 642 | ; At least one offset must be present. 643 | ; Return Values: 644 | ; Positive integer The final memory address pointed to by the pointer. 645 | ; Negative integer Failure 646 | ; Null Failure 647 | ; Note: If the target application is 64bit the pointers are read as an 8 byte Int64 (this.PtrType) 648 | 649 | getAddressFromOffsets(address, aOffsets*) 650 | { 651 | return aOffsets.Remove() + this.pointer(address, this.ptrType, aOffsets*) ; remove the highest key so can use pointer() to find final memory address (minus the last offset) 652 | } 653 | 654 | ; Interesting note: 655 | ; Although handles are 64-bit pointers, only the less significant 32 bits are employed in them for the purpose 656 | ; of better compatibility (for example, to enable 32-bit and 64-bit processes interact with each other) 657 | ; Here are examples of such types: HANDLE, HWND, HMENU, HPALETTE, HBITMAP, etc. 658 | ; http://www.viva64.com/en/k/0005/ 659 | 660 | 661 | 662 | ; Method: getProcessBaseAddress(WindowTitle, windowMatchMode := 3) 663 | ; Returns the base address of a process. In most cases this will provide the same result as calling getModuleBaseAddress() (when passing 664 | ; a null value as the module parameter), however getProcessBaseAddress() will usually work regardless of the bitness 665 | ; of both the AHK exe and the target process. 666 | ; *This method relies on the target process having a window and will not work for console apps* 667 | ; *'DetectHiddenWindows, On' is required for hidden windows* 668 | ; ***If this returns an incorrect value, try using (the MORE RELIABLE) getModuleBaseAddress() instead.*** 669 | ; Parameters: 670 | ; windowTitle This can be any AHK windowTitle identifier, such as 671 | ; ahk_exe, ahk_class, ahk_pid, or simply the window title. e.g. "ahk_exe calc.exe" or "Calculator". 672 | ; It's safer not to use the window title, as some things can have the same window title e.g. an open folder called "Starcraft II" 673 | ; would have the same window title as the game itself. 674 | ; windowMatchMode Determines the matching mode used when finding the program's window (windowTitle). 675 | ; The default value is 3 i.e. an exact match. The current matchmode will be used if the parameter is null or 0. 676 | ; Refer to AHK's setTitleMathMode for more information. 677 | ; Return Values: 678 | ; Positive integer The base address of the process (success). 679 | ; Null The process's window couldn't be found. 680 | ; 0 The GetWindowLong or GetWindowLongPtr call failed. Try getModuleBaseAddress() instead. 681 | 682 | 683 | getProcessBaseAddress(windowTitle, windowMatchMode := "3") 684 | { 685 | if (windowMatchMode && A_TitleMatchMode != windowMatchMode) 686 | { 687 | mode := A_TitleMatchMode ; This is a string and will not contain the 0x prefix 688 | StringReplace, windowMatchMode, windowMatchMode, 0x ; remove hex prefix as SetTitleMatchMode will throw a run time error. This will occur if integer mode is set to hex and matchmode param is passed as an number not a string. 689 | SetTitleMatchMode, %windowMatchMode% ;mode 3 is an exact match 690 | } 691 | WinGet, hWnd, ID, %WindowTitle% 692 | if mode 693 | SetTitleMatchMode, %mode% ; In case executed in autoexec 694 | if !hWnd 695 | return ; return blank failed to find window 696 | ; GetWindowLong returns a Long (Int) and GetWindowLongPtr return a Long_Ptr 697 | return DllCall(A_PtrSize = 4 ; If DLL call fails, returned value will = 0 698 | ? "GetWindowLong" 699 | : "GetWindowLongPtr" 700 | , "Ptr", hWnd, "Int", -6, A_Is64bitOS ? "Int64" : "UInt") 701 | ; For the returned value when the OS is 64 bit use Int64 to prevent negative overflow when AHK is 32 bit and target process is 64bit 702 | ; however if the OS is 32 bit, must use UInt, otherwise the number will be huge (however it will still work as the lower 4 bytes are correct) 703 | ; Note - it's the OS bitness which matters here, not the scripts/AHKs 704 | } 705 | 706 | ; http://winprogger.com/getmodulefilenameex-enumprocessmodulesex-failures-in-wow64/ 707 | ; http://stackoverflow.com/questions/3801517/how-to-enum-modules-in-a-64bit-process-from-a-32bit-wow-process 708 | 709 | ; Method: getModuleBaseAddress(module := "", byRef aModuleInfo := "") 710 | ; Parameters: 711 | ; moduleName - The file name of the module/dll to find e.g. "calc.exe", "GDI32.dll", "Bass.dll" etc 712 | ; If no module (null) is specified, the address of the base module - main()/process will be returned 713 | ; e.g. for calc.exe the following two method calls are equivalent getModuleBaseAddress() and getModuleBaseAddress("calc.exe") 714 | ; aModuleInfo - (Optional) A module Info object is returned in this variable. If method fails this variable is made blank. 715 | ; This object contains the keys: name, fileName, lpBaseOfDll, SizeOfImage, and EntryPoint 716 | ; Return Values: 717 | ; Positive integer - The module's base/load address (success). 718 | ; -1 - Module not found 719 | ; -3 - EnumProcessModulesEx failed 720 | ; -4 - The AHK script is 32 bit and you are trying to access the modules of a 64 bit target process. Or the target process has been closed. 721 | ; Notes: A 64 bit AHK can enumerate the modules of a target 64 or 32 bit process. 722 | ; A 32 bit AHK can only enumerate the modules of a 32 bit process 723 | ; This method requires PROCESS_QUERY_INFORMATION + PROCESS_VM_READ access rights. These are included by default with this class. 724 | 725 | getModuleBaseAddress(moduleName := "", byRef aModuleInfo := "") 726 | { 727 | aModuleInfo := "" 728 | if (moduleName = "") 729 | moduleName := this.GetModuleFileNameEx(0, True) ; main executable module of the process - get just fileName no path 730 | if r := this.getModules(aModules, True) < 0 731 | return r ; -4, -3 732 | return aModules.HasKey(moduleName) ? (aModules[moduleName].lpBaseOfDll, aModuleInfo := aModules[moduleName]) : -1 733 | ; no longer returns -5 for failed to get module info 734 | } 735 | 736 | 737 | ; Method: getModuleFromAddress(address, byRef aModuleInfo) 738 | ; Finds the module in which the address resides. 739 | ; Parameters: 740 | ; address The address of interest. 741 | ; 742 | ; aModuleInfo (Optional) An unquoted variable name. If the module associated with the address is found, 743 | ; a moduleInfo object will be stored in this variable. This object has the 744 | ; following keys: name, fileName, lpBaseOfDll, SizeOfImage, and EntryPoint. 745 | ; If the address is not found to reside inside a module, the passed variable is 746 | ; made blank/null. 747 | ; offsetFromModuleBase (Optional) Stores the relative offset from the module base address 748 | ; to the specified address. If the method fails then the passed variable is set to blank/empty. 749 | ; Return Values: 750 | ; 1 Success - The address is contained within a module. 751 | ; -1 The specified address does not reside within a loaded module. 752 | ; -3 EnumProcessModulesEx failed. 753 | ; -4 The AHK script is 32 bit and you are trying to access the modules of a 64 bit target process. 754 | 755 | getModuleFromAddress(address, byRef aModuleInfo, byRef offsetFromModuleBase := "") 756 | { 757 | aModuleInfo := offsetFromModule := "" 758 | if result := this.getmodules(aModules) < 0 759 | return result ; error -3, -4 760 | for k, module in aModules 761 | { 762 | if (address >= module.lpBaseOfDll && address < module.lpBaseOfDll + module.SizeOfImage) 763 | return 1, aModuleInfo := module, offsetFromModuleBase := address - module.lpBaseOfDll 764 | } 765 | return -1 766 | } 767 | 768 | ; SeDebugPrivileges is required to read/write memory in some programs. 769 | ; This only needs to be called once when the script starts, 770 | ; regardless of the number of programs being read (or if the target programs restart) 771 | ; Call this before attempting to call any other methods in this class 772 | ; i.e. call _ClassMemory.setSeDebugPrivilege() at the very start of the script. 773 | 774 | setSeDebugPrivilege(enable := True) 775 | { 776 | h := DllCall("OpenProcess", "UInt", 0x0400, "Int", false, "UInt", DllCall("GetCurrentProcessId"), "Ptr") 777 | ; Open an adjustable access token with this process (TOKEN_ADJUST_PRIVILEGES = 32) 778 | DllCall("Advapi32.dll\OpenProcessToken", "Ptr", h, "UInt", 32, "PtrP", t) 779 | VarSetCapacity(ti, 16, 0) ; structure of privileges 780 | NumPut(1, ti, 0, "UInt") ; one entry in the privileges array... 781 | ; Retrieves the locally unique identifier of the debug privilege: 782 | DllCall("Advapi32.dll\LookupPrivilegeValue", "Ptr", 0, "Str", "SeDebugPrivilege", "Int64P", luid) 783 | NumPut(luid, ti, 4, "Int64") 784 | if enable 785 | NumPut(2, ti, 12, "UInt") ; enable this privilege: SE_PRIVILEGE_ENABLED = 2 786 | ; Update the privileges of this process with the new access token: 787 | r := DllCall("Advapi32.dll\AdjustTokenPrivileges", "Ptr", t, "Int", false, "Ptr", &ti, "UInt", 0, "Ptr", 0, "Ptr", 0) 788 | DllCall("CloseHandle", "Ptr", t) ; close this access token handle to save memory 789 | DllCall("CloseHandle", "Ptr", h) ; close this process handle to save memory 790 | return r 791 | } 792 | 793 | 794 | ; Method: isTargetProcess64Bit(PID, hProcess := "", currentHandleAccess := "") 795 | ; Determines if a process is 64 bit. 796 | ; Parameters: 797 | ; PID The Process ID of the target process. If required this is used to open a temporary process handle. 798 | ; hProcess (Optional) A handle to the process, as returned by openProcess() i.e. [derivedObject].hProcess 799 | ; currentHandleAccess (Optional) The dwDesiredAccess value used when opening the process handle which has been 800 | ; passed as the hProcess parameter. If specifying hProcess, you should also specify this value. 801 | ; Return Values: 802 | ; True The target application is 64 bit. 803 | ; False The target application is 32 bit. 804 | ; Null The method failed. 805 | ; Notes: 806 | ; This is an internal method which is called when the new operator is used. It is used to set the pointer type for 32/64 bit applications so the pointer methods will work. 807 | ; This operation requires a handle with PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access rights. 808 | ; If the currentHandleAccess parameter does not contain these rights (or not passed) or if the hProcess (process handle) is invalid (or not passed) 809 | ; a temporary handle is opened to perform this operation. Otherwise if hProcess and currentHandleAccess appear valid 810 | ; the passed hProcess is used to perform the operation. 811 | 812 | isTargetProcess64Bit(PID, hProcess := "", currentHandleAccess := "") 813 | { 814 | if !A_Is64bitOS 815 | return False 816 | ; If insufficient rights, open a temporary handle 817 | else if !hProcess || !(currentHandleAccess & (this.aRights.PROCESS_QUERY_INFORMATION | this.aRights.PROCESS_QUERY_LIMITED_INFORMATION)) 818 | closeHandle := hProcess := this.openProcess(PID, this.aRights.PROCESS_QUERY_INFORMATION) 819 | if (hProcess && DllCall("IsWow64Process", "Ptr", hProcess, "Int*", Wow64Process)) 820 | result := !Wow64Process 821 | return result, closeHandle ? this.CloseHandle(hProcess) : "" 822 | } 823 | /* 824 | _Out_ PBOOL Wow64Proces value set to: 825 | True if the process is running under WOW64 - 32bit app on 64bit OS. 826 | False if the process is running under 32-bit Windows! 827 | False if the process is a 64-bit application running under 64-bit Windows. 828 | */ 829 | 830 | ; Method: suspend() / resume() 831 | ; Notes: 832 | ; These are undocumented Windows functions which suspend and resume the process. Here be dragons. 833 | ; The process handle must have PROCESS_SUSPEND_RESUME access rights. 834 | ; That is, you must specify this when using the new operator, as it is not included. 835 | ; Some people say it requires more rights and just use PROCESS_ALL_ACCESS, however PROCESS_SUSPEND_RESUME has worked for me. 836 | ; Suspending a process manually can be quite helpful when reversing memory addresses and pointers, although it's not at all required. 837 | ; As an unorthodox example, memory addresses holding pointers are often stored in a slightly obfuscated manner i.e. they require bit operations to calculate their 838 | ; true stored value (address). This obfuscation can prevent Cheat Engine from finding the true origin of a pointer or links to other memory regions. If there 839 | ; are no static addresses between the obfuscated address and the final destination address then CE wont find anything (there are ways around this in CE). One way around this is to 840 | ; suspend the process, write the true/deobfuscated value to the address and then perform your scans. Afterwards write back the original values and resume the process. 841 | 842 | suspend() 843 | { 844 | return DllCall("ntdll\NtSuspendProcess", "Ptr", this.hProcess) 845 | } 846 | 847 | resume() 848 | { 849 | return DllCall("ntdll\NtResumeProcess", "Ptr", this.hProcess) 850 | } 851 | 852 | ; Method: getModules(byRef aModules, useFileNameAsKey := False) 853 | ; Stores the process's loaded modules as an array of (object) modules in the aModules parameter. 854 | ; Parameters: 855 | ; aModules An unquoted variable name. The loaded modules of the process are stored in this variable as an array of objects. 856 | ; Each object in this array has the following keys: name, fileName, lpBaseOfDll, SizeOfImage, and EntryPoint. 857 | ; useFileNameAsKey When true, the file name e.g. GDI32.dll is used as the lookup key for each module object. 858 | ; Return Values: 859 | ; Positive integer The size of the aModules array. (Success) 860 | ; -3 EnumProcessModulesEx failed. 861 | ; -4 The AHK script is 32 bit and you are trying to access the modules of a 64 bit target process. 862 | 863 | getModules(byRef aModules, useFileNameAsKey := False) 864 | { 865 | if (A_PtrSize = 4 && this.IsTarget64bit) 866 | return -4 ; AHK is 32bit and target process is 64 bit, this function wont work 867 | aModules := [] 868 | if !moduleCount := this.EnumProcessModulesEx(lphModule) 869 | return -3 870 | loop % moduleCount 871 | { 872 | this.GetModuleInformation(hModule := numget(lphModule, (A_index - 1) * A_PtrSize), aModuleInfo) 873 | aModuleInfo.Name := this.GetModuleFileNameEx(hModule) 874 | filePath := aModuleInfo.name 875 | SplitPath, filePath, fileName 876 | aModuleInfo.fileName := fileName 877 | if useFileNameAsKey 878 | aModules[fileName] := aModuleInfo 879 | else aModules.insert(aModuleInfo) 880 | } 881 | return moduleCount 882 | } 883 | 884 | 885 | 886 | getEndAddressOfLastModule(byRef aModuleInfo := "") 887 | { 888 | if !moduleCount := this.EnumProcessModulesEx(lphModule) 889 | return -3 890 | hModule := numget(lphModule, (moduleCount - 1) * A_PtrSize) 891 | if this.GetModuleInformation(hModule, aModuleInfo) 892 | return aModuleInfo.lpBaseOfDll + aModuleInfo.SizeOfImage 893 | return -5 894 | } 895 | 896 | ; lpFilename [out] 897 | ; A pointer to a buffer that receives the fully qualified path to the module. 898 | ; If the size of the file name is larger than the value of the nSize parameter, the function succeeds 899 | ; but the file name is truncated and null-terminated. 900 | ; If the buffer is adequate the string is still null terminated. 901 | 902 | GetModuleFileNameEx(hModule := 0, fileNameNoPath := False) 903 | { 904 | ; ANSI MAX_PATH = 260 (includes null) - unicode can be ~32K.... but no one would ever have one that size 905 | ; So just give it a massive size and don't bother checking. Most coders just give it MAX_PATH size anyway 906 | VarSetCapacity(lpFilename, 2048 * (A_IsUnicode ? 2 : 1)) 907 | DllCall("psapi\GetModuleFileNameEx" 908 | , "Ptr", this.hProcess 909 | , "Ptr", hModule 910 | , "Str", lpFilename 911 | , "Uint", 2048 / (A_IsUnicode ? 2 : 1)) 912 | if fileNameNoPath 913 | SplitPath, lpFilename, lpFilename ; strips the path so = GDI32.dll 914 | 915 | return lpFilename 916 | } 917 | 918 | ; dwFilterFlag 919 | ; LIST_MODULES_DEFAULT 0x0 920 | ; LIST_MODULES_32BIT 0x01 921 | ; LIST_MODULES_64BIT 0x02 922 | ; LIST_MODULES_ALL 0x03 923 | ; If the function is called by a 32-bit application running under WOW64, the dwFilterFlag option 924 | ; is ignored and the function provides the same results as the EnumProcessModules function. 925 | EnumProcessModulesEx(byRef lphModule, dwFilterFlag := 0x03) 926 | { 927 | lastError := A_LastError 928 | size := VarSetCapacity(lphModule, 4) 929 | loop 930 | { 931 | DllCall("psapi\EnumProcessModulesEx" 932 | , "Ptr", this.hProcess 933 | , "Ptr", &lphModule 934 | , "Uint", size 935 | , "Uint*", reqSize 936 | , "Uint", dwFilterFlag) 937 | if ErrorLevel 938 | return 0 939 | else if (size >= reqSize) 940 | break 941 | else size := VarSetCapacity(lphModule, reqSize) 942 | } 943 | ; On first loop it fails with A_lastError = 0x299 as its meant to 944 | ; might as well reset it to its previous version 945 | DllCall("SetLastError", "UInt", lastError) 946 | return reqSize // A_PtrSize ; module count ; sizeof(HMODULE) - enumerate the array of HMODULEs 947 | } 948 | 949 | GetModuleInformation(hModule, byRef aModuleInfo) 950 | { 951 | VarSetCapacity(MODULEINFO, A_PtrSize * 3), aModuleInfo := [] 952 | return DllCall("psapi\GetModuleInformation" 953 | , "Ptr", this.hProcess 954 | , "Ptr", hModule 955 | , "Ptr", &MODULEINFO 956 | , "UInt", A_PtrSize * 3) 957 | , aModuleInfo := { lpBaseOfDll: numget(MODULEINFO, 0, "Ptr") 958 | , SizeOfImage: numget(MODULEINFO, A_PtrSize, "UInt") 959 | , EntryPoint: numget(MODULEINFO, A_PtrSize * 2, "Ptr") } 960 | } 961 | 962 | ; Method: hexStringToPattern(hexString) 963 | ; Converts the hex string parameter into an array of bytes pattern (AOBPattern) that 964 | ; can be passed to the various pattern scan methods i.e. modulePatternScan(), addressPatternScan(), rawPatternScan(), and processPatternScan() 965 | ; 966 | ; Parameters: 967 | ; hexString - A string of hex bytes. The '0x' hex prefix is optional. 968 | ; Bytes can optionally be separated using the space or tab characters. 969 | ; Each byte must be two characters in length i.e. '04' or '0x04' (not '4' or '0x4') 970 | ; ** Unlike the other methods, wild card bytes MUST be denoted using '??' (two question marks)** 971 | ; 972 | ; Return Values: 973 | ; Object Success - The returned object contains the AOB pattern. 974 | ; -1 An empty string was passed. 975 | ; -2 Non hex character present. Acceptable characters are A-F, a-F, 0-9, ?, space, tab, and 0x (hex prefix). 976 | ; -3 Non-even wild card character count. One of the wild card bytes is missing a '?' e.g. '?' instead of '??'. 977 | ; -4 Non-even character count. One of the hex bytes is probably missing a character e.g. '4' instead of '04'. 978 | ; 979 | ; Examples: 980 | ; pattern := hexStringToPattern("DEADBEEF02") 981 | ; pattern := hexStringToPattern("0xDE0xAD0xBE0xEF0x02") 982 | ; pattern := hexStringToPattern("DE AD BE EF 02") 983 | ; pattern := hexStringToPattern("0xDE 0xAD 0xBE 0xEF 0x02") 984 | ; 985 | ; This will mark the third byte as wild: 986 | ; pattern := hexStringToPattern("DE AD ?? EF 02") 987 | ; pattern := hexStringToPattern("0xDE 0xAD ?? 0xEF 0x02") 988 | ; 989 | ; The returned pattern can then be passed to the various pattern scan methods, for example: 990 | ; pattern := hexStringToPattern("DE AD BE EF 02") 991 | ; memObject.processPatternScan(,, pattern*) ; Note the '*' 992 | 993 | hexStringToPattern(hexString) 994 | { 995 | AOBPattern := [] 996 | hexString := RegExReplace(hexString, "(\s|0x)") 997 | StringReplace, hexString, hexString, ?, ?, UseErrorLevel 998 | wildCardCount := ErrorLevel 999 | 1000 | if !length := StrLen(hexString) 1001 | return -1 ; no str 1002 | else if RegExMatch(hexString, "[^0-9a-fA-F?]") 1003 | return -2 ; non hex character and not a wild card 1004 | else if Mod(wildCardCount, 2) 1005 | return -3 ; non-even wild card character count 1006 | else if Mod(length, 2) 1007 | return -4 ; non-even character count 1008 | loop, % length/2 1009 | { 1010 | value := "0x" SubStr(hexString, 1 + 2 * (A_index-1), 2) 1011 | AOBPattern.Insert(value + 0 = "" ? "?" : value) 1012 | } 1013 | return AOBPattern 1014 | } 1015 | 1016 | ; Method: stringToPattern(string, encoding := "UTF-8", insertNullTerminator := False) 1017 | ; Converts a text string parameter into an array of bytes pattern (AOBPattern) that 1018 | ; can be passed to the various pattern scan methods i.e. modulePatternScan(), addressPatternScan(), rawPatternScan(), and processPatternScan() 1019 | ; 1020 | ; Parameters: 1021 | ; string The text string to convert. 1022 | ; encoding This refers to how the string is stored in the program's memory. 1023 | ; UTF-8 and UTF-16 are common. Refer to the AHK manual for other encoding types. 1024 | ; insertNullTerminator Includes the null terminating byte(s) (at the end of the string) in the AOB pattern. 1025 | ; This should be set to 'false' unless you are certain that the target string is null terminated and you are searching for the entire string or the final part of the string. 1026 | ; 1027 | ; Return Values: 1028 | ; Object Success - The returned object contains the AOB pattern. 1029 | ; -1 An empty string was passed. 1030 | ; 1031 | ; Examples: 1032 | ; pattern := stringToPattern("This text exists somewhere in the target program!") 1033 | ; memObject.processPatternScan(,, pattern*) ; Note the '*' 1034 | 1035 | stringToPattern(string, encoding := "UTF-8", insertNullTerminator := False) 1036 | { 1037 | if !length := StrLen(string) 1038 | return -1 ; no str 1039 | AOBPattern := [] 1040 | encodingSize := (encoding = "utf-16" || encoding = "cp1200") ? 2 : 1 1041 | requiredSize := StrPut(string, encoding) * encodingSize - (insertNullTerminator ? 0 : encodingSize) 1042 | VarSetCapacity(buffer, requiredSize) 1043 | StrPut(string, &buffer, length + (insertNullTerminator ? 1 : 0), encoding) 1044 | loop, % requiredSize 1045 | AOBPattern.Insert(NumGet(buffer, A_Index-1, "UChar")) 1046 | return AOBPattern 1047 | } 1048 | 1049 | 1050 | ; Method: modulePatternScan(module := "", aAOBPattern*) 1051 | ; Scans the specified module for the specified array of bytes 1052 | ; Parameters: 1053 | ; module - The file name of the module/dll to search e.g. "calc.exe", "GDI32.dll", "Bass.dll" etc 1054 | ; If no module (null) is specified, the executable file of the process will be used. 1055 | ; e.g. for calc.exe it would be the same as calling modulePatternScan(, aAOBPattern*) or modulePatternScan("calc.exe", aAOBPattern*) 1056 | ; aAOBPattern* A variadic list of byte values i.e. the array of bytes to find. 1057 | ; Wild card bytes should be indicated by passing a non-numeric value eg "?". 1058 | ; Return Values: 1059 | ; Positive int Success. The memory address of the found pattern. 1060 | ; Null Failed to find or retrieve the specified module. ErrorLevel is set to the returned error from getModuleBaseAddress() 1061 | ; refer to that method for more information. 1062 | ; 0 The pattern was not found inside the module 1063 | ; -9 VirtualQueryEx() failed 1064 | ; -10 The aAOBPattern* is invalid. No bytes were passed 1065 | 1066 | modulePatternScan(module := "", aAOBPattern*) 1067 | { 1068 | MEM_COMMIT := 0x1000, MEM_MAPPED := 0x40000, MEM_PRIVATE := 0x20000 1069 | , PAGE_NOACCESS := 0x01, PAGE_GUARD := 0x100 1070 | 1071 | if (result := this.getModuleBaseAddress(module, aModuleInfo)) <= 0 1072 | return "", ErrorLevel := result ; failed 1073 | if !patternSize := this.getNeedleFromAOBPattern(patternMask, AOBBuffer, aAOBPattern*) 1074 | return -10 ; no pattern 1075 | ; Try to read the entire module in one RPM() 1076 | ; If fails with access (-1) iterate the modules memory pages and search the ones which are readable 1077 | if (result := this.PatternScan(aModuleInfo.lpBaseOfDll, aModuleInfo.SizeOfImage, patternMask, AOBBuffer)) >= 0 1078 | return result ; Found / not found 1079 | ; else RPM() failed lets iterate the pages 1080 | address := aModuleInfo.lpBaseOfDll 1081 | endAddress := address + aModuleInfo.SizeOfImage 1082 | loop 1083 | { 1084 | if !this.VirtualQueryEx(address, aRegion) 1085 | return -9 1086 | if (aRegion.State = MEM_COMMIT 1087 | && !(aRegion.Protect & (PAGE_NOACCESS | PAGE_GUARD)) ; can't read these areas 1088 | ;&& (aRegion.Type = MEM_MAPPED || aRegion.Type = MEM_PRIVATE) ;Might as well read Image sections as well 1089 | && aRegion.RegionSize >= patternSize 1090 | && (result := this.PatternScan(address, aRegion.RegionSize, patternMask, AOBBuffer)) > 0) 1091 | return result 1092 | } until (address += aRegion.RegionSize) >= endAddress 1093 | return 0 1094 | } 1095 | 1096 | ; Method: addressPatternScan(startAddress, sizeOfRegionBytes, aAOBPattern*) 1097 | ; Scans a specified memory region for an array of bytes pattern. 1098 | ; The entire memory area specified must be readable for this method to work, 1099 | ; i.e. you must ensure the area is readable before calling this method. 1100 | ; Parameters: 1101 | ; startAddress The memory address from which to begin the search. 1102 | ; sizeOfRegionBytes The numbers of bytes to scan in the memory region. 1103 | ; aAOBPattern* A variadic list of byte values i.e. the array of bytes to find. 1104 | ; Wild card bytes should be indicated by passing a non-numeric value eg "?". 1105 | ; Return Values: 1106 | ; Positive integer Success. The memory address of the found pattern. 1107 | ; 0 Pattern not found 1108 | ; -1 Failed to read the memory region. 1109 | ; -10 An aAOBPattern pattern. No bytes were passed. 1110 | 1111 | addressPatternScan(startAddress, sizeOfRegionBytes, aAOBPattern*) 1112 | { 1113 | if !this.getNeedleFromAOBPattern(patternMask, AOBBuffer, aAOBPattern*) 1114 | return -10 1115 | return this.PatternScan(startAddress, sizeOfRegionBytes, patternMask, AOBBuffer) 1116 | } 1117 | 1118 | ; Method: processPatternScan(startAddress := 0, endAddress := "", aAOBPattern*) 1119 | ; Scan the memory space of the current process for an array of bytes pattern. 1120 | ; To use this in a loop (scanning for multiple occurrences of the same pattern), 1121 | ; simply call it again passing the last found address + 1 as the startAddress. 1122 | ; Parameters: 1123 | ; startAddress - The memory address from which to begin the search. 1124 | ; endAddress - The memory address at which the search ends. 1125 | ; Defaults to 0x7FFFFFFF for 32 bit target processes. 1126 | ; Defaults to 0xFFFFFFFF for 64 bit target processes when the AHK script is 32 bit. 1127 | ; Defaults to 0x7FFFFFFFFFF for 64 bit target processes when the AHK script is 64 bit. 1128 | ; 0x7FFFFFFF and 0x7FFFFFFFFFF are the maximum process usable virtual address spaces for 32 and 64 bit applications. 1129 | ; Anything higher is used by the system (unless /LARGEADDRESSAWARE and 4GT have been modified). 1130 | ; Note: The entire pattern must be occur inside this range for a match to be found. The range is inclusive. 1131 | ; aAOBPattern* - A variadic list of byte values i.e. the array of bytes to find. 1132 | ; Wild card bytes should be indicated by passing a non-numeric value eg "?". 1133 | ; Return Values: 1134 | ; Positive integer - Success. The memory address of the found pattern. 1135 | ; 0 The pattern was not found. 1136 | ; -1 VirtualQueryEx() failed. 1137 | ; -2 Failed to read a memory region. 1138 | ; -10 The aAOBPattern* is invalid. (No bytes were passed) 1139 | 1140 | processPatternScan(startAddress := 0, endAddress := "", aAOBPattern*) 1141 | { 1142 | address := startAddress 1143 | if endAddress is not integer 1144 | endAddress := this.isTarget64bit ? (A_PtrSize = 8 ? 0x7FFFFFFFFFF : 0xFFFFFFFF) : 0x7FFFFFFF 1145 | 1146 | MEM_COMMIT := 0x1000, MEM_MAPPED := 0x40000, MEM_PRIVATE := 0x20000 1147 | PAGE_NOACCESS := 0x01, PAGE_GUARD := 0x100 1148 | if !patternSize := this.getNeedleFromAOBPattern(patternMask, AOBBuffer, aAOBPattern*) 1149 | return -10 1150 | while address <= endAddress ; > 0x7FFFFFFF - definitely reached the end of the useful area (at least for a 32 target process) 1151 | { 1152 | if !this.VirtualQueryEx(address, aInfo) 1153 | return -1 1154 | if A_Index = 1 1155 | aInfo.RegionSize -= address - aInfo.BaseAddress 1156 | if (aInfo.State = MEM_COMMIT) 1157 | && !(aInfo.Protect & (PAGE_NOACCESS | PAGE_GUARD)) ; can't read these areas 1158 | ;&& (aInfo.Type = MEM_MAPPED || aInfo.Type = MEM_PRIVATE) ;Might as well read Image sections as well 1159 | && aInfo.RegionSize >= patternSize 1160 | && (result := this.PatternScan(address, aInfo.RegionSize, patternMask, AOBBuffer)) 1161 | { 1162 | if result < 0 1163 | return -2 1164 | else if (result + patternSize - 1 <= endAddress) 1165 | return result 1166 | else return 0 1167 | } 1168 | address += aInfo.RegionSize 1169 | } 1170 | return 0 1171 | } 1172 | 1173 | ; Method: rawPatternScan(byRef buffer, sizeOfBufferBytes := "", aAOBPattern*) 1174 | ; Scans a binary buffer for an array of bytes pattern. 1175 | ; This is useful if you have already dumped a region of memory via readRaw() 1176 | ; Parameters: 1177 | ; buffer The binary buffer to be searched. 1178 | ; sizeOfBufferBytes The size of the binary buffer. If null or 0 the size is automatically retrieved. 1179 | ; startOffset The offset from the start of the buffer from which to begin the search. This must be >= 0. 1180 | ; aAOBPattern* A variadic list of byte values i.e. the array of bytes to find. 1181 | ; Wild card bytes should be indicated by passing a non-numeric value eg "?". 1182 | ; Return Values: 1183 | ; >= 0 The offset of the pattern relative to the start of the haystack. 1184 | ; -1 Not found. 1185 | ; -2 Parameter incorrect. 1186 | 1187 | rawPatternScan(byRef buffer, sizeOfBufferBytes := "", startOffset := 0, aAOBPattern*) 1188 | { 1189 | if !this.getNeedleFromAOBPattern(patternMask, AOBBuffer, aAOBPattern*) 1190 | return -10 1191 | if (sizeOfBufferBytes + 0 = "" || sizeOfBufferBytes <= 0) 1192 | sizeOfBufferBytes := VarSetCapacity(buffer) 1193 | if (startOffset + 0 = "" || startOffset < 0) 1194 | startOffset := 0 1195 | return this.bufferScanForMaskedPattern(&buffer, sizeOfBufferBytes, patternMask, &AOBBuffer, startOffset) 1196 | } 1197 | 1198 | ; Method: getNeedleFromAOBPattern(byRef patternMask, byRef needleBuffer, aAOBPattern*) 1199 | ; Converts an array of bytes pattern (aAOBPattern*) into a binary needle and pattern mask string 1200 | ; which are compatible with patternScan() and bufferScanForMaskedPattern(). 1201 | ; The modulePatternScan(), addressPatternScan(), rawPatternScan(), and processPatternScan() methods 1202 | ; allow you to directly search for an array of bytes pattern in a single method call. 1203 | ; Parameters: 1204 | ; patternMask - (output) A string which indicates which bytes are wild/non-wild. 1205 | ; needleBuffer - (output) The array of bytes passed via aAOBPattern* is converted to a binary needle and stored inside this variable. 1206 | ; aAOBPattern* - (input) A variadic list of byte values i.e. the array of bytes from which to create the patternMask and needleBuffer. 1207 | ; Wild card bytes should be indicated by passing a non-numeric value eg "?". 1208 | ; Return Values: 1209 | ; The number of bytes in the binary needle and hence the number of characters in the patternMask string. 1210 | 1211 | getNeedleFromAOBPattern(byRef patternMask, byRef needleBuffer, aAOBPattern*) 1212 | { 1213 | patternMask := "", VarSetCapacity(needleBuffer, aAOBPattern.MaxIndex()) 1214 | for i, v in aAOBPattern 1215 | patternMask .= (v + 0 = "" ? "?" : "x"), NumPut(round(v), needleBuffer, A_Index - 1, "UChar") 1216 | return round(aAOBPattern.MaxIndex()) 1217 | } 1218 | 1219 | ; The handle must have been opened with the PROCESS_QUERY_INFORMATION access right 1220 | VirtualQueryEx(address, byRef aInfo) 1221 | { 1222 | 1223 | if (aInfo.__Class != "_ClassMemory._MEMORY_BASIC_INFORMATION") 1224 | aInfo := new this._MEMORY_BASIC_INFORMATION() 1225 | return aInfo.SizeOfStructure = DLLCall("VirtualQueryEx" 1226 | , "Ptr", this.hProcess 1227 | , "Ptr", address 1228 | , "Ptr", aInfo.pStructure 1229 | , "Ptr", aInfo.SizeOfStructure 1230 | , "Ptr") 1231 | } 1232 | 1233 | /* 1234 | // The c++ function used to generate the machine code 1235 | int scan(unsigned char* haystack, unsigned int haystackSize, unsigned char* needle, unsigned int needleSize, char* patternMask, unsigned int startOffset) 1236 | { 1237 | for (unsigned int i = startOffset; i <= haystackSize - needleSize; i++) 1238 | { 1239 | for (unsigned int j = 0; needle[j] == haystack[i + j] || patternMask[j] == '?'; j++) 1240 | { 1241 | if (j + 1 == needleSize) 1242 | return i; 1243 | } 1244 | } 1245 | return -1; 1246 | } 1247 | */ 1248 | 1249 | ; Method: PatternScan(startAddress, sizeOfRegionBytes, patternMask, byRef needleBuffer) 1250 | ; Scans a specified memory region for a binary needle pattern using a machine code function 1251 | ; If found it returns the memory address of the needle in the processes memory. 1252 | ; Parameters: 1253 | ; startAddress - The memory address from which to begin the search. 1254 | ; sizeOfRegionBytes - The numbers of bytes to scan in the memory region. 1255 | ; patternMask - This string indicates which bytes must match and which bytes are wild. Each wildcard byte must be denoted by a single '?'. 1256 | ; Non wildcards can use any other single character e.g 'x'. There should be no spaces. 1257 | ; With the patternMask 'xx??x', the first, second, and fifth bytes must match. The third and fourth bytes are wild. 1258 | ; needleBuffer - The variable which contains the binary needle. This needle should consist of UChar bytes. 1259 | ; Return Values: 1260 | ; Positive integer The address of the pattern. 1261 | ; 0 Pattern not found. 1262 | ; -1 Failed to read the region. 1263 | 1264 | patternScan(startAddress, sizeOfRegionBytes, byRef patternMask, byRef needleBuffer) 1265 | { 1266 | if !this.readRaw(startAddress, buffer, sizeOfRegionBytes) 1267 | return -1 1268 | if (offset := this.bufferScanForMaskedPattern(&buffer, sizeOfRegionBytes, patternMask, &needleBuffer)) >= 0 1269 | return startAddress + offset 1270 | else return 0 1271 | } 1272 | ; Method: bufferScanForMaskedPattern(byRef hayStack, sizeOfHayStackBytes, byRef patternMask, byRef needle) 1273 | ; Scans a binary haystack for binary needle against a pattern mask string using a machine code function. 1274 | ; Parameters: 1275 | ; hayStackAddress - The address of the binary haystack which is to be searched. 1276 | ; sizeOfHayStackBytes The total size of the haystack in bytes. 1277 | ; patternMask - A string which indicates which bytes must match and which bytes are wild. Each wildcard byte must be denoted by a single '?'. 1278 | ; Non wildcards can use any other single character e.g 'x'. There should be no spaces. 1279 | ; With the patternMask 'xx??x', the first, second, and fifth bytes must match. The third and fourth bytes are wild. 1280 | ; needleAddress - The address of the binary needle to find. This needle should consist of UChar bytes. 1281 | ; startOffset - The offset from the start of the haystack from which to begin the search. This must be >= 0. 1282 | ; Return Values: 1283 | ; >= 0 Found. The pattern begins at this offset - relative to the start of the haystack. 1284 | ; -1 Not found. 1285 | ; -2 Invalid sizeOfHayStackBytes parameter - Must be > 0. 1286 | 1287 | ; Notes: 1288 | ; This is a basic function with few safeguards. Incorrect parameters may crash the script. 1289 | 1290 | bufferScanForMaskedPattern(hayStackAddress, sizeOfHayStackBytes, byRef patternMask, needleAddress, startOffset := 0) 1291 | { 1292 | static p 1293 | if !p 1294 | { 1295 | if A_PtrSize = 4 1296 | p := this.MCode("1,x86:8B44240853558B6C24182BC5568B74242489442414573BF0773E8B7C241CBB010000008B4424242BF82BD8EB038D49008B54241403D68A0C073A0A740580383F750B8D0C033BCD74174240EBE98B442424463B74241876D85F5E5D83C8FF5BC35F8BC65E5D5BC3") 1297 | else 1298 | p := this.MCode("1,x64:48895C2408488974241048897C2418448B5424308BF2498BD8412BF1488BF9443BD6774A4C8B5C24280F1F800000000033C90F1F400066660F1F840000000000448BC18D4101418D4AFF03C80FB60C3941380C18740743803C183F7509413BC1741F8BC8EBDA41FFC2443BD676C283C8FF488B5C2408488B742410488B7C2418C3488B5C2408488B742410488B7C2418418BC2C3") 1299 | } 1300 | if (needleSize := StrLen(patternMask)) + startOffset > sizeOfHayStackBytes 1301 | return -1 ; needle can't exist inside this region. And basic check to prevent wrap around error of the UInts in the machine function 1302 | if (sizeOfHayStackBytes > 0) 1303 | return DllCall(p, "Ptr", hayStackAddress, "UInt", sizeOfHayStackBytes, "Ptr", needleAddress, "UInt", needleSize, "AStr", patternMask, "UInt", startOffset, "cdecl int") 1304 | return -2 1305 | } 1306 | 1307 | ; Notes: 1308 | ; Other alternatives for non-wildcard buffer comparison. 1309 | ; Use memchr to find the first byte, then memcmp to compare the remainder of the buffer against the needle and loop if it doesn't match 1310 | ; The function FindMagic() by Lexikos uses this method. 1311 | ; Use scanInBuf() machine code function - but this only supports 32 bit ahk. I could check if needle contains wild card and AHK is 32bit, 1312 | ; then call this function. But need to do a speed comparison to see the benefits, but this should be faster. Although the benefits for 1313 | ; the size of the memory regions be dumped would most likely be inconsequential as it's already extremely fast. 1314 | 1315 | MCode(mcode) 1316 | { 1317 | static e := {1:4, 2:1}, c := (A_PtrSize=8) ? "x64" : "x86" 1318 | if !regexmatch(mcode, "^([0-9]+),(" c ":|.*?," c ":)([^,]+)", m) 1319 | return 1320 | if !DllCall("crypt32\CryptStringToBinary", "str", m3, "uint", 0, "uint", e[m1], "ptr", 0, "uint*", s, "ptr", 0, "ptr", 0) 1321 | return 1322 | p := DllCall("GlobalAlloc", "uint", 0, "ptr", s, "ptr") 1323 | ; if (c="x64") ; Virtual protect must always be enabled for both 32 and 64 bit. If DEP is set to all applications (not just systems), then this is required 1324 | DllCall("VirtualProtect", "ptr", p, "ptr", s, "uint", 0x40, "uint*", op) 1325 | if DllCall("crypt32\CryptStringToBinary", "str", m3, "uint", 0, "uint", e[m1], "ptr", p, "uint*", s, "ptr", 0, "ptr", 0) 1326 | return p 1327 | DllCall("GlobalFree", "ptr", p) 1328 | return 1329 | } 1330 | 1331 | ; This link indicates that the _MEMORY_BASIC_INFORMATION32/64 should be based on the target process 1332 | ; http://stackoverflow.com/questions/20068219/readprocessmemory-on-a-64-bit-proces-always-returns-error-299 1333 | ; The msdn documentation is unclear, and suggests that a debugger can pass either structure - perhaps there is some other step involved. 1334 | ; My tests seem to indicate that you must pass _MEMORY_BASIC_INFORMATION i.e. structure is relative to the AHK script bitness. 1335 | ; Another post on the net also agrees with my results. 1336 | 1337 | ; Notes: 1338 | ; A 64 bit AHK script can call this on a target 64 bit process. Issues may arise at extremely high memory addresses as AHK does not support UInt64 (but these addresses should never be used anyway). 1339 | ; A 64 bit AHK can call this on a 32 bit target and it should work. 1340 | ; A 32 bit AHk script can call this on a 64 bit target and it should work providing the addresses fall inside the 32 bit range. 1341 | 1342 | class _MEMORY_BASIC_INFORMATION 1343 | { 1344 | __new() 1345 | { 1346 | if !this.pStructure := DllCall("GlobalAlloc", "UInt", 0, "Ptr", this.SizeOfStructure := A_PtrSize = 8 ? 48 : 28, "Ptr") 1347 | return "" 1348 | return this 1349 | } 1350 | __Delete() 1351 | { 1352 | DllCall("GlobalFree", "Ptr", this.pStructure) 1353 | } 1354 | ; For 64bit the int64 should really be unsigned. But AHK doesn't support these 1355 | ; so this won't work correctly for higher memory address areas 1356 | __get(key) 1357 | { 1358 | static aLookUp := A_PtrSize = 8 1359 | ? { "BaseAddress": {"Offset": 0, "Type": "Int64"} 1360 | , "AllocationBase": {"Offset": 8, "Type": "Int64"} 1361 | , "AllocationProtect": {"Offset": 16, "Type": "UInt"} 1362 | , "RegionSize": {"Offset": 24, "Type": "Int64"} 1363 | , "State": {"Offset": 32, "Type": "UInt"} 1364 | , "Protect": {"Offset": 36, "Type": "UInt"} 1365 | , "Type": {"Offset": 40, "Type": "UInt"} } 1366 | : { "BaseAddress": {"Offset": 0, "Type": "UInt"} 1367 | , "AllocationBase": {"Offset": 4, "Type": "UInt"} 1368 | , "AllocationProtect": {"Offset": 8, "Type": "UInt"} 1369 | , "RegionSize": {"Offset": 12, "Type": "UInt"} 1370 | , "State": {"Offset": 16, "Type": "UInt"} 1371 | , "Protect": {"Offset": 20, "Type": "UInt"} 1372 | , "Type": {"Offset": 24, "Type": "UInt"} } 1373 | 1374 | if aLookUp.HasKey(key) 1375 | return numget(this.pStructure+0, aLookUp[key].Offset, aLookUp[key].Type) 1376 | } 1377 | __set(key, value) 1378 | { 1379 | static aLookUp := A_PtrSize = 8 1380 | ? { "BaseAddress": {"Offset": 0, "Type": "Int64"} 1381 | , "AllocationBase": {"Offset": 8, "Type": "Int64"} 1382 | , "AllocationProtect": {"Offset": 16, "Type": "UInt"} 1383 | , "RegionSize": {"Offset": 24, "Type": "Int64"} 1384 | , "State": {"Offset": 32, "Type": "UInt"} 1385 | , "Protect": {"Offset": 36, "Type": "UInt"} 1386 | , "Type": {"Offset": 40, "Type": "UInt"} } 1387 | : { "BaseAddress": {"Offset": 0, "Type": "UInt"} 1388 | , "AllocationBase": {"Offset": 4, "Type": "UInt"} 1389 | , "AllocationProtect": {"Offset": 8, "Type": "UInt"} 1390 | , "RegionSize": {"Offset": 12, "Type": "UInt"} 1391 | , "State": {"Offset": 16, "Type": "UInt"} 1392 | , "Protect": {"Offset": 20, "Type": "UInt"} 1393 | , "Type": {"Offset": 24, "Type": "UInt"} } 1394 | 1395 | if aLookUp.HasKey(key) 1396 | { 1397 | NumPut(value, this.pStructure+0, aLookUp[key].Offset, aLookUp[key].Type) 1398 | return value 1399 | } 1400 | } 1401 | Ptr() 1402 | { 1403 | return this.pStructure 1404 | } 1405 | sizeOf() 1406 | { 1407 | return this.SizeOfStructure 1408 | } 1409 | } 1410 | 1411 | } --------------------------------------------------------------------------------