Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Easy API hooking in Windows CE

0.00/5 (No votes)
13 Nov 2010 1  
An easy intro to kernel API hooking in Windows Mobile / CE
I won't go into all the interesting things you can do with API hooking as there are lots of articles on CodeProject already about that. But, here's a quick and easy way to do it under Windows CE / Windows Mobile.
 
You need platform builder for pkfuncs.h and psyscall.h and access to the private sources for kernel.h. Fortunately for the rest of you, however, all these things can be found by some quick Internet searches, too.
 
This example will subvert the GetTickCount() API to print 12345 and then restore it to its original state.
 
#include <psyscall.h>
#include <pkfuncs.h>
#include <kernel.h>

DWORD WINAPI Hook_GetTickCount( VOID )
{
    return 12345;
}
 
/// swap two function pointers
void SwapPFN( PFNVOID* a, PFNVOID* b )
{
    PFNVOID temp = *a;
    *a = *b;
    *b = temp;
}
 
int _tmain( int argc, _TCHAR* argv[] )
{
    // Give ourselves phenomenal cosmic powers
    DWORD old_permissions = ::SetProcPermissions( 0xFFFFFFFF );
    ::SetKMode( TRUE );
 
    // get access to the kernel data page and the WIN32 API pointers
    CINFO** api_sets = ( CINFO** )( UserKInfo[ KINX_APISETS ] );
    CINFO* win32_api = api_sets[ SH_WIN32 ];
 
    PFNVOID pfnHook_GetTickCount = ( PFNVOID )Hook_GetTickCount;
 
    // swap the usual GetTickCount() with our Hook_GetTickCount()
    SwapPFN( &win32_api->m_ppMethods[ W32_GetTickCount ], &pfnHook_GetTickCount );
    NKDbgPrintfW( L"Hooked: %d\r\n", ::GetTickCount() );
 
    // restore the original GetTickCount()
    SwapPFN( &win32_api->m_ppMethods[ W32_GetTickCount ], &pfnHook_GetTickCount );
    NKDbgPrintfW( L"Unhooked: %d\r\n", ::GetTickCount() );
 
    // restore our original permissions
    ::SetProcPermissions( old_permissions );
    ::SetKMode( FALSE );
    return 0;
}
 
For me, this prints:
 
Hooked: 12345
Unhooked: 2596716
 
Unfortunately, the reason this is easy is because it's incomplete. While this will work for your process, any other process that tries to call GetTickCount() while you've hooked it will crash and burn. Why? Because the function pointer address we put in the kernel API table is local to our process. Other processes can't access memory in our process.
 
The solution to that little conundrum will be posted soon!
 
Enjoy!
PaulH

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here