Do WriteProcessMemory and similiar functions invalidate the possibly cached data?

Viewed 196

I have an existing program which I need to communicate with over IPC. I can modify small parts of it but can't add any fancy solutions like shared memory, pipes or sockets. So I'd like to communicate with functions that directly read / write into the programs address space:

  • process_vm_writev on linux
  • WriteProcessMemory on windows
  • mach_vm_write on macOS

If I modify a value in memory with one of these functions is the possibly cached copy of the old value invalidated? If not is a volatile pointer enough to instantly retrieve the new value?

1 Answers

WriteProcessMemory will happily do exactly what it's told. It writes to memory, and the CPU cache(s) will end up in a logically valid (but unspecified) state afterwards.

However, be aware that the other program is not made aware of those writes. And if it has its own idea of caching, including such mechanisms as caching variable values in registers, then those copies will NOT be updated. There is no way in which the OS can know how each language implements such caching mechanisms, but performance concerns dictate that most serious programming languages have mechanisms like this.

If the written-to program uses C or C++ volatile pointers, this is partially mitigated. The compiler cannot eliminate the reads entirely. However, such reads can be reordered with other instructions as long as those are not observable. That might affect their timing, which gives an effect similar to caching - your WriteProcessMemory might be too late.

Related