虚拟内存示例代码 WinApi C++

发布于 2024-12-08 17:05:52 字数 5551 浏览 1 评论 0原文

我对有关内存分配的教程代码有一些问题。 下面有一段代码,它的作用是: 1)打印虚拟内存数据 2)内存分配 3)打印虚拟内存数据 4)内存释放 5) 打印虚拟内存数据

我才开始学习 WinApi 的 C++。有人可以帮我写代码吗? 我无法编译它。我收到一些错误(如下所示)。 据我所知,这段代码在 MS Visual Studio 的早期版本中可以正常工作。 目前我正在使用 2010 版本。 提前致谢。

 #include "stdafx.h"

LPVOID myblock[5];
BOOL alloc = FALSE;

PCTSTR GetProtectText(MEMORY_BASIC_INFORMATION mbi)
{
    PCTSTR p = "Unknown";
    if(mbi.State == MEM_FREE) mbi.Protect = PAGE_NOACCESS;
    if(mbi.State == MEM_RESERVE) mbi.Protect = mbi.AllocationProtect;
    switch (mbi.Protect & ~(PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE))
    {
        case PAGE_READONLY:          p = "-R--"; break;
        case PAGE_READWRITE:         p = "-RW-"; break;
        case PAGE_WRITECOPY:         p = "-RWC"; break;
        case PAGE_EXECUTE:           p = "E---"; break;
        case PAGE_EXECUTE_READ:      p = "ER--"; break;
        case PAGE_EXECUTE_READWRITE: p = "ERW-"; break;
        case PAGE_EXECUTE_WRITECOPY: p = "ERWC"; break;
        case PAGE_NOACCESS:          p = "----"; break;
    }
    return(p);
}

PCTSTR GetMemStorageText(MEMORY_BASIC_INFORMATION mbi)
{
   PCTSTR p = TEXT("Unknown");

   switch (mbi.State)
   {
        case MEM_FREE:      p = "Free";     break;
        case MEM_RESERVE:       p = "Reserve";  break;
        case MEM_COMMIT:
            switch (mbi.Type)
            {
                case MEM_FREE:  p = "Free";     break;
                case MEM_RESERVE:   p = "Reserve";  break;
                case MEM_IMAGE: p = "Image";    break;
                case MEM_MAPPED:    p = "Mapped";   break;
                case MEM_PRIVATE:   p = "Private";  break;
            }
            break;
   }
   return(p);
}

VOID MemoryMap()
{
    DWORD dwProcessId = GetCurrentProcessId(),
    dwNeeded = 0;
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);
    HMODULE lpModule[40];  //handle to a module
    LPVOID lpModuleAddress[40];
    MODULEINFO ModuleInfo; //structure contains the module load address, size, and entry point. 

    EnumProcessModules(hProcess, lpModule, sizeof(HMODULE)*40, &dwNeeded);

    dwNeeded /= sizeof(HMODULE);

    for(UINT i = 0;i < dwNeeded;i++)
    {
        GetModuleInformation(hProcess, lpModule[i], &ModuleInfo, sizeof(ModuleInfo));
        lpModuleAddress[i] = ModuleInfo.lpBaseOfDll;
    }

    MEMORY_BASIC_INFORMATION mbi; //structure contains information about a range of                       //pages in the virtual address space of a process
    PVOID lpAddress = NULL;

    printf("  Address\tBlok Size\tStorage\t\tProtect\n");
    CHAR str[255];

    while(VirtualQueryEx(hProcess, lpAddress, &mbi, sizeof(mbi)))
    {
        if(!(((UINT)lpAddress) % 0x10000))
        {
            printf("0x%p\t\t\t%s", lpAddress, GetMemStorageText(mbi));
            for(int i = 0;i < 5;i++)
                if(myblock[i] == lpAddress && alloc) printf("\n(My Al-location Block)");

            for(int i = 0;i < dwNeeded;i++)
                if(lpAddress == lpModuleAddress[i])
                {
                    GetModuleFileName(lpModule[i], str, 255);
                    printf("\n(Image: %s)", str);
                }
            printf("\n");
        }
        printf("  0x%p\t0x%p\t%s\t\t%s\n", lpAddress, (DWORD)mbi.RegionSize,
            GetMemStorageText(mbi), GetProtectText(mbi));
        lpAddress = ((PBYTE)lpAddress + mbi.RegionSize);
    };
}

VOID Allocation()
{
    alloc = TRUE;
    myblock[0] = VirtualAlloc(NULL, 1024, MEM_RESERVE, PAGE_READONLY);
    myblock[1] = VirtualAlloc(NULL, 1024*2, MEM_RESERVE, PAGE_READWRITE);
    myblock[2] = VirtualAlloc(NULL, 1024*8, MEM_RESERVE, PAGE_EXECUTE);
    myblock[3] = VirtualAlloc(NULL, 1024*16, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READ);
    myblock[4] = VirtualAlloc(NULL, 1024*16, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE);
}

VOID Release()
{
    for(int i = 0;i < 5;i++)
        VirtualFree(myblock[i], 0, MEM_RELEASE);
    alloc = FALSE;
}



INT _tmain(INT argc, _TCHAR* argv[])
{
    printf("\nProcess Virtual Memory Before Allocation Memory:\n");
    MemoryMap();
    printf("\nProcess Virtual Memory After Allocation Memory:\n");
    Allocation();
    MemoryMap();
    printf("\nProcess Virtual Memory After Release Memory:\n");
    Release();
    MemoryMap();
    getch();
    return 0;
}

1>------ Build started: Project: VirtMemory, Configuration: Debug Win32 ------
1>Build started 06.10.2011 23:51:01.
1>InitializeBuildStatus:
1>  Touching ".\Debug\VirtMemory.unsuccessfulbuild".
1>ClCompile:
1>  VirtMemory.cpp
1>e:\виртуальная память\kod1\virtmemory.cpp(80): warning C4018: '<' : signed/unsigned mismatch
1>e:\виртуальная память\kod1\virtmemory.cpp(123): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          d:\program files\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>ManifestResourceCompile:
1>  All outputs are up-to-date.
1>VirtMemory.obj : error LNK2019: unresolved external symbol _GetModuleInformation@16 referenced in function "void __cdecl MemoryMap(void)" (?MemoryMap@@YAXXZ)
1>VirtMemory.obj : error LNK2019: unresolved external symbol _EnumProcessModules@16 referenced in function "void __cdecl MemoryMap(void)" (?MemoryMap@@YAXXZ)
1>.\Debug\VirtMemory.exe : fatal error LNK1120: 2 unresolved externals
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:01.43
enter code here

I have some problems with tutorial code about Memory allocation.
Below there is a code which do:
1) print virtal memory data
2) memory allocation
3) print virtal memory data
4) memory releasing
5) print virtal memory data

I am only starting learning C++ for WinApi. Can somebody help me with code?
I cannot compile it.I am getting some errors(are shown below).
As I know this code worked correctly in earlier versions of MS Visual Studio.
Currently I am working with 2010 version.
Thanks in advance.

 #include "stdafx.h"

LPVOID myblock[5];
BOOL alloc = FALSE;

PCTSTR GetProtectText(MEMORY_BASIC_INFORMATION mbi)
{
    PCTSTR p = "Unknown";
    if(mbi.State == MEM_FREE) mbi.Protect = PAGE_NOACCESS;
    if(mbi.State == MEM_RESERVE) mbi.Protect = mbi.AllocationProtect;
    switch (mbi.Protect & ~(PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE))
    {
        case PAGE_READONLY:          p = "-R--"; break;
        case PAGE_READWRITE:         p = "-RW-"; break;
        case PAGE_WRITECOPY:         p = "-RWC"; break;
        case PAGE_EXECUTE:           p = "E---"; break;
        case PAGE_EXECUTE_READ:      p = "ER--"; break;
        case PAGE_EXECUTE_READWRITE: p = "ERW-"; break;
        case PAGE_EXECUTE_WRITECOPY: p = "ERWC"; break;
        case PAGE_NOACCESS:          p = "----"; break;
    }
    return(p);
}

PCTSTR GetMemStorageText(MEMORY_BASIC_INFORMATION mbi)
{
   PCTSTR p = TEXT("Unknown");

   switch (mbi.State)
   {
        case MEM_FREE:      p = "Free";     break;
        case MEM_RESERVE:       p = "Reserve";  break;
        case MEM_COMMIT:
            switch (mbi.Type)
            {
                case MEM_FREE:  p = "Free";     break;
                case MEM_RESERVE:   p = "Reserve";  break;
                case MEM_IMAGE: p = "Image";    break;
                case MEM_MAPPED:    p = "Mapped";   break;
                case MEM_PRIVATE:   p = "Private";  break;
            }
            break;
   }
   return(p);
}

VOID MemoryMap()
{
    DWORD dwProcessId = GetCurrentProcessId(),
    dwNeeded = 0;
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);
    HMODULE lpModule[40];  //handle to a module
    LPVOID lpModuleAddress[40];
    MODULEINFO ModuleInfo; //structure contains the module load address, size, and entry point. 

    EnumProcessModules(hProcess, lpModule, sizeof(HMODULE)*40, &dwNeeded);

    dwNeeded /= sizeof(HMODULE);

    for(UINT i = 0;i < dwNeeded;i++)
    {
        GetModuleInformation(hProcess, lpModule[i], &ModuleInfo, sizeof(ModuleInfo));
        lpModuleAddress[i] = ModuleInfo.lpBaseOfDll;
    }

    MEMORY_BASIC_INFORMATION mbi; //structure contains information about a range of                       //pages in the virtual address space of a process
    PVOID lpAddress = NULL;

    printf("  Address\tBlok Size\tStorage\t\tProtect\n");
    CHAR str[255];

    while(VirtualQueryEx(hProcess, lpAddress, &mbi, sizeof(mbi)))
    {
        if(!(((UINT)lpAddress) % 0x10000))
        {
            printf("0x%p\t\t\t%s", lpAddress, GetMemStorageText(mbi));
            for(int i = 0;i < 5;i++)
                if(myblock[i] == lpAddress && alloc) printf("\n(My Al-location Block)");

            for(int i = 0;i < dwNeeded;i++)
                if(lpAddress == lpModuleAddress[i])
                {
                    GetModuleFileName(lpModule[i], str, 255);
                    printf("\n(Image: %s)", str);
                }
            printf("\n");
        }
        printf("  0x%p\t0x%p\t%s\t\t%s\n", lpAddress, (DWORD)mbi.RegionSize,
            GetMemStorageText(mbi), GetProtectText(mbi));
        lpAddress = ((PBYTE)lpAddress + mbi.RegionSize);
    };
}

VOID Allocation()
{
    alloc = TRUE;
    myblock[0] = VirtualAlloc(NULL, 1024, MEM_RESERVE, PAGE_READONLY);
    myblock[1] = VirtualAlloc(NULL, 1024*2, MEM_RESERVE, PAGE_READWRITE);
    myblock[2] = VirtualAlloc(NULL, 1024*8, MEM_RESERVE, PAGE_EXECUTE);
    myblock[3] = VirtualAlloc(NULL, 1024*16, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READ);
    myblock[4] = VirtualAlloc(NULL, 1024*16, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE);
}

VOID Release()
{
    for(int i = 0;i < 5;i++)
        VirtualFree(myblock[i], 0, MEM_RELEASE);
    alloc = FALSE;
}



INT _tmain(INT argc, _TCHAR* argv[])
{
    printf("\nProcess Virtual Memory Before Allocation Memory:\n");
    MemoryMap();
    printf("\nProcess Virtual Memory After Allocation Memory:\n");
    Allocation();
    MemoryMap();
    printf("\nProcess Virtual Memory After Release Memory:\n");
    Release();
    MemoryMap();
    getch();
    return 0;
}

1>------ Build started: Project: VirtMemory, Configuration: Debug Win32 ------
1>Build started 06.10.2011 23:51:01.
1>InitializeBuildStatus:
1>  Touching ".\Debug\VirtMemory.unsuccessfulbuild".
1>ClCompile:
1>  VirtMemory.cpp
1>e:\виртуальная память\kod1\virtmemory.cpp(80): warning C4018: '<' : signed/unsigned mismatch
1>e:\виртуальная память\kod1\virtmemory.cpp(123): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          d:\program files\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>ManifestResourceCompile:
1>  All outputs are up-to-date.
1>VirtMemory.obj : error LNK2019: unresolved external symbol _GetModuleInformation@16 referenced in function "void __cdecl MemoryMap(void)" (?MemoryMap@@YAXXZ)
1>VirtMemory.obj : error LNK2019: unresolved external symbol _EnumProcessModules@16 referenced in function "void __cdecl MemoryMap(void)" (?MemoryMap@@YAXXZ)
1>.\Debug\VirtMemory.exe : fatal error LNK1120: 2 unresolved externals
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:01.43
enter code here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

给我一枪 2024-12-15 17:05:52

获取模块信息& EnumProcessModules 将要求您正确包含并链接 psapi.lib

您可以在项目顶部轻松添加:

#include <Psapi.h>
#pragma comment(lib, "psapi.lib")

GetModuleInformation & EnumProcessModules will require that you properly include and link with psapi.lib

You can do so easily at the top of your project add:

#include <Psapi.h>
#pragma comment(lib, "psapi.lib")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文