ACCESS_VIOLATION when use Hook Engine - c++

I have a problem using this hook engine http://www.codeproject.com/Articles/21414/Powerful-x86-x64-Mini-Hook-Engine
Function is hooked correctly, but when i try to call real function(original), error ACCESS_VIOLATION is raising.
My code
typedef int (__stdcall *MyCloseSocket) (SOCKET s);
MyCloseSocket pTrampolineCloseSocket = NULL;
int main()
{
//...
HookFunction((ULONG_PTR) GetProcAddress(LoadLibrary(dll), "closesocket"), (ULONG_PTR) &OwnCloseSocket);
pTrampolineCloseSocket = (MyCloseSocket) GetOriginalFunction((ULONG_PTR) OwnCloseSocket);
}
int OwnCloseSocket(SOCKET fd)
{
// here successfully. Function is hooked
return pTrampolineCloseSocket(fd); // but here ACCESS_VIOLATION
}
What i'm doing wrong? Thanks!

If you are free to choose the technology for hooking I recommend our own hooking engine Deviare because it handles the hooking complexity itself (remote process injection, parameters parsing, race conditions) giving a higher level programming interface. It is available at http://www.nektra.com/products/deviare-api-hook-windows/ hope it will speed up you solution

Depending on the implementation of the rest of your program, you have a potential race condition where your hook function could be called before pTrampolineCloseSocket is set. What's the value of pTrampolineCloseSocket when you crash?

Related

Unhandled exception at 0x6D3800C8 in Konfig32.exe: 0xC000041D after using MS Detours

First of all, I'm a beginner and I started to learn C++ last month, so don't be mad if I can't good explain the problem. :D
I'm using MS Detours to hook some custom functions to original functions from Windows. When I run the software, the original functions which are showing the text inside menus, windows etc. will be changed with my functions which are going to translate the text and show it like original function but just in the other language.
I have done the traditional hooking in C++ where I overwrite hot-patch header of function but the problem is that such hooking doesn't work with an 64-bit software and I realized that I can use MS Detours to do hooking because it is compatible with X86 and X64 software. The traditional hooking worked in 32 bit mode but after implementing MS Detours I get an error:
Unhandled exception at 0x6D3800C8 in Konfig32.exe: 0xC000041D: An unhandled exception was encountered during a user callback.
Here is a photo of it where you can see the function and the exception inside wincore.cpp file
The hooking worked and a checked with debugger that every function was successfully hooked to the original one.
Then the program starts to translate the text and it was successfull and after calling this function i got this error.
I searched for an answer in stackoverflow but none of them was connected with hooking, so it would be great if somebody can say what can be the possible problem or solution.
This is my source code:
// Constructor
CFunctionControll::CFunctionControll(BYTE* pOrigFunc, BYTE* pDetourFunc)
{
m_pOrigFunc = pOrigFunc;
m_pDetourFunc = pDetourFunc;
}
// Destructor
CFunctionControll::~CFunctionControll()
{
Disable();
}
void CFunctionControll::Enable()
{
try
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(LPVOID&)m_pOrigFunc, m_pDetourFunc);
if (!DetourTransactionCommit())
throw transactionerror;
}
catch (TransactionError)
{
// Add proper exception handling later
}
}
void CFunctionControll::Disable()
{
try
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(LPVOID&)m_pOrigFunc, m_pDetourFunc);
if (!DetourTransactionCommit())
throw transactionerror;
}
catch (TransactionError)
{
// Add proper exception handling later
}
}
class TransactionError : public std::exception
{
virtual const char* what() const throw()
{
return "DetourTransactionCommit() failed.";
}
} transactionerror;
The paramerer pOrigFunc is a pointer to the original function and the parameter pDetourFunc is a pointer to my customized function.
I am doing hooking with this CFunctionControll class where I can just say Enable()[to hook a function] or Disable()[to unhook it] :)

Calling a function when thread is exiting in PThreads or Windows

I am creating a C++ library for both Linux (with PThreads) and Windows (with their built-in WinThreads) which can be attached to any program, and needs to have a function called when the thread is exiting, similar to how atexit works for processes.
I know of pthread_cleanup_push and pthread_cleanup_pop for pthreads, but these do not work for me since they are macros that add another lexical scope, whereas I want to declare this function the first time my library is called into, and then allow the program itself to run its own code however it needs to. I haven't found anything similar in Windows whatsoever.
Note that this doesn't mean I want an outside thread to be alerted when the thread stops, or even that I can change the way the thread will be exited, since that is controlled by the program itself, my library is just attached, along for the ride.
So the question is: What is the best way, in this instance, for me to have a function I've written called when the thread closes, in either Windows or Linux, when I have no control over how the thread is created or destroyed?
For example in main program:
void* threadFunc(void* arg)
{
printf("Hello world!\n");
return NULL;
}
int main(int argc, char** argv)
{
int numThreads = 1;
pid_t* pids = NULL;
pids = (pid_t*) calloc(sizeof(pid_t), numThreads);
pthread_create(&ntid, NULL, threadFunc, &nVal);
pthreads[0] = ntid;
pthread_join(pthreads[0], NULL);
return 0;
}
In library:
void callMeOnExit()
{
printf("Exiting Thread!\n");
}
I would want for callMeOnExit to be called when the thread reaches return NULL; in this case, as well as when the main thread reaches the return 0;. Wrapping pthread_exit would work for other cases, and could be a solution, but I'd like a better one if possible.
If anyone has any ideas on how I might be able to do this, that would be great!
So after a few code reviews, we were able to find a much more elegant way to do this in Linux, which matches both what Windows does with Fibers (as Neeraj points out) as well as what I expected to find when I started looking into this issue.
The key is that pthread_key_create takes in, as the second argument, a pointer to a destructor, which is called when any thread which has initialized this TLS data dies. I was already using TLS elsewhere per thread, but a simple store into TLS would get you this feature as well to ensure it was called.
Change this:
pthread_create(&ntid, NULL, threadFunc, &nVal);
into:
struct exitInformData
{
void* (CB*)(void*);
void* data;
exitInformData(void* (cp*)(void*), void* dp): CB(cp) data(dp) {}
};
pthread_create(&ntid, NULL, exitInform, new exitInformData(&threadFunc, &nVal));
Then Add:
void* exitInform(void* data)
{
exitInformData* ei = reinterpret_cast<exitInformData*>(data);
void* r = (ei.CB)(ei.data); // Calls the function you want.
callMeOnExit(); // Calls the exit notification.
delete ei;
return r;
}
For Windows, you could try Fls Callbacks. They FLS system can be used to allocate per thread (ignore the 'fiber' part, each thread contains one fiber) storage. You get this callback to free the storage, but can do other things in the callback as well.
I found out that this has already been asked, although the solution given then may not be the same as what you want...
Another idea might be to simply extend from the pthread_t class/struct, and override the pthread_exit call to call another function as you want it to, then call the superclass pthread_exit

Is there anything like timer and timertask in c++ just like java has?

I am not an experinced c++ programmer. So I just want to know how to implement timer and timertask just like java has in C++. I have tried timer_create example that is in man page of timer_create but It is not working as per my requirement.
I want that after particualar time span an event should fire, and if specific condition fulfills then timer should be canceled.
Any help would be highly appreciated.
Thanks,
Yuvi.
I too was looking for a Java like TimerTask but I needed one for Windows C++ when I came across this question. After a day of researching mostly on SO and learning about passing class member functions, I was able to put together a solution that seems to work well for me. I realize that I am years late in answering this question but maybe someone still looking for this solution will find this useful.
This is a Windows only solution which I tested on Windows 10 using Visual Studio C++. I'm still learning C++ so please be gentle if I've broken any rules. I realize the exceptions are elementary but they are easy to customize to your needs. I created a TimerTask class similar to the Java class. You'll need to derive a new user class from the TimerTask class and create a "task" function that includes the code you want executed at regular intervals. Here is the TimerTask class:
--TimerTask.h--
#pragma once
#include <thread>
class TimerTask {
HANDLE timeoutEvent;
DWORD msTimeout;
bool exit = false;
void* pObj;
static void taskWrapper(TimerTask* pObj) {
while (!pObj->exit) {
DWORD waitResult = WaitForSingleObject(pObj->timeoutEvent, pObj->msTimeout);
if (pObj->exit)
break;
pObj->task();
}
}
public:
TimerTask::TimerTask() {
timeoutEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!timeoutEvent) {
throw "TimerTask CreateEvent Error: ";
}
}
TimerTask::~TimerTask() {
CloseHandle(timeoutEvent);
}
// Derived class must create task function that runs at every timer interval.
virtual void task() = 0;
void start(void* pObj, DWORD msTimeout) {
this->pObj = pObj;
this->msTimeout = msTimeout;
std::thread timerThread(taskWrapper, (TimerTask*)pObj);
timerThread.detach();
}
void stop() {
exit = true;
if (!SetEvent(timeoutEvent))
throw "TimerTask:stop(): Error: ";
}
};
And here is a sample of usage. For brevity I didn't include error checking.
--Test.cpp--
#include "Windows.h"
#include <iostream>
#include "TimerTask.h"
using namespace std;
class KeepAliveTask : public TimerTask {
public:
void task() {
cout << "Insert your code here!\n";
}
};
int main()
{
cout << "Hello, TimerTask!\n";
KeepAliveTask keepAlive;
keepAlive.start(&keepAlive, 1000); // Execute once per second
Sleep(5100); // Pause 5.1s to give time for task thread to run.
keepAlive.stop();
Sleep(1000); // Pause another sec to give time for thread to stop.
return 0;
}
This is generally a very difficult question, since you are inherently asking for some concurrent, or at least asynchronous processing.
The simplest, single-threaded solution is to use something like Posix's alarm(2). This will cause a signal to be sent to your process after a specified time. You need to register a signal handler (e.g. with signal(2)), but you are subject to all its limitations (e.g. you must only call async-safe functions within the handler).
A second, single-threaded option is to use a select-style (or epoll-style) I/O loop and use a kernel timer file descriptor. This is a very recent Linux feature, though, so availability will vary.
Finally, the typical, general solution is to use multiple threads: Make a dedicated thread for the timer whose only purpose is to sleep for the set time span and then execute some code. For this you will have to bear the full weight of concurrent programming responsibilities, such as handling shared data, guaranteeing the absence of races, etc.
Some higher-level libraries like Boost.ASIO and the new standard library provide some nice timing mechanisms once you've decided to go down the multithreaded route.

why do we need to call these functions at run time using function pointers. we can as well call them directly

Having read a bit about function pointers and callbacks, I fail to understand the basic purpose of it. To me it just looks like instead of calling the function directly we use the pointer to that function to invoke it. Can anybody please explain me callbacks and function pointers? How come the callback takes place when we use function pointers, because it seems we just call a function through a pointer to it instead of calling directly?
Thanks
ps: There have been some questions asked here regarding callbacks and function pointers but they do not sufficiently explain my problem.
What is a Callbak function?
In simple terms, a Callback function is one that is not called explicitly by the programmer. Instead, there is some mechanism that continually waits for events to occur, and it will call selected functions in response to particular events.
This mechanism is typically used when a operation(function) can take long time for execution and the caller of the function does not want to wait till the operation is complete, but does wish to be intimated of the outcome of the operation. Typically, Callback functions help implement such an asynchronous mechanism, wherein the caller registers to get inimated about the result of the time consuming processing and continuous other operations while at a later point of time, the caller gets informed of the result.
An practical example:
Windows event processing:
virtually all windows programs set up an event loop, that makes the program respond to particular events (eg button presses, selecting a check box, window getting focus) by calling a function. The handy thing is that the programmer can specify what function gets called when (say) a particular button is pressed, even though it is not possible to specify when the button will be pressed. The function that is called is referred to as a callback.
An source Code Illustration:
//warning: Mind compiled code, intended to illustrate the mechanism
#include <map>
typedef void (*Callback)();
std::map<int, Callback> callback_map;
void RegisterCallback(int event, Callback function)
{
callback_map[event] = function;
}
bool finished = false;
int GetNextEvent()
{
static int i = 0;
++i;
if (i == 5) finished = false;
}
void EventProcessor()
{
int event;
while (!finished)
{
event = GetNextEvent();
std::map<int, Callback>::const_iterator it = callback_map.find(event);
if (it != callback_map.end()) // if a callback is registered for event
{
Callback function = *it;
if (function)
{
(*function)();
}
else
{
std::cout << "No callback found\n";
}
}
}
}
void Cat()
{
std::cout << "Cat\n";
}
void Dog()
{
std::cout << "Dog\n";
}
void Bird()
{
std::cout << "Bird\n";
}
int main()
{
RegisterCallBack(1, Cat);
RegisterCallback(2, Dog);
RegisterCallback(3, Cat);
RegisterCallback(4, Bird);
RegisterCallback(5, Cat);
EventProcessor();
return 0;
}
The above would output the following:
Cat
Dog
Cat
Bird
Cat
Hope this helps!
Note: This is from one of my previous answers, here
One very striking reason for why we need function pointers is that they allow us to call a function that the author of the calling code (that's us) does not know! A call-back is a classic example; the author of qsort() doesn't know or care about how you compare elements, she just writes the generic algorithm, and it's up to you to provide the comparison function.
But for another important, widely used scenario, think about dynamic loading of libraries - by this I mean loading at run time. When you write your program, you have no idea which functions exist in some run-time loaded library. You might read a text string from the user input and then open a user-specified library and execute a user-specified function! The only way you could refer to such function is via a pointer.
Here's a simple example; I hope it convinces you that you could not do away with the pointers!
typedef int (*myfp)(); // function pointer type
const char * libname = get_library_name_from_user();
const char * funname = get_function_name_from_user();
void * libhandle = dlopen(libname, RTLD_NOW); // load the library
myfp fun = (myfp) dlsym(libhandle, funname); // get our mystery function...
const int result = myfp(); // ... and call the function
// -- we have no idea which one!
printf("Your function \"%s:%s\" returns %i.\n", libname, funname, result);
It's for decoupling. Look at sqlite3_exec() - it accepts a callback pointer that is invoked for each row retrieved. SQLite doesn't care of what your callback does, it only needs to know how to call it.
Now you don't need to recompile SQLite each time your callback changes. You may have SQLite compiled once and then just recompile your code and either relink statically or just restart and relink dynamically.
It also avoids name collision. If you have 2 libs, both do sorting and both expect you to define a function called sort_criteria that they can call, how would you sort 2 different objects types with the same function?
It would quickly get complicated following all the if's and switches in the sort_criteria function, with callbacks you can specify your own function (with their nice to interpret name) to those sort functions.

Call back routine

In the Learning OpenCV book, I came to the term callback, and sometimes used with routine as callback routine.
What do we mean when we saycallback?
Thanks.
What is a Callback function?
In simple terms, a Callback function is a function that is not called explicitly by the programmer. Instead, there is some mechanism that continually waits for events to occur, and it will call selected functions in response to particular events.
This mechanism is typically used when an operation(function) takes a long time for execution and the caller of the function does not want to wait till the operation is complete, but does wish to be intimated of the outcome of the operation. Typically, Callback functions help implement such an asynchronous mechanism, wherein the caller registers to get inimated about the result of the time consuming processing and continuous other operations while at a later point of time, the caller gets informed of the result.
A practical example:
Windows event processing:
virtually all windows programs set up an event loop, that makes the program respond to particular events (e.g button presses, selecting a check box, window getting focus) by calling a function. The handy thing is that the programmer can specify what function gets called when (say) a particular button is pressed, even though it is not possible to specify when the button will be pressed. The function that is called is referred to as a callback.
A source Code Illustration:
//warning: Mind compiled code, intended to illustrate the mechanism
#include <map>
typedef void (*Callback)();
std::map<int, Callback> callback_map;
void RegisterCallback(int event, Callback function)
{
callback_map[event] = function;
}
bool finished = false;
int GetNextEvent()
{
static int i = 0;
++i;
if (i == 5) finished = false;
}
void EventProcessor()
{
int event;
while (!finished)
{
event = GetNextEvent();
std::map<int, Callback>::const_iterator it = callback_map.find(event);
if (it != callback_map.end()) // if a callback is registered for event
{
Callback function = *it;
if (function)
{
(*function)();
}
else
{
std::cout << "No callback found\n";
}
}
}
}
void Cat()
{
std::cout << "Cat\n";
}
void Dog()
{
std::cout << "Dog\n";
}
void Bird()
{
std::cout << "Bird\n";
}
int main()
{
RegisterCallBack(1, Cat);
RegisterCallback(2, Dog);
RegisterCallback(3, Cat);
RegisterCallback(4, Bird);
RegisterCallback(5, Cat);
EventProcessor();
return 0;
}
The above would output the following:
Cat
Dog
Cat
Bird
Cat
Hope this helps!
Note:
Imported this answer from one of my old answers here.
"I don't call it by myself, but the system (or some others) will call it". That's callback.
They mean that you pass a pointer to a procedure to OpenCV. This will be called back when something happens. This can e.g. seen at cvSetMouseCallback(). The function referenced by the pointer will be called whenever the mouse moves.
Following the Holywood principle "Don't call us, we call you", a callback is a reference to a function which is passed to another function.
The callback will be called by the function it is given to for instance when data is available or certain processing steps need to be performed.
"Routine" in this context is the same as "function". The term goes back to older languages (like Fortran) that made a difference between functions, that returns values, and (sub)routines that don't.
"Callback" is a technique where you provide a pointer to one of your functions ("routines") to the system/API/framework and the system/API/framework would call it back when it feels like doing so. So a callback routine, or simply a callback, is a function that's intended for such usage.
In strictly object languages (like Java) they typically use listeners and delegates for that. The callback technique, in its C++ form, has the advantage that's it's compatible with non-object-oriented languages like classic C.
EDIT: in the Microsoft C run-time library, this technique is used for qsort() function. The compare argument is a function pointer to a callback routine. It's called by the RTL whenever two array elements need to be compared. It's not a typical example 'cause all the calls to compare happen before the qsort() call returns.
In Win32 API, callbacks are a staple. The window procedure is a prime example - you pass a pointer to it in the WNDCLASS structure, the system calls the procedure back as the message arrive. In this case, the callback routine is invoked long after the RegisterClass() - for the whole lifetime of the window.
In POSIX/Unix/Linux, the signal processing function is an example. See the signal() syscall description.
Callback functions are function which are not called explicitly such functions automatically invoked after some event occurs, for example after pressing​ "ctrl+c" SIGINT signal generated so automatically handler will execute.