feos
feos

Reputation: 1116

Detect when memory address is being written to

I have an array of bytes that is used as an emulated system RAM. I want to make a bullet-proof patch for a given cell, that detects when it's being written to, and overwrites it instantly. Using a loop like

for (;;) {
    address = x;
    sleep(y);
}

has a flaw that there's a minimum possible value for sleep, which appears to be nearly identical to the emulated frame length, so it'd only patch the address once per frame. So, if it's written to 100 times per frame by a game, such a patch will make little sense.

I have some hooks on writing, but those only catch writes by reading the game's code being executed, while I want to make such patches work for any memory region, not just RAM, hence I can't rely on interpreting the emulated code too much (it simply doesn't match for all regions I want to patch).

So I need some pragrammatical watchpoint, having a pointer to the array, and a byte I want to watch change.

Upvotes: 3

Views: 2120

Answers (2)

Clarus
Clarus

Reputation: 2338

I'd look into 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 on this memory region occurs a SIGSEGV would be generated, which you can catch, and then take some sort of an action. This is using UNIX terminology, but you can do the same thing with windows it is just slightly more involved.

Upvotes: 3

David Grayson
David Grayson

Reputation: 87376

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

  1. Wrap the emulated memory up in an opaque pointer that can only be read and written to with a specific set of functions (e.g. memory_write_byte and memory_read_byte).
  2. Make the memory object maintain a list of function pointers that point to callback functions for handling write events. Whenever a write happens, make it call all those callbacks.
  3. The part of the code that wants to monitor that spot in memory can register a callback with the memory object, and whenever the callback gets called it can modify the memory if needed.

Upvotes: 3

Related Questions