Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback on memory access?

Does there exist a way to allocate some memory and have some sort of callback (be it pointer to a function or signal) when the memory is being accessed (either read or written to)?

For example, if I said allocate 1mb of memory, I would like to have a way to call a function when any of that 1mb is being accessed.

The platform I'm working on is x86 Linux and writing in C/C++.

like image 957
John Avatar asked Jun 02 '11 06:06

John


2 Answers

Yes, there is.

Use the mprotect(2) system call (see: http://linux.die.net/man/2/mprotect) to set read only or no access memory protection on the page and set a SIGEGVsignal handler that will be called when the memory has been accessed.

Note that you will need to use mprotect in your signal handler to actually allow the memory access once your signal handler is called and when you do you open a window to anything else to access the memory without you knowing it, for example from a different thread. This may or may not be an issue depending on your specific usage.

like image 84
gby Avatar answered Sep 21 '22 04:09

gby


You can use your own version of a "safe-pointer"-like class which will wrap the allocated pointer, and by the way will have an implementation of the dereference operator. It will require using it of cause for allocations, though.

Something in these lines:

// based on pretty standard auto_ptr
template <class T> class auto_ptr
{
    T* ptr;
public:
    explicit auto_ptr(T* p = 0) : ptr(p) {}
    ~auto_ptr()                 {delete ptr;}
    T& operator*()              {return *ptr;}   // <<--- add your stuff here
    T* operator->()             {return ptr;} // <<--- and here
    // .
};
like image 24
littleadv Avatar answered Sep 24 '22 04:09

littleadv