在内存中搜索字符串时的性能问题

时间:2015-09-15 22:32:22

标签: performance memory dll memcmp virtualquery

我在Win32下开发了一个简单的工作DLL:它扫描主机的虚拟内存中的子字符串。但由于某些原因,与使用单线程扫描的Cheat Engine,ArtMoney甚至OllyDbg相比,它的速度非常慢。这是我用VirtualQuery()扫描单个内存部分的函数的代码。主机(.exe应用程序)提交大约300-400 MiB的内存,我必须扫描大约170个不同大小的内存部分,从4KiB到32MiB。我只扫描MEM_PRIVATE,MEM_COMMIT区域,不扫描PAGE_GUARD,PAGE_NOACCESS,PAGE_READONLY,跳过DLL自己的内存。

由于某些原因,性能很糟糕 - 找到单个字符串需要10-12秒。例如,OllyDbg在~2-3秒内找到字符串。

UINT __stdcall ScanAndReplace(UCHAR* pStartAddress, UCHAR* pEndAddress, const char* csSearchFor, const char* csReplaceTo, UINT iLength)
{
    // This function runs inside the single memory section and looks for a specific substring

    // pStartAddress: UCHAR* - The begining of the memory section
    // pEndAddress: UCHAR* - The ending of the memory section
    // csSearchFor: const char* - The pointer to the substring to search for
    // csReplaceTo: const char* - The pointer to the substring to replace with
    // iLength: UINT - max length of csSearchFor substring

    // Total iterations
    UINT iHits = 0;

    // Scan from pStartAddress to (pEndAddress - iLength) and don't overrun memory section
    for (pStartAddress; pStartAddress < (pEndAddress - iLength); ++pStartAddress)
    {
        UINT iIterator = 0;

        // Scan for specific string that begins at current address (pStartAddress) until condition breaks
        for (iIterator; (iIterator < iLength) && (pStartAddress[iIterator] == csSearchFor[iIterator]); ++iIterator);

        // String matches if iIterator == iLength
        if (iIterator == iLength)
        {
            // Found, do something (edit/replace, etc), increment counter...
            ++iHits;
        }

        /*
        // Even if you search for single byte it's very slow
        if (*pStartAddress == 'A')
            ++iHits;
        */
    }

    return iHits;
}

我正在使用MSVS 2010。

编译器命令行:

/nologo /W3 /WX- /O2 /Os /Oy- /GL /D "WIN32" /D "NDEBUG" /D "_WINDOWS"
  /D "_USRDLL" /D "MYDLL_EXPORTS" /D "_WINDLL" /GF /Gm- /MD /GS- /Gy
  /fp:precise /Zc:wchar_t /Zc:forScope /Fp"Release\MyDll.pch" /FAcs
  /Fa"Release\" /Fo"Release\" /Fd"Release\vc100.pdb" /Gd /TC /analyze-
  /errorReport:queue

链接器命令行:

/OUT:"D:\MyDll\Release\MyDll.dll" /INCREMENTAL:NO /NOLOGO /DLL "Dbghelp.lib"
  "msvcrt.lib" "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
  "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib" "oleaut32.lib"
  "uuid.lib" "odbc32.lib" "odbccp32.lib" /NODEFAULTLIB /MANIFEST:NO
  /ManifestFile:"Release\MyDll.dll.intermediate.manifest" /ALLOWISOLATION
  /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /DEBUG
  /PDB:"D:\MyDll\Release\MyDll.pdb" /SUBSYSTEM:WINDOWS /OPT:REF /OPT:ICF
  /PGD:"D:\MyDll\Release\MyDll.pgd" /LTCG /TLBID:1 /ENTRY:"DllMain"
  /DYNAMICBASE /NXCOMPAT /MACHINE:X86 /ERRORREPORT:QUEUE

我做错了什么?我的algorythm是坏的还是有某种&#34;魔法&#34;其他内存扫描仪使用?

1 个答案:

答案 0 :(得分:0)

其他内存扫描仪可能正在使用&#34; magic&#34;以更好的搜索算法的形式,例如Boyer-Moore。他们也可能会对他们的搜索算法进行额外的微观优化,但我猜测算法的选择会占据你所看到的大部分差异。