6

I have an address like 0x6041f0. I know there's an integer sitting out there. In C, I would have simply done *(int *)0x6041f0 to get the integer value present at that address.

How to achieve the same in Python?

PS: I am writing a Python script that uses the gdb module. The actual program being debugged is in C++. As such a lot of low level manipulation is required.

Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
  • May I ask why/how you ended up having to manipulate an address like `0x6041f0` in your Python program? – TigerhawkT3 Jun 13 '15 at 00:01
  • 1
    Are you working with `gdb.Value` objects? I'm not familiar with the GDB Python API, but from looking at [the docs](https://sourceware.org/gdb/onlinedocs/gdb/Values-From-Inferior.html), it looks like if you have a `gdb.Value` representing an integer that's been cast from a pointer, you'd call the `Value.cast` method to cast it to a pointer, then `Value.dereference` to dereference it. I don't know if there are any considerations that would make it specifically a bad idea to bypass this and use ctypes, but it seems safest to go with the provided API. – user2357112 Jun 13 '15 at 00:12
  • Are you talking about a pointer in the process the python script runs or a pointer in the debugged process? Because that will make a huge difference. – textshell Jun 13 '15 at 00:13
  • @user2357112 You are right. You've outlined the correct way to go about wrt to GDB API. But I wanted to know a generic way of doing it in Python if in case I encounter this situation again in standalone Python. – Pavan Manjunath Jun 13 '15 at 00:14
  • @textshell Disregard the GDB thing. I just added it to give some context as someone asked it. I understand your concern of dereferencing a pointer of a process in some other process not making sense. – Pavan Manjunath Jun 13 '15 at 00:27

1 Answers1

0

Something like this:

$ python
Python 2.7.9 (default, Mar 19 2015, 22:32:11) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> c_int_p = POINTER(c_int)
>>> x = c_int(4)
>>> cast(addressof(x), c_int_p).contents
c_int(4)

With that artbitrary address :)

>>> cast(0x6041f0, c_int_p)
<__main__.LP_c_int object at 0x7f44d06ce050>
>>> cast(0x6041f0, c_int_p).contents
Segmentation fault

See: ctypes for reference

James Mills
  • 18,669
  • 3
  • 49
  • 62