开发者

Callback on memory access?

开发者 https://www.devze.com 2023-03-10 02:18 出处:网络
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)?

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++.


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.


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


I don't think there is such an API to do so, until you create a wrapper object around the allocated memory and then access to the memory is done through this wrapper object. Then this wrapper object will be able to see all access to the underlying memory.


Well....you could set up a buffer. You could even just set up an array with the allocation. Then set up an if statement that if anything tampers with that array section, for instance if the array was defaulted to have a value of 0 at an index, and now its not, call whatever you want to do.

If you want a lot to happen, and then the program break and respond to that allocation being tampered with, set a boolean and when the value is changed, the boolean goes to true, and have a function posted to check that boolean.

0

精彩评论

暂无评论...
验证码 换一张
取 消