Advertisement
Guest User

VAM_Controls.ahk

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