Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading/Writing another process memory in Python running on OS X

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?

like image 668
Dig Avatar asked Sep 05 '26 04:09

Dig


1 Answers

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.

like image 196
abarnert Avatar answered Sep 07 '26 20:09

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!