?
Solved

Searching memory.

Posted on 2006-11-24
12
Medium Priority
?
280 Views
Last Modified: 2010-04-05
Hi.

If i know the handle of a process,
how can i search for a specific value in memory (of the process) and write to it (change the value) ?

Thanks in advance.
0
Comment
Question by:CodedK
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
12 Comments
 
LVL 4

Expert Comment

by:tobjectpascal
ID: 18010246
function ReadProcMem(WindowCaption : String;Address : Pointer;Len : Integer) : String;
var
Wnd : Hwnd;
ph,pid : dword;
BytesRead : Cardinal;
begin
Result := '';
Wnd := FindWindow(nil,pchar(WindowCaption));
if Wnd = 0 then exit;
GetWindowThreadProcessID(Wnd, @pid);
ph := OpenProcess(PROCESS_ALL_ACCESS, false, pid);
SetLength(Result,Len);
ReadProcessMemory(ph, Address, pointer(Result), len, BytesRead);
CloseHandle(ph);
end;

//thats about it, you should call it like : ReadProcMem('Hi',Ptr($44444),12);


Const
  WindowTitle = 'Game Window'; // define the game's window name ;
  Address1 = $4ab3485f;      // define your address to poke   ;
  PokeValue1 = $32;          // define what value to write    ;
  NumberOfBytes1 = 1;        // define how many bytes to write
  Address2 = $4ab3485c;
  PokeValue2 = $11;
  NumberOfBytes2 = 3;

procedure TForm1.Button1Click(Sender: TObject); // when button is clicked ... ;
Var
 WindowName : integer;
  ProcessId : integer;
  ThreadId : integer;     // defining variable's types  ;
  buf : PChar;
  HandleWindow : Integer;
  write : cardinal ;
begin
 WindowName := FindWindow(nil,WindowTitle);
     If WindowName = 0 then  // check if the game is running;
                MessageDlg('The game must be running in the background. Run it now, and then try again.', mtwarning,[mbOK],0);
  ThreadId := GetWindowThreadProcessId(WindowName,@ProcessId);
  HandleWindow := OpenProcess(PROCESS_ALL_ACCESS,False,ProcessId);
  GetMem(buf,1);
  buf^ := Chr(PokeValue1);
  WriteProcessMemory(HandleWindow,ptr(Address1),buf,NumberOfBytes1,write);
  FreeMem(buf);
  closehandle(HandleWindow);
end;

procedure TForm1.Button1Click(Sender: TObject);
Var
 Wnd : Hwnd;
 ph,pid : dword;
 BytesRead : Cardinal;
 Buffer: Array [0..255] of Char;
 Address: Integer;
Begin
 // Wnd := FindWindow(nil,pchar(WindowCaption));
 // if Wnd = 0 then exit;
   Wnd:=form1.Handle; //use self for now.
   GetWindowThreadProcessID(Wnd, @pid);
   ph := OpenProcess(PROCESS_ALL_ACCESS, false, pid);
   Address:=GetWindowLong(Wnd,GWL_HINSTANCE);
   BytesRead:=1;
   While BytesRead<>0 do
    Begin
      ReadProcessMemory(ph, Pointer(Address), @Buffer, SizeOf(Buffer), BytesRead);
      Richedit1.Lines.Add(Buffer);
      Inc(Address,Integer(BytesRead));
   //read into buffer and repeat.
    End;
   CloseHandle(ph);
end;

0
 
LVL 16

Author Comment

by:CodedK
ID: 18010540
Hi tobjectpascal. Thank you :)

Well some questions...

You say :  "you should call it like : ReadProcMem('Hi',Ptr($44444),12);"
I'll only know the value for example (6 lifes left)... value = 6
How can i call it ? >> 
ReadProcMem('Super Game',?????,6);"

The question about searching the memory space for the specific value stands.
And probably its going to take multiple searches to see if those values changed.
(creating a list & excluding addresses that dont have this value any more).

If i first check for '6' for example it will bring about 2000 results at least (imagine searching for 1).
I need a search method that will bring back the address.
0
 
LVL 16

Author Comment

by:CodedK
ID: 18010553
Is it possible to know where the address of this application in memory start and end and
search all the values inside ?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Accepted Solution

by:
Meldrachaun earned 2000 total points
ID: 18082596
Took some digging, but yes, there is a way to find the memory locations.  Unfortunately it's not simple.  The program isn't one big memory block you can search.  The exe, and each DLL that loads (including the windows API DLLs) are seperate modules that have their own address spaces.  Memory that is allocated onto the heap is also stored in a seperate place, so you have to find and search all the heap spaces as well.  If you know what area of memory you are looking for, you can narrow the search.

Here's some code to find each module's memory space.  Make sure to include SysUtils and the PSApi units.  This code assumes you have the ProcessID variable already set

var
  Output: DWORD;
  ProcessHandle: THandle;
  ModuleHandles: array[0..1023] of HMODULE;
  i, len: integer;
  info: _MODULEINFO;
  pinfo: LPMODULEINFO;
  start: pointer;
  size: cardinal;

begin
  ProcessHandle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_OPERATION or
                               PROCESS_VM_READ or PROCESS_VM_WRITE, false, ProcessID);
  if ProcessHandle = 0 then RaiseLastOSError;
  try
    if not EnumProcessModules(ProcessHandle, @ModuleHandles, sizeof(ModuleHandles), output) then
      RaiseLastOSError;
    len := (output div sizeof(HMODULE))-1;
    pinfo := @info;
    for i := 0 to len do
    begin
      if not GetModuleInformation(ProcessHandle, ModuleHandles[i], pinfo, sizeof(_MODULEINFO)) then
        RaiseLastOSError;
      start := info.lpBaseOfDll;
      size := info.SizeOfImage;
    // start is the starting memory address of the module
    // size if the number of bytes the module takes up
    // add code here to search memory, replace memory with desired data, etc.  

    end;

  finally
    CloseHandle(ProcessHandle);
  end;
end;

If you want to examine what each module is before you search it's memory, use the GetModuleBaseName or GetModuleFileName APIs.  

To get the heap info, use the GetProcessHeaps API, then use the  HeapLock, HeapWalk, and HeapUnlock APIs to search the heap, but I think the above code is what you're looking for.
0
 
LVL 16

Author Comment

by:CodedK
ID: 18099727
Meldrachaun thanks but i cant make it work.

I use it like this : ProcessID :=Form1.Handle;
RaiseLastOSError always raises an error.
0
 
LVL 4

Expert Comment

by:Meldrachaun
ID: 18100404
The process ID is not the same as a window handle.  If you are trying to test this on your current app, replace the

ProcessHandle := OpenProcess code above with

ProcessHandle := GetCurrentProcess;

You also should remove the

  CloseHandle(ProcessHandle);

code.  

OR - you can get the process ID from the Window handle using the GetWindowThreadProcessId

see http://msdn2.microsoft.com/en-us/library/ms633522.aspx
0
 
LVL 16

Author Comment

by:CodedK
ID: 18100654
I've tried
  ProcessID :=GetCurrentProcess;
  ProcessID := GetWindowThreadProcessId(Form1.Handle);
But i still get the errors...
0
 
LVL 4

Expert Comment

by:Meldrachaun
ID: 18110444
GetWindowThreadProcessID returns a handle to a thread.  To get the process ID, you pass the process ID as the second parameter.  I just tested it, and it worked for me like this:

GetWindowThreadProcessID(Form1.Handle, ProcessID);

I'm testing this on a Windows XP machine.
0
 
LVL 16

Author Comment

by:CodedK
ID: 18119026
Sorry for not posting earlier.
Well

I've tried this :

  ProcessID := GetWindowThreadProcessID(Form1.Handle, ProcessID);
  ShowMessage('Form PID : '+IntToStr(ProcessID));   /// Everyhting ok here...

  ProcessHandle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_OPERATION or
                               PROCESS_VM_READ or PROCESS_VM_WRITE, false, ProcessID);

  ShowMessage('Form HID : '+IntToStr(ProcessHandle)); // This is 0 ... it shouldn't be 0...
0
 
LVL 4

Expert Comment

by:Meldrachaun
ID: 18120701
Don't do

ProcessID := GetWindowThreadProcessID(Form1.Handle, ProcessID);

 Just do

GetWindowThreadProcessID(Form1.Handle, ProcessID);
0
 
LVL 16

Author Comment

by:CodedK
ID: 18122571
Thank you very much for your time & your help :)
0
 
LVL 4

Expert Comment

by:Meldrachaun
ID: 18127313
you're welcome.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction The parallel port is a very commonly known port, it was widely used to connect a printer to the PC, if you look at the back of your computer, for those who don't have newer computers, there will be a port with 25 pins and a small print…
In this tutorial I will show you how to use the Windows Speech API in Delphi. I will only cover basic functions such as text to speech and controlling the speed of the speech. SAPI Installation First you need to install the SAPI type library, th…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Suggested Courses
Course of the Month10 days, 16 hours left to enroll

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question