#include "stdafx.h"
#include "EZDetour.h"
#include <assert.h>
#include <detours/detours.h>
#include "log/my_log.h"
//#include "MyCommon.h"
extern FARPROC MyGetProcAddress(const char* dll_name, const char* fun_name);


namespace my
{

LONG WINAPI EZDetour::Attach(_Inout_ PVOID &ppPointer, _In_ PVOID pDetour)
{
    if (ppPointer == 0 || pDetour == 0) {
        assert(true);
        return 0;
    }

    addr_ = ppPointer;
    pDetourFunc_ = pDetour;
    DetourRestoreAfterWith();
    DetourTransactionBegin();
    LONG result = 0;
    MyLogD("addr_, pDetourFunc_ = %016I64X, %016I64X.\n", addr_, pDetourFunc_);
    result = DetourAttach(&(PVOID&)addr_, pDetourFunc_);
    LONG result2 = DetourTransactionCommit();
    MyLogD("result, result2 = %08X, %08X.\n", result, result2);
    return result2;
}

LONG WINAPI EZDetour::Attach(const char* dll_name, const char* fun_name, _In_ PVOID pDetour)
{
    FARPROC addr = MyGetProcAddress(dll_name, fun_name);
    return this->Attach((PVOID&)addr, pDetour);
}


LONG WINAPI EZDetour::detach(_Inout_ PVOID &ppPointer, _In_ PVOID pDetour)
{
    MyLogD("ppPointer, pDetour = %08X, %08X.\n", ppPointer, pDetour);

    if (ppPointer == 0 || pDetour == 0) {
        assert(true);
        return 0;
    }

    DetourRestoreAfterWith();
    DetourTransactionBegin();
    LONG result = 0;
    result = DetourDetach(&(PVOID&)ppPointer, pDetour);
    LONG result2 = DetourTransactionCommit();
    MyLogD("result, result2 = %08X, %08X.\n", result, result2);
    // ÒÑ¾­Ð¶ÔØÁË
    ppPointer = 0;
    return result2;
}

void detour_func_null()
{
    MY_ENTER_FUNCTION;
}

}