I am working on writing my own malloc
and using the LD_PRELOAD
trick to use it. I need to be able to perform custom functionality for every memory access to the heap, both reads and writes (performance is not a concern, functionality is the goal).
For example, for some code like
int x = A[5];
I would like to be able to trap the read from (A + 5)
and instead of reading from that memory location, return my own custom value to store in x
.
The ideas I have as of now are:
mprotect
away, handling the resulting SIGSEGVs and doing what I need to in the handler. As far as I know, I can access the faulty address invoid *si_addr
, but I'm not sure how to distinguish between a read and a write - and even if I did manage to do so, I'm not sure how to handle writes since I wouldn't know the value to be written within the handler.- Tweak gcc to handle memory accesses specially. From what I have read, understanding gcc code takes a while, and unless its IR/abstract assembly conveniently isolates memory loads/stores, I'm not sure how practical this is.
Any suggestions are appreciated.