root/lang/objective-cplusplus/i3/trunk/tmp/dwmedit/ApiHook.cc @ 39066

Revision 39066, 2.6 kB (checked in by saturday06, 19 months ago)

zsiodf

  • Property svn:executable set to *
Line 
1
2#include "ApiHook.h"
3#include "WindowsVersionHelp.h"
4#include <tlhelp32.h>
5
6namespace api_hook {
7
8    /**
9     * �ЂƂ‚̃��W���[���ɑ΂���PI�t�b�N����֐�
10     * @see http://ruffnex.oc.to/kenji/text/api_hook/
11     */
12    void ReplaceIATEntryInOneMod(
13        const char* pszModuleName,
14        void* pfnCurrent,
15        void* pfnNew,
16        HMODULE hmodCaller)
17    {
18        ULONG ulSize = 0;
19        IMAGE_IMPORT_DESCRIPTOR* pImportDesc =
20            reinterpret_cast<IMAGE_IMPORT_DESCRIPTOR*>(
21                dll.ImageDirectoryEntryToData(
22                    hmodCaller, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &ulSize));
23
24        if (pImportDesc == NULL) {
25            return;
26        }
27
28        for (; pImportDesc->Name; ++pImportDesc) {
29            char* pszModName = reinterpret_cast<char*>(hmodCaller) + pImportDesc->Name;
30            if (lstrcmpiA(pszModName, pszModuleName) == 0) {
31                break;
32            }
33        }
34
35        if (!pImportDesc->Name) {
36            return;
37        }
38
39        IMAGE_THUNK_DATA* pThunk =
40            reinterpret_cast<IMAGE_THUNK_DATA*>(
41                reinterpret_cast<char*>(hmodCaller) + pImportDesc->FirstThunk);
42
43        for (; pThunk->u1.Function; ++pThunk) {
44            void** ppfn = reinterpret_cast<void**>(&pThunk->u1.Function);
45            if (*ppfn != pfnCurrent) {
46                continue;
47            }
48            DWORD dwDummy = 0;
49            VirtualProtect(ppfn, sizeof(ppfn), PAGE_EXECUTE_READWRITE, &dwDummy);
50            // DLL code will be CoW
51            WriteProcessMemory(GetCurrentProcess(), ppfn, &pfnNew, sizeof(pfnNew), NULL);
52            return;
53        }
54    }
55
56    /**
57     * ���ׂẴ��W���[���ɑ΂���PI�t�b�N����֐�
58     * @see http://ruffnex.oc.to/kenji/text/api_hook/
59     */
60    void ReplaceIATEntryInAllMods(
61        const char* pszModuleName,
62        void* pfnCurrent,
63        void* pfnNew)
64    {
65        // ���W���[�����X�g���
66        HANDLE hModuleSnap = CreateToolhelp32Snapshot(
67                                 TH32CS_SNAPMODULE, GetCurrentProcessId());
68        if(hModuleSnap == INVALID_HANDLE_VALUE) {
69            return;
70        }
71   
72        MODULEENTRY32 me = {};
73        me.dwSize = sizeof(me);
74        BOOL bModuleResult = Module32First(hModuleSnap, &me);
75        // ���ꂼ�����W���[���ɑ΂���eplaceIATEntryInOneMod��s
76        while (bModuleResult) {
77            ReplaceIATEntryInOneMod(pszModuleName, pfnCurrent, pfnNew, me.hModule);
78            bModuleResult = Module32Next(hModuleSnap, &me);
79        }
80        CloseHandle(hModuleSnap);
81    }
82}
Note: See TracBrowser for help on using the browser.