Reputation: 3950
Is is possible to read/write another process memory (not a Python process, and doesn't use share memory or anything) using Python when running on Mac OS X Lion?
For example, I want to launch Safari and monitor several memory addresses used by Safari.
In Windows I've found plenty of solutions, but can it be done on Mac OS X?
Upvotes: 3
Views: 2830
Reputation: 365617
Yes, it can.
Not directly, of course—but you can call any C API you want from Python, either by building a Python extension module in C (or Pyrex, etc.), or by using ctypes from within Python.
The particular C APIs you want to call are task_for_pid and the mach_vm methods. The manpages for these methods don't exist in modern OS X, but the headers are well documented (and so, for that matter, is the source, which is readily available), and you can find manpages for other Mach-based systems online, and there's plenty of third-party documentation.
See https://github.com/abarnert/pymach for a quick proof of concept. You should be able to build it with "python setup.py build_ext --inplace" or "sudo python setup.py install", and then see test.py for a simple example of how to use it.
Keep in mind that in modern OS X, unless you're root, you only have access to child processes. The easiest way around this is to have your script actually launch Safari. Or, if you can't do that, just sudo your script. Alternatively, you can get fancy and use ptrace to attach to a running process, but that's left as an exercise for the reader.
Upvotes: 6