如何在另一个进程的内存中搜索字符串?

时间:2015-01-30 07:18:02

标签: c++ windows winapi

目前我正在使用这个功能,我通过互联网阅读几个松散相关的问题拼凑而成。我遇到的问题是,我第一次运行它时返回错误,但不幸的是我无法重现它。现在,当我运行它时,它每次只返回0.

DWORD GetAddressOfString(char *input)
{
    unsigned char *p = NULL;
    MEMORY_BASIC_INFORMATION info;
    HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, _processID);

    for (p = NULL; VirtualQueryEx(process, p, &info, sizeof(info)) == sizeof(info); p += info.RegionSize)
    {
        if (info.State == MEM_COMMIT && (info.Type == MEM_MAPPED || info.Type == MEM_PRIVATE))
        {
            char *buffer = new char[info.RegionSize];
            SIZE_T bytesRead;
            ReadProcessMemory(process, p, &buffer, info.RegionSize, &bytesRead);
            for (int i = 0; i <= (info.RegionSize - sizeof(input)); i++)
            {
                if (memcmp(input, &buffer[i], sizeof(input)) == 0)
                {
                    return i;
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:6)

这是一个快速而又脏的版本,可以自行搜索数据。如果打开Notepad ++,键入&#34; SomeDataToFind&#34;,用正确的值替换pid,并运行它,它也应该找到数据。它可能会给你一些开始和装饰,以满足你的需求。

你的代码正在搜索错误的长度,返回错误的偏移量,像筛子一样泄漏内存,并且不总是返回一个未定义行为的值。

#include <Windows.h>
#include <iostream>
#include <string>
#include <vector>

char* GetAddressOfData(DWORD pid, const char *data, size_t len)
{
    HANDLE process = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pid);
    if(process)
    {
        SYSTEM_INFO si;
        GetSystemInfo(&si);

        MEMORY_BASIC_INFORMATION info;
        std::vector<char> chunk;
        char* p = 0;
        while(p < si.lpMaximumApplicationAddress)
        {
            if(VirtualQueryEx(process, p, &info, sizeof(info)) == sizeof(info))
            {
                p = (char*)info.BaseAddress;
                chunk.resize(info.RegionSize);
                SIZE_T bytesRead;
                if(ReadProcessMemory(process, p, &chunk[0], info.RegionSize, &bytesRead))
                {
                    for(size_t i = 0; i < (bytesRead - len); ++i)
                    {
                        if(memcmp(data, &chunk[i], len) == 0)
                        {
                            return (char*)p + i;
                        }
                    }
                }
                p += info.RegionSize;
            }
        }
    }
    return 0;
}

int main()
{
    const char someData[] = "SomeDataToFind";
    std::cout << "Local data address: " << (void*)someData << "\n";

    //Pass whatever process id you like here instead.
    DWORD pid = GetCurrentProcessId();
    char* ret = GetAddressOfData(pid, someData, sizeof(someData));
    if(ret)
    {
        std::cout << "Found: " << (void*)ret << "\n";
    }
    else
    {
        std::cout << "Not found\n";
    }

    return 0;
}