Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template<CallingConvention calling_convention, typename return_type, typename... args>
- class DynamicCall
- {
- private:
- DWORD m_FunctionAddress;
- HMODULE m_module;
- public:
- using cc_fastcall = return_type(__fastcall *)(args...);
- using cc_cdecl = return_type(__cdecl *)(args...);
- using cc_stdcall = return_type(__stdcall *)(args...);
- inline return_type Call(args... arguments) {
- switch (calling_convention) {
- case CallingConventions::asm_cdecl:
- return (cc_cdecl(this->m_FunctionAddress))(arguments...);
- case CallingConventions::asm_stdcall:
- return (cc_stdcall(this->m_FunctionAddress))(arguments...);
- case CallingConventions::asm_fastcall:
- return (cc_fastcall(this->m_FunctionAddress))(arguments...);
- default:
- return (return_type)0;
- }
- }
- inline return_type operator()(args... arguments) {
- return this->Call(arguments...);
- }
- void Assign(wchar_t *module, DWORD funcHash)
- {
- UNICODE_STRING str;
- RtlInitUnicodeString(&str, module);
- LdrLoadDll(0, 0, &str, &this->m_module);
- this->m_FunctionAddress = (DWORD)_GetProcAddress(this->m_module, funcHash);
- }
- DynamicCall(wchar_t *module, DWORD funcHash)
- {
- this->Assign(module, funcHash);
- }
- DynamicCall()
- {
- }
- };
- //_GetProcAddress (I did not completly write that myself, I used a snippet from rohitab):
- void *_GetProcAddress(HMODULE module, DWORD funcHash)
- {
- char *modb = (char *)module;
- IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER *)modb;
- IMAGE_NT_HEADERS *nt_headers = (IMAGE_NT_HEADERS *)(modb + dos_header->e_lfanew);
- IMAGE_OPTIONAL_HEADER *opt_header = &nt_headers->OptionalHeader;
- IMAGE_DATA_DIRECTORY *exp_entry = (IMAGE_DATA_DIRECTORY *)(&opt_header->DataDirectory[0]);
- IMAGE_EXPORT_DIRECTORY *exp_dir = (IMAGE_EXPORT_DIRECTORY *)(modb + exp_entry->VirtualAddress);
- void **func_table = (void **)(modb + exp_dir->AddressOfFunctions);
- WORD *ord_table = (WORD *)(modb + exp_dir->AddressOfNameOrdinals);
- char **name_table = (char **)(modb + exp_dir->AddressOfNames);
- void *address = NULL;
- for (DWORD i = 0; i < exp_dir->NumberOfNames; i++)
- {
- char *curr = modb + (DWORD)name_table[i];
- //name table pointers are rvas
- if (StrHash(curr) == funcHash)
- {
- address = (void *)(modb + (DWORD)func_table[ord_table[i]]);
- break;
- }
- }
- return address;
- }
- //Usage
- //Global
- DynamicCall<CallingConvention::asm_stdcall, ULONGLONG> _GetTickCount64;
- _GetTickCount64 = DynamicCall<CallingConvention::asm_stdcall, ULONGLONG>(L"Kernel32.dll", 668280486 /* GetTickCount64 */);
- //Inline:
- DynamicCall<CallingConvention::asm_stdcall, int, HWND, LPCTSTR, LPCTSTR, UINT>(L"User32.dll", 3943220947 /* MessageBoxA */)(0, "Test", 0, 0);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement