Memory access callback?

Is there a way to allocate some memory and have some kind of callback (be it a pointer to a function or signal) when the memory is accessed (read or written)?

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

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

+4
source share
4 answers

Yes there is.

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

Note that you will need to use mprotect in the signal handler to actually allow memory access after calling the signal handler, and when you open a window for something else, to access the memory without knowing it, for example, from another thread . This may or may not be a problem depending on your specific use.

+5
source

You can use your own version of the class with a safe pointer, which will wrap the selected pointer, and, by the way, will have an implementation of the dereference operator. However, this will require using it for distribution.

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 // . }; 
+3
source

I don’t think there is such an API for this until you create a wrapper object around the allocated memory, and then the memory will be accessed through this wrapper object. Then this wrapper object will be able to see all access to the main memory.

+1
source

Well ... you can configure the buffer. You can even set up an array with distribution. Then configure the if statement, which, if something obscures this section of the array, for example, if the array had a default value of 0 in the index, and now it is gone, call whatever you want to do.

If you want a lot to happen, and then the program breaks down and responds that the distribution has been tampered with, set the boolean and when the value is changed, the boolean will be true and the function will be sent to verify that the boolean is boolean.

0
source

All Articles