Detect when a memory address is written to

I have a byte array that is being used as the system's emulated RAM. I want to make a patch patch for a given cell that detects when it is being recorded and overwrites it instantly. Using a loop like

for (;;) {
    address = x;


has the disadvantage that the minimum possible sleep value seems to be almost identical to the emulated frame length, so it only corrects the address once per frame. Thus, if it was recorded 100 times per frame per game, such a patch would make little sense.

I have some hooks when writing, but they only grab writes by reading executable game code, while I want patches like this to work in any memory area, not just RAM, so I can't rely on interpreting the emulated one too a lot of code (it just doesn't fit all regions I want to fix).

So I need some kind of pragmatic watchpoint, a pointer to an array, and bytes I want to watch the change.


source to share

2 answers

Although C is not an object-oriented language, I would use an object-oriented approach:

  • Wrap the emulated memory up in an opaque pointer that can only be read and written with a specific set of functions (such as memory_write_byte

    and memory_read_byte

  • Let a memory object be a list of function pointers that point to callback functions for handling write events. Whenever a write occurs, call all of these callbacks.
  • The piece of code that wants to control this place in memory can register a callback with the memory object, and whenever the called call is called, it can modify the memory as needed.


I would look into the shared memory ala mmap. Using mmap, you can have the same page shared by two processes, and one of the processes can be read-only.

When a write occurs in this area of ​​memory, a SIGSEGV is generated, which you can catch and then take some action. This uses UNIX terminology, but you can do the same with windows, but it's a bit more.



All Articles