Click here to Skip to main content
Click here to Skip to main content
Go to top

Stealing Program's Memory

, 2 Dec 2003
Rate this:
Please Sign up or sign in to vote.
An advanced article on allocating and using memory in another process using the Win32 API.

Introduction

I was recently trying to steal strings from another program's listview control. You need to pass a pointer so it knows where to put the string. Normally this wouldn't be a problem, but because Windows uses virtual memory pointers are not valid across programs.

Virtual memory is how Windows deals out memory to all it's programs. It makes programs think they have 2 Gb of memory to use. It also protects programs from using each other's memory so if one program crashes it doesn't take down the whole system with it.

So after coding a fair bit, I realized my pointers were all invalid and it wouldn't work. A few hours of digging through MSDN brought me to the functions VirtualAllocEx(), VirtualFreeEx(), WriteProcessMemory() and ReadProcessMemory(). Armed with this new information, I set out to modify my code. Here is what I had so far:

#define WIN32_LEAN_AND_MEAN
#include <stdio.h>
#include <windows.h>
#include <commctrl.h>

int main(void) {
 /* Run through the windows until we find our listview. */
 HWND hwnd=FindWindow(NULL, "Stealing Program's Memory: ListView");
 HWND listview=FindWindowEx(hwnd, NULL, "SysListView32", NULL);

 int count=(int)SendMessage(listview, LVM_GETITEMCOUNT, 0, 0);
 int i;

 char item[512], subitem[512];

 /* Shove all items of listview into item and subitem
    and print out one by one. */

 LVITEM lvi;
 lvi.cchTextMax=512;

 for(i=0; i<count; i++) {
  lvi.iSubItem=0;
  lvi.pszText=item;
  SendMessage(listview, LVM_GETITEMTEXT, (WPARAM)i, (LPARAM)&lvi);

  lvi.iSubItem=1;
  lvi.pszText=subitem;
  SendMessage(listview, LVM_GETITEMTEXT, (WPARAM)i, (LPARAM)&lvi);

  printf("%s - %s\n", item, subitem);
 }
 return 0;
}

As I said before, this won't work. The pointers to lvi, item, and subitem all get screwed when they go across process. The solution? Use WriteProcessMemory() and ReadProcessMemory() to use the other programs memory, perform LVM_GETITEMTEXT on it, and read it back. Hackish yes, but then again reading items from another program's listview control is one giant hack.

First, we get the process of the listview like this:

unsigned long pid;
HANDLE process;
GetWindowThreadProcessId(listview, &pid);
process=OpenProcess(PROCESS_VM_OPERATION|PROCESS_VM_READ|
                    PROCESS_VM_WRITE|PROCESS_QUERY_INFORMATION, FALSE, pid);

Next We create three pointers, LVITEM *_lvi, char *_item, and char *_subitem and allocate them in the other program's virtual memory space with VirtualAllocEx():

LVITEM *_lvi=(LVITEM*)VirtualAllocEx(process, NULL, sizeof(LVITEM),
                                     MEM_COMMIT, PAGE_READWRITE);
char *_item=(char*)VirtualAllocEx(process, NULL, 512, MEM_COMMIT,
                                  PAGE_READWRITE);
char *_subitem=(char*)VirtualAllocEx(process, NULL, 512, MEM_COMMIT,
                                     PAGE_READWRITE);

Now we point lvi.pszText to _item, and copy it's memory to _lvi using WriteMemoryProcess():

lvi.pszText=_item;
WriteProcessMemory(process, _lvi, &lvi, sizeof(LVITEM), NULL);

Now that we have an LVITEM pointer that is valid in the other programs virtual memory, we can shoot off LVM_GETITEMTEXT to listview and copy _item's text into item so we can read it in our program:

SendMessage(hwnd, LVM_GETITEMTEXT, (WPARAM)i, (LPARAM)_lvi);
ReadProcessMemory(process, _item, item, max, NULL);

Repeat that for subitem, then free the memory we used in the other program's memory:

VirtualFreeEx(process, _lvi, 0, MEM_RELEASE);
VirtualFreeEx(process, _item, 0, MEM_RELEASE);
VirtualFreeEx(process, _subitem, 0, MEM_RELEASE);

Yay, all done. In case that didn't make too much sense to you, here is our new code, all fixed up:

#define WIN32_LEAN_AND_MEAN
#include <stdio.h>
#include <windows.h>
#include <commctrl.h>

int main(void) {
 HWND hwnd=FindWindow(NULL, "Stealing Program's Memory: ListView");
 HWND listview=FindWindowEx(hwnd, NULL, "SysListView32", NULL);

 int count=(int)SendMessage(listview, LVM_GETITEMCOUNT, 0, 0);
 int i;

 LVITEM lvi, *_lvi;
 char item[512], subitem[512];
 char *_item, *_subitem;
 unsigned long pid;
 HANDLE process;

 GetWindowThreadProcessId(listview, &pid);
 process=OpenProcess(PROCESS_VM_OPERATION|PROCESS_VM_READ|
                     PROCESS_VM_WRITE|PROCESS_QUERY_INFORMATION, FALSE, pid);

 _lvi=(LVITEM*)VirtualAllocEx(process, NULL, sizeof(LVITEM),
                              MEM_COMMIT, PAGE_READWRITE);
 _item=(char*)VirtualAllocEx(process, NULL, 512, MEM_COMMIT,
                             PAGE_READWRITE);
 _subitem=(char*)VirtualAllocEx(process, NULL, 512, MEM_COMMIT,
                                PAGE_READWRITE);

 lvi.cchTextMax=512;

 for(i=0; i<count; i++) {
  lvi.iSubItem=0;
  lvi.pszText=_item;
  WriteProcessMemory(process, _lvi, &lvi, sizeof(LVITEM), NULL);
  SendMessage(listview, LVM_GETITEMTEXT, (WPARAM)i, (LPARAM)_lvi);

  lvi.iSubItem=1;
  lvi.pszText=_subitem;
  WriteProcessMemory(process, _lvi, &lvi, sizeof(LVITEM), NULL);
  SendMessage(listview, LVM_GETITEMTEXT, (WPARAM)i, (LPARAM)_lvi);

  ReadProcessMemory(process, _item, item, 512, NULL);
  ReadProcessMemory(process, _subitem, subitem, 512, NULL);

  printf("%s - %s\n", item, subitem);
 }

 VirtualFreeEx(process, _lvi, 0, MEM_RELEASE);
 VirtualFreeEx(process, _item, 0, MEM_RELEASE);
 VirtualFreeEx(process, _subitem, 0, MEM_RELEASE);

 return 0;
}

If you're looking to use a program's memory for another reason, or have had a similar problem to mine, adapting this should be fairly easy.

This article was originally written for int64.org

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Cory Nelson
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
AnswerRe: Doesn't work in Vista 64 [modified] Pinmemberderek_penguin6-Nov-09 21:30 
GeneralRe: Doesn't work in Vista 64 PinmemberZockerman™22-May-12 7:04 
GeneralVirtualAllocEx problems PinmemberCedar8217-Nov-07 4:45 
GeneralStatic Text Pinmemberjosip cagalj23-Aug-07 1:14 
QuestionGetting list vew Data with sendmessage(xxxxx) PinmemberXzion28-Mar-07 21:40 
Questionwhat if not window default control Pinmember9999kkk25-Nov-06 0:04 
GeneralA Clever Utility, and an Explanation of Cross-Process Copying of Data PinmemberMike O'Neill6-Sep-06 16:14 
GeneralC# Version PinmemberMarco225028-Aug-06 15:57 
Hi. I'm trying to convert to C# but I got a null buffer (all items are \0).
 
Please, can someone help me?
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
 
namespace WindowsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
 
private void Form1_Load(object sender, EventArgs e)
{
IntPtr mainWindowHwnd;
IntPtr lvwHwnd = (IntPtr)0;
 
try
{
mainWindowHwnd = FindWindow(null, "Stealing Program's memory: ListView");
lvwHwnd = FindWindowEx(mainWindowHwnd, IntPtr.Zero, "SysListView32", IntPtr.Zero);
 
if (lvwHwnd == (IntPtr)0)
throw new Win32Exception();
}
catch(Exception ex)
{
MessageBox.Show("[" + Marshal.GetLastWin32Error().ToString() + "] - Não foi possível obter o handle do controle filho.\n\n" + ex.ToString(), "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
 
int lvwItem = 0;
 
IntPtr pid = (IntPtr)0;
GetWindowThreadProcessId(lvwHwnd, ref pid);
 
IntPtr _lvi;
IntPtr _subitem = IntPtr.Zero;
 
IntPtr process = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, false, pid.ToInt32());
 
LVITEM lvi = new LVITEM();
 
//process = (IntPtr)(process.ToInt32() - 1);
_lvi = VirtualAllocEx(process, IntPtr.Zero, Marshal.SizeOf(typeof(LVITEM)), MEM_COMMIT, PAGE_READWRITE);
_subitem = VirtualAllocEx(process, IntPtr.Zero, 512, MEM_COMMIT, PAGE_READWRITE);
 
if(_lvi == IntPtr.Zero)
throw new SystemException("Failed to allocate memory in remote process");
 
bool bsuccess;
 
lvi.cchTextMax = 512;
lvi.iSubItem = 1;
lvi.pszText = _subitem;
bsuccess = WriteProcessMemory(process, _lvi, ref lvi, Marshal.SizeOf(typeof(LVITEM)), IntPtr.Zero);
SendMessage(lvwHwnd, LVM_GETITEMTEXT, lvwItem, _lvi);
 
IntPtr lpBuffer;
lpBuffer = Marshal.AllocHGlobal(512);
string sRet;
IntPtr bytesReaded;
byte[] buffer = new byte[512];
ReadProcessMemory(process, _subitem, buffer, 512, out bytesReaded);
//sRet = Marshal.PtrToStringAnsi(lpBuffer, 512);
 
VirtualFreeEx(process, _lvi, 0, MEM_RELEASE);
VirtualFreeEx(process, _subitem, 0, MEM_RELEASE);
}
 
[DllImport("user32.dll",
CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern IntPtr FindWindow(string lpClassName,
string lpWindowName);
 
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindowEx(IntPtr parent /*HWND*/,
IntPtr next /*HWND*/,
string sClassName,
IntPtr sWindowTitle);
 
//'''''''''''''''''''''''''''''''''''''''''''''''
//' Used by the OpenProcess API call
 
private const long STANDARD_RIGHTS_REQUIRED = 0xF0000;
private const long SYNCHRONIZE = 0x100000;
 
private const int PROCESS_TERMINATE = 0x1;
private const int PROCESS_CREATE_THREAD = 0x2;
private const int PROCESS_SET_SESSIONID = 0x4;
private const int PROCESS_VM_OPERATION = 0x8;
private const int PROCESS_VM_READ = 0x10;
private const int PROCESS_VM_WRITE = 0x20;
private const long PROCESS_DUP_HANDLE = 0x40;
private const long PROCESS_CREATE_PROCESS = 0x80;
private const long PROCESS_SET_QUOTA = 0x100;
private const long PROCESS_SET_INFORMATION = 0x200;
private const int PROCESS_QUERY_INFORMATION = 0x400;
private const long PROCESS_SUSPEND_RESUME = 0x800;
private const long PROCESS_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF;
 
[DllImport("kernel32")]
public static extern IntPtr OpenProcess(int dwDesiredAccess,
bool bInheritHandle,
int dwProcessID);
//'''''''''''''''''''''''''''''''''''''''''''''''
 
const uint MEM_COMMIT = 0x1000;
const uint MEM_RELEASE = 0x8000;
const uint PAGE_READWRITE = 0x4;
 
[DllImport("kernel32")]
static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress,
int dwSize, uint flAllocationType, uint flProtect);
 

[DllImport("kernel32")]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress,
ref LVITEM buffer, int dwSize, IntPtr lpNumberOfBytesWritten);
 
//Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hWnd As IntPtr, ByVal msg As Int32, ByVal wParam As IntPtr, ByRef lParam As IntPtr) As Boolean
[DllImport("user32.dll")]
static extern bool SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam);
 
private const int LVM_FIRST = 0x1000;
private const long LVM_GETSELECTEDCOUNT = (LVM_FIRST + 50);
private const long LVM_GETITEMSTATE = (LVM_FIRST + 44);
public const int LVM_GETITEMTEXT = (LVM_FIRST + 45);
public const long LVM_GETITEMCOUNT = LVM_FIRST + 4;
private const long LVIF_TEXT = 0x1;
 
//'Public Const LVM_GETITEMA = (LVM_FIRST + 5)
//'Public Const LVM_GETITEMW = (LVM_FIRST + 75)
public const long LVM_GETITEM = (LVM_FIRST + 5);
 

[StructLayout(LayoutKind.Sequential)]
private struct LVITEM
{
public Int16 mask;
public Int16 iItem;
public Int16 iSubItem;
public Int16 state;
public Int16 stateMask;
public IntPtr pszText;
public Int16 cchTextMax;
public Int16 iImage;
}
 
[DllImport("kernel32.dll")]
public static extern bool ReadProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
//[In, Out] byte[] buffer,
IntPtr buffer,
UInt32 size,
out IntPtr lpNumberOfBytesRead
);
 
[DllImport("kernel32.dll")]
public static extern Int32 ReadProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
[In, Out] byte[] buffer,
UInt32 size,
out IntPtr lpNumberOfBytesRead
);
 
[DllImport("kernel32")]
static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr lpAddress, int dwSize,
uint dwFreeType);
 
[DllImport("user32")]
private static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd,
ref IntPtr lpdwProcessId);
}
}
GeneralRe: C# Version PinmemberKarlheinz Godo15-Feb-07 8:40 
GeneralCleaner C# Function Pinmemberdfhgesart7-Jul-07 16:10 
JokeThanks a lot! This is exactly what I'm looking for. Pinmembersongkiet9-Aug-06 8:58 
Questionretrieve text on statusbar Pinmemberdoenoe31-Jul-06 22:22 
AnswerRe: retrieve text on statusbar Pinmemberandy66611-Nov-06 4:19 
QuestionGet strings from Microsoft Outlook SUPERGRID Pinmemberkopyt19-Jul-06 2:13 
QuestionPossible to do same for delphi TStringGrid? PinmemberAbsorbant Pad13-Jun-06 0:10 
Questioncan we write text? Pinmemberaldo hexosa4-Mar-06 2:47 
AnswerRe: can we write text? Pinmembershazzababs12-Oct-09 5:25 
Questionleak? Pinmember[cs2]27-Jan-06 7:11 
GeneralProblem with one App Pinmemberclivet18-Sep-05 0:50 
GeneralRe: Problem with one App Pinmember___Charles___26-Jan-07 17:45 
GeneralSelect and SetText PinmemberJ3ff28-Jul-05 10:30 
Generala PinsussAnonymous9-Dec-04 9:57 
Generalb PinsussAnonymous10-May-05 0:39 
Generalc PinmemberZaibot17-Dec-06 3:52 
Generald Pinmembergames guru1-Aug-07 13:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140921.1 | Last Updated 3 Dec 2003
Article Copyright 2003 by Cory Nelson
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid