学习c++ (八) 关于inline hook时执行自己 的代码

几个小问题,汇总一下

一、关于读出内存时,如果是中文的字符,请注意字符编码的问题,比如最近做的一个程序拿出来的一直是乱码,那不妨这样试试

char* charToGBK(const char* str)
{    
    int    textlen = 0;
    wchar_t* result;
    textlen = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
    result = (wchar_t*)malloc((textlen + 1) * sizeof(wchar_t));
    memset(result, 0, (textlen + 1) * sizeof(wchar_t));
    MultiByteToWideChar(CP_UTF8, 0, str, -1, (LPWSTR)result, textlen);

    textlen = WideCharToMultiByte(CP_ACP, 0, result, -1, NULL, 0, NULL, NULL);
    char* strGBK = new char[textlen];
    WideCharToMultiByte(CP_ACP, 0, result, -1, strGBK, textlen, NULL, NULL);
     
    return    strGBK;
}

二、在内存中植入代码时,执行自己的代码

_declspec(naked) void OnCall() {
    __asm {
        //mov EXesp, esp
        //pushfd
        pushad

        push 0x11
        push 0x22
        call addsum
        
        add esp, 0x8;
        popad
        
        //popfd
        call calloriaddr
        jmp jmbback
    }
}

addsum是c++写的,然后直接在asm中执行,并且传了两个参数,参数的传递顺序是,先push的,是后面的参数,比如上面的就表示 addsum(22,11)

执行完了之后,有一个堆栈平衡的问题,所以我在后面执行了一个add esp,0x8,这是一个固定写法,但0x8是按你传的参数来的,一个参数为4,两个参数为8,三个就是C了

第三个问题是如何打印调试信息,正常调试时,可以在ide里看到调试信息,但是已经成exe或dll时,可以考虑用另外的办法

#define IS_USE_OUTPUT_DEBUG_PRINT   1
#if  IS_USE_OUTPUT_DEBUG_PRINT 

#define  OUTPUT_DEBUG_PRINTF(str)  OutputDebugPrintf(str)
void OutputDebugPrintf(const char* strOutputString, ...)
{
#define PUT_PUT_DEBUG_BUF_LEN   1024
    char strBuffer[PUT_PUT_DEBUG_BUF_LEN] = { 0 };
    va_list vlArgs;
    va_start(vlArgs, strOutputString);
    _vsnprintf_s(strBuffer, sizeof(strBuffer) - 1, strOutputString, vlArgs);  //_vsnprintf_s  _vsnprintf
    //vsprintf(strBuffer,strOutputString,vlArgs);
    va_end(vlArgs);
    OutputDebugStringA(strBuffer);  //OutputDebugString    // OutputDebugStringW

}
#else 
#define  OUTPUT_DEBUG_PRINTF(str) 
#endif

调用:
OutputDebugPrintf("DEBUG_INFO | result: %s", itc);

然后用DebugView查看,过滤一下DEBUG_INFO,即可以看到了

原文地址:https://www.cnblogs.com/szyicol/p/13080092.html